No OneTemporary

File Metadata

Created
Sun, Apr 28, 3:09 PM
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/examples/aes-cmac/aes-cmac.cpp b/examples/aes-cmac/aes-cmac.cpp
index 105b2407..ce062f40 100644
--- a/examples/aes-cmac/aes-cmac.cpp
+++ b/examples/aes-cmac/aes-cmac.cpp
@@ -1,318 +1,324 @@
/*
Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <QDebug>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class AESCMACContext : public QCA::MACContext
{
public:
AESCMACContext(QCA::Provider *p) : QCA::MACContext(p, "cmac(aes)")
{
}
~AESCMACContext()
{
}
-
// Helper to left shift an arbitrary length array
// This is heavily based on the example in the I-D.
QCA::SecureArray leftShift(const QCA::SecureArray &array)
{
- // We create an output of the same size as the input
- QCA::SecureArray out(array.size());
- // We handle one byte at a time - this is the high bit
- // from the previous byte.
- int overflow = 0;
-
- // work through each byte.
- for (int i = array.size() -1; i >= 0; --i) {
- // do the left shift on this byte.
- out[i] = array[i] << 1;
- // make the low bit on this byte be the high bit
- // from the previous byte.
- out[i] |= overflow;
- // save the high bit for next time
- overflow = (array[i] & 0x80) ? 1 : 0;
- }
- return out;
+ // We create an output of the same size as the input
+ QCA::SecureArray out(array.size());
+ // We handle one byte at a time - this is the high bit
+ // from the previous byte.
+ int overflow = 0;
+
+ // work through each byte.
+ for (int i = array.size() - 1; i >= 0; --i) {
+ // do the left shift on this byte.
+ out[i] = array[i] << 1;
+ // make the low bit on this byte be the high bit
+ // from the previous byte.
+ out[i] |= overflow;
+ // save the high bit for next time
+ overflow = (array[i] & 0x80) ? 1 : 0;
+ }
+ return out;
}
-
// Helper to XOR two arrays - must be same length
QCA::SecureArray xorArray(const QCA::SecureArray &array1,
- const QCA::SecureArray &array2)
+ const QCA::SecureArray &array2)
{
- if (array1.size() != array2.size())
- // empty array
- return QCA::SecureArray();
+ if (array1.size() != array2.size())
+ // empty array
+ {
+ return QCA::SecureArray();
+ }
- QCA::SecureArray result(array1.size());
+ QCA::SecureArray result(array1.size());
- for (int i = 0; i < array1.size(); ++i)
- result[i] = array1[i] ^ array2[i];
+ for (int i = 0; i < array1.size(); ++i) {
+ result[i] = array1[i] ^ array2[i];
+ }
- return result;
+ return result;
}
-
void setup(const QCA::SymmetricKey &key)
{
- // We might not have a real key, since this can get called
- // from the constructor.
- if (key.size() == 0)
- return;
-
- m_key = key;
- // Generate the subkeys
- QCA::SecureArray const_Zero(16);
- QCA::SecureArray const_Rb(16);
- const_Rb[15] = (char)0x87;
-
- m_X = const_Zero;
- m_residual = QCA::SecureArray();
-
- // Figure 2.2, step 1.
- QCA::Cipher aesObj(QString("aes128"),
- QCA::Cipher::ECB, QCA::Cipher::DefaultPadding,
- QCA::Encode, key);
- QCA::SecureArray L = aesObj.process(const_Zero);
-
- // Figure 2.2, step 2
- if (0 == (L[0] & 0x80))
- m_k1 = leftShift(L);
- else
- m_k1 = xorArray(leftShift(L), const_Rb);
-
- // Figure 2.2, step 3
- if (0 == (m_k1[0] & 0x80))
- m_k2 = leftShift(m_k1);
- else
- m_k2 = xorArray(leftShift(m_k1), const_Rb);
+ // We might not have a real key, since this can get called
+ // from the constructor.
+ if (key.size() == 0) {
+ return;
+ }
+
+ m_key = key;
+ // Generate the subkeys
+ QCA::SecureArray const_Zero(16);
+ QCA::SecureArray const_Rb(16);
+ const_Rb[15] = (char)0x87;
+
+ m_X = const_Zero;
+ m_residual = QCA::SecureArray();
+
+ // Figure 2.2, step 1.
+ QCA::Cipher aesObj(QString("aes128"),
+ QCA::Cipher::ECB, QCA::Cipher::DefaultPadding,
+ QCA::Encode, key);
+ QCA::SecureArray L = aesObj.process(const_Zero);
+
+ // Figure 2.2, step 2
+ if (0 == (L[0] & 0x80)) {
+ m_k1 = leftShift(L);
+ } else {
+ m_k1 = xorArray(leftShift(L), const_Rb);
+ }
+
+ // Figure 2.2, step 3
+ if (0 == (m_k1[0] & 0x80)) {
+ m_k2 = leftShift(m_k1);
+ } else {
+ m_k2 = xorArray(leftShift(m_k1), const_Rb);
+ }
}
QCA::Provider::Context *clone() const
{
return new AESCMACContext(*this);
}
void clear()
{
- setup(m_key);
+ setup(m_key);
}
QCA::KeyLength keyLength() const
{
return QCA::KeyLength(16, 16, 1);
}
// This is a bit different to the way the I-D does it,
// to allow for multiple update() calls.
void update(const QCA::MemoryRegion &a)
{
- QCA::SecureArray bytesToProcess = m_residual + a;
- int blockNum;
- // note that we don't want to do the last full block here, because
- // it needs special treatment in final().
- for (blockNum = 0; blockNum < ((bytesToProcess.size()-1)/16); ++blockNum) {
- // copy a block of data
- QCA::SecureArray thisBlock(16);
- for (int yalv = 0; yalv < 16; ++yalv)
- thisBlock[yalv] = bytesToProcess[blockNum*16 + yalv];
-
- m_Y = xorArray(m_X, thisBlock);
-
- QCA::Cipher aesObj(QString("aes128"),
- QCA::Cipher::ECB, QCA::Cipher::DefaultPadding,
- QCA::Encode, m_key);
- m_X = aesObj.process(m_Y);
- }
- // This can be between 1 and 16
- int numBytesLeft = bytesToProcess.size() - 16*blockNum;
- // we copy the left over part
- m_residual.resize(numBytesLeft);
- for(int yalv = 0; yalv < numBytesLeft; ++yalv)
- m_residual[yalv] = bytesToProcess[blockNum*16 + yalv];
+ QCA::SecureArray bytesToProcess = m_residual + a;
+ int blockNum;
+ // note that we don't want to do the last full block here, because
+ // it needs special treatment in final().
+ for (blockNum = 0; blockNum < ((bytesToProcess.size() - 1) / 16); ++blockNum) {
+ // copy a block of data
+ QCA::SecureArray thisBlock(16);
+ for (int yalv = 0; yalv < 16; ++yalv) {
+ thisBlock[yalv] = bytesToProcess[blockNum * 16 + yalv];
+ }
+
+ m_Y = xorArray(m_X, thisBlock);
+
+ QCA::Cipher aesObj(QString("aes128"),
+ QCA::Cipher::ECB, QCA::Cipher::DefaultPadding,
+ QCA::Encode, m_key);
+ m_X = aesObj.process(m_Y);
+ }
+ // This can be between 1 and 16
+ int numBytesLeft = bytesToProcess.size() - 16 * blockNum;
+ // we copy the left over part
+ m_residual.resize(numBytesLeft);
+ for (int yalv = 0; yalv < numBytesLeft; ++yalv) {
+ m_residual[yalv] = bytesToProcess[blockNum * 16 + yalv];
+ }
}
- void final( QCA::MemoryRegion *out)
+ void final(QCA::MemoryRegion *out)
{
- QCA::SecureArray lastBlock;
- int numBytesLeft = m_residual.size();
-
- if ( numBytesLeft != 16 ) {
- // no full block, so we have to pad.
- m_residual.resize(16);
- m_residual[numBytesLeft] = (char)0x80;
- lastBlock = xorArray(m_residual, m_k2);
- } else {
- // this is a full block - no padding
- lastBlock = xorArray(m_residual, m_k1);
- }
- m_Y = xorArray(m_X, lastBlock);
- QCA::Cipher aesObj(QString("aes128"),
- QCA::Cipher::ECB, QCA::Cipher::DefaultPadding,
- QCA::Encode, m_key);
- *out = aesObj.process(m_Y);
+ QCA::SecureArray lastBlock;
+ int numBytesLeft = m_residual.size();
+
+ if (numBytesLeft != 16) {
+ // no full block, so we have to pad.
+ m_residual.resize(16);
+ m_residual[numBytesLeft] = (char)0x80;
+ lastBlock = xorArray(m_residual, m_k2);
+ } else {
+ // this is a full block - no padding
+ lastBlock = xorArray(m_residual, m_k1);
+ }
+ m_Y = xorArray(m_X, lastBlock);
+ QCA::Cipher aesObj(QString("aes128"),
+ QCA::Cipher::ECB, QCA::Cipher::DefaultPadding,
+ QCA::Encode, m_key);
+ *out = aesObj.process(m_Y);
}
protected:
// first subkey
QCA::SecureArray m_k1;
// second subkey
QCA::SecureArray m_k2;
// main key
QCA::SecureArray m_key;
// state
QCA::SecureArray m_X;
QCA::SecureArray m_Y;
// partial block that we can't do yet
QCA::SecureArray m_residual;
};
class ClientSideProvider : public QCA::Provider
{
public:
- int qcaVersion() const
- {
- return QCA_VERSION;
- }
+ int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
- QString name() const
- {
- return "exampleClientSideProvider";
- }
+ QString name() const
+ {
+ return "exampleClientSideProvider";
+ }
- QStringList features() const
- {
- QStringList list;
- list += "cmac(aes)";
- // you can add more features in here, if you have some.
- return list;
- }
+ QStringList features() const
+ {
+ QStringList list;
+ list += "cmac(aes)";
+ // you can add more features in here, if you have some.
+ return list;
+ }
- Provider::Context *createContext(const QString &type)
- {
- if(type == "cmac(aes)")
- return new AESCMACContext(this);
- // else if (type == some other feature)
- // return some other context.
- else
- return 0;
+ Provider::Context *createContext(const QString &type)
+ {
+ if (type == "cmac(aes)") {
+ return new AESCMACContext(this);
}
+ // else if (type == some other feature)
+ // return some other context.
+ else {
+ return 0;
+ }
+ }
};
-
// AES CMAC is a Message Authentication Code based on a block cipher
// instead of the more normal keyed hash.
// See RFC 4493 "The AES-CMAC Algorithm"
class AES_CMAC: public QCA::MessageAuthenticationCode
{
public:
AES_CMAC(const QCA::SymmetricKey &key = QCA::SymmetricKey(),
- const QString &provider = QString()):
- QCA::MessageAuthenticationCode( "cmac(aes)", key, provider)
+ const QString &provider = QString()):
+ QCA::MessageAuthenticationCode("cmac(aes)", key, provider)
{}
};
-
int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
qDebug() << "This example shows AES CMAC";
QCoreApplication app(argc, argv);
- if( ! QCA::isSupported("aes128-ecb") ) {
- qDebug() << "AES not supported!";
+ if (! QCA::isSupported("aes128-ecb")) {
+ qDebug() << "AES not supported!";
}
- if ( QCA::insertProvider(new ClientSideProvider, 0) )
- qDebug() << "Inserted our provider";
- else
- qDebug() << "our provider could not be added";
+ if (QCA::insertProvider(new ClientSideProvider, 0)) {
+ qDebug() << "Inserted our provider";
+ } else {
+ qDebug() << "our provider could not be added";
+ }
// We should check AES CMAC is supported before using it.
- if( ! QCA::isSupported("cmac(aes)") ) {
- qDebug() << "AES CMAC not supported!";
+ if (! QCA::isSupported("cmac(aes)")) {
+ qDebug() << "AES CMAC not supported!";
} else {
- // create the required object
- AES_CMAC cmacObject;
-
- // create the key
- QCA::SymmetricKey key(QCA::hexToArray("2b7e151628aed2a6abf7158809cf4f3c"));
-
- // set the MAC to use the key
- cmacObject.setup(key);
-
- QCA::SecureArray message = QCA::hexToArray("6bc1bee22e409f96e93d7e117393172a"
- "ae2d8a571e03ac9c9eb76fac45af8e51"
- "30c81c46a35ce411e5fbc1191a0a52ef"
- "f69f2445df4f9b17ad2b417be66c3710");
- QCA::SecureArray message1(message);
- message1.resize(0);
- qDebug();
- qDebug() << "Message1: " << QCA::arrayToHex(message1.toByteArray());
- qDebug() << "Expecting: bb1d6929e95937287fa37d129b756746";
- qDebug() << "AES-CMAC: " << QCA::arrayToHex(cmacObject.process(message1).toByteArray());
-
- cmacObject.clear();
- QCA::SecureArray message2(message);
- message2.resize(16);
- qDebug();
- qDebug() << "Message2: " << QCA::arrayToHex(message2.toByteArray());
- qDebug() << "Expecting: 070a16b46b4d4144f79bdd9dd04a287c";
- qDebug() << "AES-CMAC: " << QCA::arrayToHex(cmacObject.process(message2).toByteArray());
-
- cmacObject.clear();
- QCA::SecureArray message3(message);
- message3.resize(40);
- qDebug();
- qDebug() << "Message3: " << QCA::arrayToHex(message3.toByteArray());
- qDebug() << "Expecting: dfa66747de9ae63030ca32611497c827";
- qDebug() << "AES-CMAC " << QCA::arrayToHex(cmacObject.process(message3).toByteArray());
-
- cmacObject.clear();
- QCA::SecureArray message4(message);
- message4.resize(64);
- qDebug();
- qDebug() << "Message4: " << QCA::arrayToHex(message4.toByteArray());
- qDebug() << "Expecting: 51f0bebf7e3b9d92fc49741779363cfe";
- qDebug() << "AES-CMAC: " << QCA::arrayToHex(cmacObject.process(message4).toByteArray());
+ // create the required object
+ AES_CMAC cmacObject;
+
+ // create the key
+ QCA::SymmetricKey key(QCA::hexToArray("2b7e151628aed2a6abf7158809cf4f3c"));
+
+ // set the MAC to use the key
+ cmacObject.setup(key);
+
+ QCA::SecureArray message = QCA::hexToArray("6bc1bee22e409f96e93d7e117393172a"
+ "ae2d8a571e03ac9c9eb76fac45af8e51"
+ "30c81c46a35ce411e5fbc1191a0a52ef"
+ "f69f2445df4f9b17ad2b417be66c3710");
+ QCA::SecureArray message1(message);
+ message1.resize(0);
+ qDebug();
+ qDebug() << "Message1: " << QCA::arrayToHex(message1.toByteArray());
+ qDebug() << "Expecting: bb1d6929e95937287fa37d129b756746";
+ qDebug() << "AES-CMAC: " << QCA::arrayToHex(cmacObject.process(message1).toByteArray());
+
+ cmacObject.clear();
+ QCA::SecureArray message2(message);
+ message2.resize(16);
+ qDebug();
+ qDebug() << "Message2: " << QCA::arrayToHex(message2.toByteArray());
+ qDebug() << "Expecting: 070a16b46b4d4144f79bdd9dd04a287c";
+ qDebug() << "AES-CMAC: " << QCA::arrayToHex(cmacObject.process(message2).toByteArray());
+
+ cmacObject.clear();
+ QCA::SecureArray message3(message);
+ message3.resize(40);
+ qDebug();
+ qDebug() << "Message3: " << QCA::arrayToHex(message3.toByteArray());
+ qDebug() << "Expecting: dfa66747de9ae63030ca32611497c827";
+ qDebug() << "AES-CMAC " << QCA::arrayToHex(cmacObject.process(message3).toByteArray());
+
+ cmacObject.clear();
+ QCA::SecureArray message4(message);
+ message4.resize(64);
+ qDebug();
+ qDebug() << "Message4: " << QCA::arrayToHex(message4.toByteArray());
+ qDebug() << "Expecting: 51f0bebf7e3b9d92fc49741779363cfe";
+ qDebug() << "AES-CMAC: " << QCA::arrayToHex(cmacObject.process(message4).toByteArray());
}
return 0;
}
diff --git a/examples/base64test/base64test.cpp b/examples/base64test/base64test.cpp
index 113de5b8..ef35979d 100644
--- a/examples/base64test/base64test.cpp
+++ b/examples/base64test/base64test.cpp
@@ -1,71 +1,71 @@
/*
Copyright (C) 2004-2005 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <iostream>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
- QCoreApplication(argc, argv);
+ QCoreApplication(argc, argv);
- // the Initializer object sets things up, and
- // also does cleanup when it goes out of scope
- QCA::Initializer init;
+ // the Initializer object sets things up, and
+ // also does cleanup when it goes out of scope
+ QCA::Initializer init;
- // we use the first argument as the data to encode
- // if an argument is provided. Use "hello" if no argument
- QByteArray arg; // empty array
- arg.append((argc >= 2) ? argv[1] : "hello");
+ // we use the first argument as the data to encode
+ // if an argument is provided. Use "hello" if no argument
+ QByteArray arg; // empty array
+ arg.append((argc >= 2) ? argv[1] : "hello");
- // create our object, which does encoding by default
- // QCA::Base64 encoder(QCA::Encode); is equivalent
- QCA::Base64 encoder;
+ // create our object, which does encoding by default
+ // QCA::Base64 encoder(QCA::Encode); is equivalent
+ QCA::Base64 encoder;
- // This does the actual conversion (encoding).
- // You might prefer to use encoder.encode(); and have
- // it return a QCA::SecureArray, depending on your needs
- QString encoded = encoder.arrayToString(arg);
+ // This does the actual conversion (encoding).
+ // You might prefer to use encoder.encode(); and have
+ // it return a QCA::SecureArray, depending on your needs
+ QString encoded = encoder.arrayToString(arg);
- std::cout << arg.data() << " in base64 encoding is ";
- std::cout << encoded.toLatin1().data() << std::endl;
+ std::cout << arg.data() << " in base64 encoding is ";
+ std::cout << encoded.toLatin1().data() << std::endl;
- // This time, we'll create an object to decode base64. We
- // could also have reused the existing object, calling
- // clear(); and setup(QCA::Decode); on it.
- QCA::Base64 decoder(QCA::Decode);
+ // This time, we'll create an object to decode base64. We
+ // could also have reused the existing object, calling
+ // clear(); and setup(QCA::Decode); on it.
+ QCA::Base64 decoder(QCA::Decode);
- // This time, we convert a QString into a QString
- QString decoded = decoder.decodeString(encoded);
+ // This time, we convert a QString into a QString
+ QString decoded = decoder.decodeString(encoded);
- std::cout << encoded.toLatin1().data() << " decoded from base64 is ";
- std::cout << decoded.toLatin1().data() << std::endl;
+ std::cout << encoded.toLatin1().data() << " decoded from base64 is ";
+ std::cout << decoded.toLatin1().data() << std::endl;
- return 0;
+ return 0;
}
diff --git a/examples/certtest/certtest.cpp b/examples/certtest/certtest.cpp
index abd9d77d..e0394305 100644
--- a/examples/certtest/certtest.cpp
+++ b/examples/certtest/certtest.cpp
@@ -1,176 +1,173 @@
/*
Copyright (C) 2003 Justin Karneges <justin@affinix.com>
Copyright (C) 2005 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-
#include <QtCrypto>
#include <QCoreApplication>
#include <iostream>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
// dump out information about some part of the certificate
// we use this same approach for information about the subject
// of the certificate, and also about the issuer of the certificate
-static void dumpCertificateInfo( QCA::CertificateInfo info)
+static void dumpCertificateInfo(QCA::CertificateInfo info)
{
std::cout << " Organization: " << std::endl;
// Note that a single certificate can apply to more than one
// organisation. QCA::Certificate is a multimap, so when you
// ask for the values associated with a parameter, it returns
// a list.
QList<QString> orgInfoList = info.values(QCA::Organization);
// foreach() interates over each value in the list, and we dump
// out each value. Note that is uncommon for a certificate to
// actually contain multiple values for a single parameter.
QString organization;
- foreach( organization, orgInfoList ) {
- std::cout << " " << qPrintable(organization) << std::endl;
+ foreach (organization, orgInfoList) {
+ std::cout << " " << qPrintable(organization) << std::endl;
}
std::cout << " Country: " << std::endl;
// As above, however this shows a more compact way to represent
// the iteration and output.
- foreach( QString country, info.values(QCA::Country) ) {
- std::cout << " " << qPrintable(country) << std::endl;
+ foreach (QString country, info.values(QCA::Country)) {
+ std::cout << " " << qPrintable(country) << std::endl;
}
}
// This is just a convenience routine
-static void dumpSubjectInfo( QCA::CertificateInfo subject)
+static void dumpSubjectInfo(QCA::CertificateInfo subject)
{
std::cout << "Subject: " << std::endl;
- dumpCertificateInfo( subject );
+ dumpCertificateInfo(subject);
}
-
// This is just a convenience routine
-static void dumpIssuerInfo( QCA::CertificateInfo issuer)
+static void dumpIssuerInfo(QCA::CertificateInfo issuer)
{
std::cout << "Issuer: " << std::endl;
- dumpCertificateInfo( issuer );
+ dumpCertificateInfo(issuer);
}
-
-int main(int argc, char** argv)
+int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication app(argc, argv);
// We need to ensure that we have certificate handling support
- if ( !QCA::isSupported( "cert" ) ) {
- std::cout << "Sorry, no PKI certificate support" << std::endl;
- return 1;
+ if (!QCA::isSupported("cert")) {
+ std::cout << "Sorry, no PKI certificate support" << std::endl;
+ return 1;
}
// We are going to work with a number of certificates, and a
// QList is a great template class for that
QList<QCA::Certificate> certlist;
// We do two different cases - if we provide an argument, it is taken
// as a filename to read the keys from. If there is no argument, we just
// read from the system store certificates.
if (argc >= 2) {
- // we are going to read the certificates in using a single call
- // which requires a CertificateCollection.
- QCA::CertificateCollection filecerts;
- // The conversion can be tested (although you don't have to) to find out if it
- // worked.
- QCA::ConvertResult importResult;
- // This imports all the PEM encoded certificates from the file specified as the argument
- // Note that you pass in a pointer to the result argument.
- filecerts = QCA::CertificateCollection::fromFlatTextFile( argv[1], &importResult );
- if ( QCA::ConvertGood == importResult) {
- std::cout << "Import succeeded" << std::endl;
- // this turns the CertificateCollection into a QList of Certificate objects
- certlist = filecerts.certificates();
- }
+ // we are going to read the certificates in using a single call
+ // which requires a CertificateCollection.
+ QCA::CertificateCollection filecerts;
+ // The conversion can be tested (although you don't have to) to find out if it
+ // worked.
+ QCA::ConvertResult importResult;
+ // This imports all the PEM encoded certificates from the file specified as the argument
+ // Note that you pass in a pointer to the result argument.
+ filecerts = QCA::CertificateCollection::fromFlatTextFile(argv[1], &importResult);
+ if (QCA::ConvertGood == importResult) {
+ std::cout << "Import succeeded" << std::endl;
+ // this turns the CertificateCollection into a QList of Certificate objects
+ certlist = filecerts.certificates();
+ }
} else {
- // we have no arguments, so just use the system certificates
- if ( !QCA::haveSystemStore() ) {
- std::cout << "System certificates not available" << std::endl;
- return 2;
- }
+ // we have no arguments, so just use the system certificates
+ if (!QCA::haveSystemStore()) {
+ std::cout << "System certificates not available" << std::endl;
+ return 2;
+ }
- // Similar to above, except we just want the system certificates
- QCA::CertificateCollection systemcerts = QCA::systemStore();
+ // Similar to above, except we just want the system certificates
+ QCA::CertificateCollection systemcerts = QCA::systemStore();
- // this turns the CertificateCollection into a QList of Certificate objects
- certlist = systemcerts.certificates();
+ // this turns the CertificateCollection into a QList of Certificate objects
+ certlist = systemcerts.certificates();
}
std::cout << "Number of certificates: " << certlist.count() << std::endl;
QCA::Certificate cert;
foreach (cert, certlist) {
- std::cout << "Serial Number:";
- // the serial number of the certificate is a QCA::BigInteger, but we can
- // just convert it to a string, and then output it.
- std::cout << qPrintable(cert.serialNumber().toString()) << std::endl;
-
- // The subject information shows properties of who the certificate
- // applies to. See the convenience routines above.
- dumpSubjectInfo( cert.subjectInfo() );
-
- // The issuer information shows properties of who the certificate
- // was signed by. See the convenience routines above.
- dumpIssuerInfo( cert.issuerInfo() );
-
- // Test if the certificate can be used as a certificate authority
- if ( cert.isCA() ) {
- std::cout << "Is certificate authority" << std::endl;
- } else {
- std::cout << "Is not a certificate authority" << std::endl;
- }
-
- // Test if the certificate is self-signed.
- if (cert.isSelfSigned() ) {
- std::cout << "Self signed" << std::endl;
- } else {
- std::cout << "Is not self-signed!!!" << std::endl;
- }
-
- // Certificate are only valid between specific dates. We can get the dates
- // (as a QDateTime) using a couple of calls
- std::cout << "Valid from " << qPrintable(cert.notValidBefore().toString());
- std::cout << ", until " << qPrintable(cert.notValidAfter().toString());
- std::cout << std::endl;
-
- // You can get the certificate in PEM encoding with a simple toPEM() call
- std::cout << "PEM:" << std::endl;
- std::cout << qPrintable(cert.toPEM());
- std::cout << std::endl << std::endl;
- }
+ std::cout << "Serial Number:";
+ // the serial number of the certificate is a QCA::BigInteger, but we can
+ // just convert it to a string, and then output it.
+ std::cout << qPrintable(cert.serialNumber().toString()) << std::endl;
+
+ // The subject information shows properties of who the certificate
+ // applies to. See the convenience routines above.
+ dumpSubjectInfo(cert.subjectInfo());
+
+ // The issuer information shows properties of who the certificate
+ // was signed by. See the convenience routines above.
+ dumpIssuerInfo(cert.issuerInfo());
+
+ // Test if the certificate can be used as a certificate authority
+ if (cert.isCA()) {
+ std::cout << "Is certificate authority" << std::endl;
+ } else {
+ std::cout << "Is not a certificate authority" << std::endl;
+ }
+
+ // Test if the certificate is self-signed.
+ if (cert.isSelfSigned()) {
+ std::cout << "Self signed" << std::endl;
+ } else {
+ std::cout << "Is not self-signed!!!" << std::endl;
+ }
+
+ // Certificate are only valid between specific dates. We can get the dates
+ // (as a QDateTime) using a couple of calls
+ std::cout << "Valid from " << qPrintable(cert.notValidBefore().toString());
+ std::cout << ", until " << qPrintable(cert.notValidAfter().toString());
+ std::cout << std::endl;
+
+ // You can get the certificate in PEM encoding with a simple toPEM() call
+ std::cout << "PEM:" << std::endl;
+ std::cout << qPrintable(cert.toPEM());
+ std::cout << std::endl << std::endl;
+ }
return 0;
}
diff --git a/examples/ciphertest/ciphertest.cpp b/examples/ciphertest/ciphertest.cpp
index 448d9147..c86d3339 100644
--- a/examples/ciphertest/ciphertest.cpp
+++ b/examples/ciphertest/ciphertest.cpp
@@ -1,133 +1,132 @@
/*
Copyright (C) 2003 Justin Karneges <justin@affinix.com>
Copyright (C) 2005-2006 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <stdio.h>
#include <QCoreApplication>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication app(argc, argv);
// we use the first argument if provided, or
// use "hello" if no arguments
QCA::SecureArray arg = (argc >= 2) ? argv[1] : "hello";
// AES128 testing
- if(!QCA::isSupported("aes128-cbc-pkcs7"))
- printf("AES128-CBC not supported!\n");
- else {
- // Create a random key - you'd probably use one from another
- // source in a real application
- QCA::SymmetricKey key(16);
-
- // Create a random initialisation vector - you need this
- // value to decrypt the resulting cipher text, but it
- // need not be kept secret (unlike the key).
- QCA::InitializationVector iv(16);
-
- // create a 128 bit AES cipher object using Cipher Block Chaining (CBC) mode
- QCA::Cipher cipher(QString("aes128"),QCA::Cipher::CBC,
- // use Default padding, which is equivalent to PKCS7 for CBC
- QCA::Cipher::DefaultPadding,
- // this object will encrypt
- QCA::Encode,
- key, iv);
-
- // we use the cipher object to encrypt the argument we passed in
- // the result of that is returned - note that if there is less than
- // 16 bytes (1 block), then nothing will be returned - it is buffered
- // update() can be called as many times as required.
- QCA::SecureArray u = cipher.update(arg);
-
- // We need to check if that update() call worked.
- if (!cipher.ok()) {
- printf("Update failed\n");
- }
- // output the results of that stage
- printf("AES128 encryption of %s is [%s]\n",
- arg.data(),
- qPrintable(QCA::arrayToHex(u.toByteArray())) );
-
-
- // Because we are using PKCS7 padding, we need to output the final (padded) block
- // Note that we should always call final() even with no padding, to clean up
- QCA::SecureArray f = cipher.final();
-
- // Check if the final() call worked
- if (!cipher.ok()) {
- printf("Final failed\n");
- }
- // and output the resulting block. The ciphertext is the results of update()
- // and the result of final()
- printf("Final block for AES128 encryption is [0x%s]\n", qPrintable(QCA::arrayToHex(f.toByteArray())) );
-
- // re-use the Cipher t decrypt. We need to use the same key and
- // initialisation vector as in the encryption.
- cipher.setup( QCA::Decode, key, iv );
-
- // Build a single cipher text array. You could also call update() with
- // each block as you receive it, if that is more useful.
- QCA::SecureArray cipherText = u.append(f);
-
- // take that cipher text, and decrypt it
- QCA::SecureArray plainText = cipher.update(cipherText);
-
- // check if the update() call worked
- if (!cipher.ok()) {
- printf("Update failed\n");
- }
-
- // output results
- printf("Decryption using AES128 of [0x%s] is %s\n",
- qPrintable(QCA::arrayToHex(cipherText.toByteArray())), plainText.data());
-
- // Again we need to call final(), to get the last block (with its padding removed)
- plainText = cipher.final();
-
- // check if the final() call worked
- if (!cipher.ok()) {
- printf("Final failed\n");
- }
-
- // output results
- printf("Final decryption block using AES128 is %s\n", plainText.data());
- // instead of update() and final(), you can do the whole thing
- // in one step, using process()
- printf("One step decryption using AES128: %s\n",
- QCA::SecureArray(cipher.process(cipherText)).data() );
+ if (!QCA::isSupported("aes128-cbc-pkcs7")) {
+ printf("AES128-CBC not supported!\n");
+ } else {
+ // Create a random key - you'd probably use one from another
+ // source in a real application
+ QCA::SymmetricKey key(16);
+
+ // Create a random initialisation vector - you need this
+ // value to decrypt the resulting cipher text, but it
+ // need not be kept secret (unlike the key).
+ QCA::InitializationVector iv(16);
+
+ // create a 128 bit AES cipher object using Cipher Block Chaining (CBC) mode
+ QCA::Cipher cipher(QString("aes128"), QCA::Cipher::CBC,
+ // use Default padding, which is equivalent to PKCS7 for CBC
+ QCA::Cipher::DefaultPadding,
+ // this object will encrypt
+ QCA::Encode,
+ key, iv);
+
+ // we use the cipher object to encrypt the argument we passed in
+ // the result of that is returned - note that if there is less than
+ // 16 bytes (1 block), then nothing will be returned - it is buffered
+ // update() can be called as many times as required.
+ QCA::SecureArray u = cipher.update(arg);
+
+ // We need to check if that update() call worked.
+ if (!cipher.ok()) {
+ printf("Update failed\n");
+ }
+ // output the results of that stage
+ printf("AES128 encryption of %s is [%s]\n",
+ arg.data(),
+ qPrintable(QCA::arrayToHex(u.toByteArray())));
+
+ // Because we are using PKCS7 padding, we need to output the final (padded) block
+ // Note that we should always call final() even with no padding, to clean up
+ QCA::SecureArray f = cipher.final();
+
+ // Check if the final() call worked
+ if (!cipher.ok()) {
+ printf("Final failed\n");
+ }
+ // and output the resulting block. The ciphertext is the results of update()
+ // and the result of final()
+ printf("Final block for AES128 encryption is [0x%s]\n", qPrintable(QCA::arrayToHex(f.toByteArray())));
+
+ // re-use the Cipher t decrypt. We need to use the same key and
+ // initialisation vector as in the encryption.
+ cipher.setup(QCA::Decode, key, iv);
+
+ // Build a single cipher text array. You could also call update() with
+ // each block as you receive it, if that is more useful.
+ QCA::SecureArray cipherText = u.append(f);
+
+ // take that cipher text, and decrypt it
+ QCA::SecureArray plainText = cipher.update(cipherText);
+
+ // check if the update() call worked
+ if (!cipher.ok()) {
+ printf("Update failed\n");
+ }
+
+ // output results
+ printf("Decryption using AES128 of [0x%s] is %s\n",
+ qPrintable(QCA::arrayToHex(cipherText.toByteArray())), plainText.data());
+
+ // Again we need to call final(), to get the last block (with its padding removed)
+ plainText = cipher.final();
+
+ // check if the final() call worked
+ if (!cipher.ok()) {
+ printf("Final failed\n");
+ }
+
+ // output results
+ printf("Final decryption block using AES128 is %s\n", plainText.data());
+ // instead of update() and final(), you can do the whole thing
+ // in one step, using process()
+ printf("One step decryption using AES128: %s\n",
+ QCA::SecureArray(cipher.process(cipherText)).data());
}
return 0;
}
diff --git a/examples/cms/cmsexample.cpp b/examples/cms/cmsexample.cpp
index 2d8f54e8..a059257a 100644
--- a/examples/cms/cmsexample.cpp
+++ b/examples/cms/cmsexample.cpp
@@ -1,215 +1,208 @@
/*
Copyright (C) 2003 Justin Karneges <justin@affinix.com>
Copyright (C) 2005-2006 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-
#include <QtCrypto>
#include <QCoreApplication>
#include <QDebug>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
-int main(int argc, char** argv)
+int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication app(argc, argv);
// We need to ensure that we have certificate handling support
- if ( !QCA::isSupported( "cert" ) ) {
- qWarning() << "Sorry, no PKI certificate support";
- return 1;
+ if (!QCA::isSupported("cert")) {
+ qWarning() << "Sorry, no PKI certificate support";
+ return 1;
}
// Read in a public key cert
// you could also build this using the fromPEMFile() method
- QCA::Certificate pubCert( "User.pem" );
- if ( pubCert.isNull() ) {
- qWarning() << "Sorry, could not import public key certificate";
- return 1;
+ QCA::Certificate pubCert("User.pem");
+ if (pubCert.isNull()) {
+ qWarning() << "Sorry, could not import public key certificate";
+ return 1;
}
// We are building the certificate into a SecureMessageKey object, via a
// CertificateChain
QCA::SecureMessageKey secMsgKey;
QCA::CertificateChain chain;
chain += pubCert;
- secMsgKey.setX509CertificateChain( chain );
+ secMsgKey.setX509CertificateChain(chain);
// build up a SecureMessage object, based on our public key certificate
- if ( !QCA::isSupported( "cms" ) ) {
- qWarning() << "Sorry, no CMS support";
- return 1;
+ if (!QCA::isSupported("cms")) {
+ qWarning() << "Sorry, no CMS support";
+ return 1;
}
QCA::CMS cms;
QCA::SecureMessage msg(&cms);
msg.setRecipient(secMsgKey);
// Some plain text - we use the first command line argument if provided
QByteArray plainText = (argc >= 2) ? argv[1] : "What do ya want for nuthin'";
// Now use the SecureMessage object to encrypt the plain text.
msg.startEncrypt();
msg.update(plainText);
msg.end();
// I think it is reasonable to wait for 1 second for this
msg.waitForFinished(1000);
// check to see if it worked
- if(!msg.success())
- {
- qWarning() << "Error encrypting: " << msg.errorCode();
- return 1;
+ if (!msg.success()) {
+ qWarning() << "Error encrypting: " << msg.errorCode();
+ return 1;
}
// get the result
QByteArray cipherText = msg.read();
QCA::Base64 enc;
qDebug() << "'" << plainText.data() << "' encrypts to (in base 64): ";
- qDebug() << enc.arrayToString( cipherText );
+ qDebug() << enc.arrayToString(cipherText);
qDebug() << "Message uses" << msg.hashName() << "hashing algorithm";
qDebug();
// Show we can decrypt it with the private key
// Read in a private key
QCA::PrivateKey privKey;
QCA::ConvertResult convRes;
QCA::SecureArray passPhrase = "start";
- privKey = QCA::PrivateKey::fromPEMFile( "Userkey.pem", passPhrase, &convRes );
- if ( convRes != QCA::ConvertGood ) {
- qWarning() << "Sorry, could not import Private Key";
- return 1;
+ privKey = QCA::PrivateKey::fromPEMFile("Userkey.pem", passPhrase, &convRes);
+ if (convRes != QCA::ConvertGood) {
+ qWarning() << "Sorry, could not import Private Key";
+ return 1;
}
QCA::SecureMessageKey secMsgKey2;
// needed?
- secMsgKey2.setX509CertificateChain( chain );
+ secMsgKey2.setX509CertificateChain(chain);
secMsgKey2.setX509PrivateKey(privKey);
QCA::SecureMessageKeyList privKeyList;
privKeyList += secMsgKey2;
// build up a SecureMessage object, based on the private key
// you could re-use the existing QCA::CMS object (cms), but
// this example simulates encryption and one end, and decryption
// at the other
QCA::CMS anotherCms;
- anotherCms.setPrivateKeys( privKeyList );
+ anotherCms.setPrivateKeys(privKeyList);
- QCA::SecureMessage msg2( &anotherCms );
+ QCA::SecureMessage msg2(&anotherCms);
msg2.startDecrypt();
- msg2.update( cipherText );
+ msg2.update(cipherText);
msg2.end();
// I think it is reasonable to wait for 1 second for this
msg2.waitForFinished(1000);
// check to see if it worked
- if(!msg2.success())
- {
- qWarning() << "Error encrypting: " << msg2.errorCode();
- return 1;
+ if (!msg2.success()) {
+ qWarning() << "Error encrypting: " << msg2.errorCode();
+ return 1;
}
QCA::SecureArray plainTextResult = msg2.read();
- qDebug() << enc.arrayToString( cipherText )
- << " (in base 64) decrypts to: "
- << plainTextResult.data();
+ qDebug() << enc.arrayToString(cipherText)
+ << " (in base 64) decrypts to: "
+ << plainTextResult.data();
if (msg2.wasSigned()) {
- qDebug() << "Message was signed at "
- << msg2.signer().timestamp();
+ qDebug() << "Message was signed at "
+ << msg2.signer().timestamp();
} else {
- qDebug() << "Message was not signed";
+ qDebug() << "Message was not signed";
}
qDebug() << "Message used" << msg2.hashName() << "hashing algorithm";
qDebug();
// Now we want to try a signature
QByteArray text("Got your message");
// Re-use the CMS and SecureMessageKeyList objects from the decrypt...
- QCA::SecureMessage signing( &anotherCms );
+ QCA::SecureMessage signing(&anotherCms);
signing.setSigners(privKeyList);
signing.startSign(QCA::SecureMessage::Detached);
signing.update(text);
signing.end();
// I think it is reasonable to wait for 1 second for this
signing.waitForFinished(1000);
// check to see if it worked
- if(!signing.success())
- {
- qWarning() << "Error signing: " << signing.errorCode();
- return 1;
+ if (!signing.success()) {
+ qWarning() << "Error signing: " << signing.errorCode();
+ return 1;
}
// get the result
QByteArray signature = signing.signature();
qDebug() << "'" << text.data() << "', signature (converted to base 64), is: ";
- qDebug() << enc.arrayToString( signature );
+ qDebug() << enc.arrayToString(signature);
qDebug() << "Message uses" << signing.hashName() << "hashing algorithm";
qDebug();
-
// Now we go back to the first CMS, and re-use that.
- QCA::SecureMessage verifying( &cms );
+ QCA::SecureMessage verifying(&cms);
// You have to pass the signature to startVerify(),
// and the message to update()
verifying.startVerify(signature);
verifying.update(text);
verifying.end();
verifying.waitForFinished(1000);
// check to see if it worked
- if(!verifying.success())
- {
- qWarning() << "Error verifying: " << verifying.errorCode();
- return 1;
+ if (!verifying.success()) {
+ qWarning() << "Error verifying: " << verifying.errorCode();
+ return 1;
}
QCA::SecureMessageSignature sign;
sign = verifying.signer();
// todo: dump some data out about the signer
- if(verifying.verifySuccess())
- {
- qDebug() << "Message verified";
+ if (verifying.verifySuccess()) {
+ qDebug() << "Message verified";
} else {
- qDebug() << "Message failed to verify:" << verifying.errorCode();
+ qDebug() << "Message failed to verify:" << verifying.errorCode();
}
return 0;
}
diff --git a/examples/cmssigner/certitem.cpp b/examples/cmssigner/certitem.cpp
index c9b560b5..f7962d8a 100644
--- a/examples/cmssigner/certitem.cpp
+++ b/examples/cmssigner/certitem.cpp
@@ -1,724 +1,716 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "certitem.h"
#include <QtCore>
#include <QtGui>
#include <QtCrypto>
#include <QMessageBox>
#include "prompter.h"
-typedef QMap<CertItemStore::IconType,QPixmap> CertItemIconset;
+typedef QMap<CertItemStore::IconType, QPixmap> CertItemIconset;
//----------------------------------------------------------------------------
// MyPrompter
//----------------------------------------------------------------------------
class MyPrompter : public Prompter
{
- Q_OBJECT
+ Q_OBJECT
private:
- QMap<QString,QCA::SecureArray> known;
- QMap<QString,QCA::SecureArray> maybe;
+ QMap<QString, QCA::SecureArray> known;
+ QMap<QString, QCA::SecureArray> maybe;
public:
- MyPrompter(QObject *parent = 0) :
- Prompter(parent)
- {
- }
-
- void fileSuccess(const QString &fileName)
- {
- if(maybe.contains(fileName))
- {
- known[fileName] = maybe[fileName];
- maybe.remove(fileName);
- }
- }
-
- void fileFailed(const QString &fileName)
- {
- maybe.remove(fileName);
- known.remove(fileName);
- }
+ MyPrompter(QObject *parent = 0) :
+ Prompter(parent)
+ {
+ }
+
+ void fileSuccess(const QString &fileName)
+ {
+ if (maybe.contains(fileName)) {
+ known[fileName] = maybe[fileName];
+ maybe.remove(fileName);
+ }
+ }
+
+ void fileFailed(const QString &fileName)
+ {
+ maybe.remove(fileName);
+ known.remove(fileName);
+ }
protected:
- virtual QCA::SecureArray knownPassword(const QCA::Event &event)
- {
- if(event.source() == QCA::Event::Data && !event.fileName().isEmpty())
- return known.value(event.fileName());
- else
- return QCA::SecureArray();
- }
-
- virtual void userSubmitted(const QCA::SecureArray &password, const QCA::Event &event)
- {
- if(event.source() == QCA::Event::Data && !event.fileName().isEmpty())
- maybe[event.fileName()] = password;
- }
+ virtual QCA::SecureArray knownPassword(const QCA::Event &event)
+ {
+ if (event.source() == QCA::Event::Data && !event.fileName().isEmpty()) {
+ return known.value(event.fileName());
+ } else {
+ return QCA::SecureArray();
+ }
+ }
+
+ virtual void userSubmitted(const QCA::SecureArray &password, const QCA::Event &event)
+ {
+ if (event.source() == QCA::Event::Data && !event.fileName().isEmpty()) {
+ maybe[event.fileName()] = password;
+ }
+ }
};
//----------------------------------------------------------------------------
// CertItem
//----------------------------------------------------------------------------
static QString escape(const QString &in)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- out += "\\\\";
- else if(in[n] == ':')
- out += "\\c";
- else if(in[n] == '\n')
- out += "\\n";
- else
- out += in[n];
- }
- return out;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ out += "\\\\";
+ } else if (in[n] == ':') {
+ out += "\\c";
+ } else if (in[n] == '\n') {
+ out += "\\n";
+ } else {
+ out += in[n];
+ }
+ }
+ return out;
}
static QString unescape(const QString &in)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- {
- if(n + 1 < in.length())
- {
- ++n;
- if(in[n] == '\\')
- out += '\\';
- else if(in[n] == 'c')
- out += ':';
- else if(in[n] == 'n')
- out += '\n';
- }
- }
- else
- out += in[n];
- }
- return out;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ if (n + 1 < in.length()) {
+ ++n;
+ if (in[n] == '\\') {
+ out += '\\';
+ } else if (in[n] == 'c') {
+ out += ':';
+ } else if (in[n] == 'n') {
+ out += '\n';
+ }
+ }
+ } else {
+ out += in[n];
+ }
+ }
+ return out;
}
class CertItem::Private : public QSharedData
{
public:
- QString name;
- QCA::CertificateChain chain;
- bool havePrivate;
- StorageType storageType;
- bool usable;
-
- QString fileName;
- QCA::KeyStoreEntry keyStoreEntry;
- QString keyStoreEntryString;
-
- Private() :
- havePrivate(false),
- storageType(File),
- usable(false)
- {
- }
-
- QString toString() const
- {
- QStringList parts;
-
- parts += name;
- parts += QString::number(chain.count());
- foreach(const QCA::Certificate &cert, chain)
- parts += QCA::Base64().arrayToString(cert.toDER());
-
- if(havePrivate)
- {
- if(storageType == File)
- {
- parts += "privateFile";
- parts += fileName;
- }
- else // KeyStoreEntry
- {
- parts += "privateEntry";
- if(!keyStoreEntry.isNull())
- parts += keyStoreEntry.toString();
- else
- parts += keyStoreEntryString;
- }
- }
-
- for(int n = 0; n < parts.count(); ++n)
- parts[n] = escape(parts[n]);
- return parts.join(":");
- }
-
- bool fromString(const QString &in)
- {
- QStringList parts = in.split(':');
- for(int n = 0; n < parts.count(); ++n)
- parts[n] = unescape(parts[n]);
-
- if(parts.count() < 3)
- return false;
-
- name = parts[0];
- int chainCount = parts[1].toInt();
- if(chainCount < 1 || chainCount > parts.count() - 2)
- return false;
- chain.clear();
- for(int n = 0; n < chainCount; ++n)
- {
- QCA::Certificate cert = QCA::Certificate::fromDER(QCA::Base64().stringToArray(parts[n + 2]).toByteArray());
- if(cert.isNull())
- return false;
- chain += cert;
- }
- int at = chain.count() + 2;
-
- if(at < parts.count())
- {
- havePrivate = true;
- usable = false;
-
- if(parts[at] == "privateFile")
- {
- storageType = File;
- fileName = parts[at + 1];
- if(QFile::exists(fileName))
- usable = true;
- }
- else if(parts[at] == "privateEntry")
- {
- storageType = KeyStore;
- keyStoreEntryString = parts[at + 1];
- keyStoreEntry = QCA::KeyStoreEntry(keyStoreEntryString);
- if(!keyStoreEntry.isNull())
- usable = true;
- }
- else
- return false;
- }
-
- return true;
- }
+ QString name;
+ QCA::CertificateChain chain;
+ bool havePrivate;
+ StorageType storageType;
+ bool usable;
+
+ QString fileName;
+ QCA::KeyStoreEntry keyStoreEntry;
+ QString keyStoreEntryString;
+
+ Private() :
+ havePrivate(false),
+ storageType(File),
+ usable(false)
+ {
+ }
+
+ QString toString() const
+ {
+ QStringList parts;
+
+ parts += name;
+ parts += QString::number(chain.count());
+ foreach (const QCA::Certificate &cert, chain) {
+ parts += QCA::Base64().arrayToString(cert.toDER());
+ }
+
+ if (havePrivate) {
+ if (storageType == File) {
+ parts += "privateFile";
+ parts += fileName;
+ } else { // KeyStoreEntry
+ parts += "privateEntry";
+ if (!keyStoreEntry.isNull()) {
+ parts += keyStoreEntry.toString();
+ } else {
+ parts += keyStoreEntryString;
+ }
+ }
+ }
+
+ for (int n = 0; n < parts.count(); ++n) {
+ parts[n] = escape(parts[n]);
+ }
+ return parts.join(":");
+ }
+
+ bool fromString(const QString &in)
+ {
+ QStringList parts = in.split(':');
+ for (int n = 0; n < parts.count(); ++n) {
+ parts[n] = unescape(parts[n]);
+ }
+
+ if (parts.count() < 3) {
+ return false;
+ }
+
+ name = parts[0];
+ int chainCount = parts[1].toInt();
+ if (chainCount < 1 || chainCount > parts.count() - 2) {
+ return false;
+ }
+ chain.clear();
+ for (int n = 0; n < chainCount; ++n) {
+ QCA::Certificate cert = QCA::Certificate::fromDER(QCA::Base64().stringToArray(parts[n + 2]).toByteArray());
+ if (cert.isNull()) {
+ return false;
+ }
+ chain += cert;
+ }
+ int at = chain.count() + 2;
+
+ if (at < parts.count()) {
+ havePrivate = true;
+ usable = false;
+
+ if (parts[at] == "privateFile") {
+ storageType = File;
+ fileName = parts[at + 1];
+ if (QFile::exists(fileName)) {
+ usable = true;
+ }
+ } else if (parts[at] == "privateEntry") {
+ storageType = KeyStore;
+ keyStoreEntryString = parts[at + 1];
+ keyStoreEntry = QCA::KeyStoreEntry(keyStoreEntryString);
+ if (!keyStoreEntry.isNull()) {
+ usable = true;
+ }
+ } else {
+ return false;
+ }
+ }
+
+ return true;
+ }
};
CertItem::CertItem()
{
}
CertItem::CertItem(const CertItem &from) :
- d(from.d)
+ d(from.d)
{
}
CertItem::~CertItem()
{
}
-CertItem & CertItem::operator=(const CertItem &from)
+CertItem &CertItem::operator=(const CertItem &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
QString CertItem::name() const
{
- return d->name;
+ return d->name;
}
QCA::CertificateChain CertItem::certificateChain() const
{
- return d->chain;
+ return d->chain;
}
bool CertItem::havePrivate() const
{
- return d->havePrivate;
+ return d->havePrivate;
}
CertItem::StorageType CertItem::storageType() const
{
- return d->storageType;
+ return d->storageType;
}
bool CertItem::isUsable() const
{
- return d->usable;
+ return d->usable;
}
//----------------------------------------------------------------------------
// CertItemStore
//----------------------------------------------------------------------------
static MyPrompter *g_prompter = 0;
static int g_prompter_refs = 0;
class CertItemStorePrivate : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- CertItemStore *q;
- MyPrompter *prompter;
- QList<CertItem> list;
- QList<int> idList;
- CertItemIconset iconset;
- int next_id;
- int next_req_id;
-
- class LoaderItem
- {
- public:
- int req_id;
- QCA::KeyLoader *keyLoader;
- QString fileName;
- };
-
- QList<LoaderItem> loaders;
-
- CertItemStorePrivate(CertItemStore *_q) :
- QObject(_q),
- q(_q),
- next_id(0),
- next_req_id(0)
- {
- if(!g_prompter)
- {
- g_prompter = new MyPrompter;
- g_prompter_refs = 1;
- }
- else
- ++g_prompter_refs;
-
- prompter = g_prompter;
- }
-
- ~CertItemStorePrivate()
- {
- foreach(const LoaderItem &i, loaders)
- delete i.keyLoader;
-
- --g_prompter_refs;
- if(g_prompter_refs == 0)
- {
- delete g_prompter;
- g_prompter = 0;
- }
- }
-
- QString getUniqueName(const QString &name)
- {
- int num = 1;
- while(1)
- {
- QString tryname;
- if(num == 1)
- tryname = name;
- else
- tryname = name + QString(" (%1)").arg(num);
-
- bool found = false;
- foreach(const CertItem &i, list)
- {
- if(i.name() == tryname)
- {
- found = true;
- break;
- }
- }
- if(!found)
- return tryname;
-
- ++num;
- }
- }
-
- static QString convertErrorToString(QCA::ConvertResult r)
- {
- QString str;
- switch(r)
- {
- case QCA::ConvertGood: break;
- case QCA::ErrorPassphrase: str = tr("Incorrect passphrase.");
- case QCA::ErrorFile: str = tr("Unable to open or read file.");
- case QCA::ErrorDecode:
- default: str = tr("Unable to decode format.");
- }
- return str;
- }
+ CertItemStore *q;
+ MyPrompter *prompter;
+ QList<CertItem> list;
+ QList<int> idList;
+ CertItemIconset iconset;
+ int next_id;
+ int next_req_id;
+
+ class LoaderItem
+ {
+ public:
+ int req_id;
+ QCA::KeyLoader *keyLoader;
+ QString fileName;
+ };
+
+ QList<LoaderItem> loaders;
+
+ CertItemStorePrivate(CertItemStore *_q) :
+ QObject(_q),
+ q(_q),
+ next_id(0),
+ next_req_id(0)
+ {
+ if (!g_prompter) {
+ g_prompter = new MyPrompter;
+ g_prompter_refs = 1;
+ } else {
+ ++g_prompter_refs;
+ }
+
+ prompter = g_prompter;
+ }
+
+ ~CertItemStorePrivate()
+ {
+ foreach (const LoaderItem &i, loaders) {
+ delete i.keyLoader;
+ }
+
+ --g_prompter_refs;
+ if (g_prompter_refs == 0) {
+ delete g_prompter;
+ g_prompter = 0;
+ }
+ }
+
+ QString getUniqueName(const QString &name)
+ {
+ int num = 1;
+ while (1) {
+ QString tryname;
+ if (num == 1) {
+ tryname = name;
+ } else {
+ tryname = name + QString(" (%1)").arg(num);
+ }
+
+ bool found = false;
+ foreach (const CertItem &i, list) {
+ if (i.name() == tryname) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ return tryname;
+ }
+
+ ++num;
+ }
+ }
+
+ static QString convertErrorToString(QCA::ConvertResult r)
+ {
+ QString str;
+ switch (r) {
+ case QCA::ConvertGood: break;
+ case QCA::ErrorPassphrase: str = tr("Incorrect passphrase.");
+ case QCA::ErrorFile: str = tr("Unable to open or read file.");
+ case QCA::ErrorDecode:
+ default: str = tr("Unable to decode format.");
+ }
+ return str;
+ }
public slots:
- void loader_finished()
- {
- QCA::KeyLoader *keyLoader = (QCA::KeyLoader *)sender();
- int at = -1;
- for(int n = 0; n < loaders.count(); ++n)
- {
- if(loaders[n].keyLoader == keyLoader)
- {
- at = n;
- break;
- }
- }
- Q_ASSERT(at != -1);
-
- int req_id = loaders[at].req_id;
- QString fileName = loaders[at].fileName;
- loaders.removeAt(at);
-
- QCA::ConvertResult r = keyLoader->convertResult();
- if(r != QCA::ConvertGood)
- {
- delete keyLoader;
- prompter->fileFailed(fileName);
- QMessageBox::information(0, tr("Error"),
- tr("Error importing certificate and private key.\nReason: %1").arg(convertErrorToString(r)));
- emit q->addFailed(req_id);
- return;
- }
-
- prompter->fileSuccess(fileName);
-
- QCA::KeyBundle kb = keyLoader->keyBundle();
- delete keyLoader;
-
- QCA::CertificateChain chain = kb.certificateChain();
- QCA::Certificate cert = chain.primary();
-
- QString name = getUniqueName(cert.commonName());
-
- CertItem i;
- i.d = new CertItem::Private;
- i.d->name = name;
- i.d->chain = chain;
- i.d->havePrivate = true;
- i.d->storageType = CertItem::File;
- i.d->usable = true;
- i.d->fileName = fileName;
-
- int id = next_id++;
-
- q->beginInsertRows(QModelIndex(), list.size(), list.size());
- list += i;
- idList += id;
- q->endInsertRows();
-
- emit q->addSuccess(req_id, id);
- }
+ void loader_finished()
+ {
+ QCA::KeyLoader *keyLoader = (QCA::KeyLoader *)sender();
+ int at = -1;
+ for (int n = 0; n < loaders.count(); ++n) {
+ if (loaders[n].keyLoader == keyLoader) {
+ at = n;
+ break;
+ }
+ }
+ Q_ASSERT(at != -1);
+
+ int req_id = loaders[at].req_id;
+ QString fileName = loaders[at].fileName;
+ loaders.removeAt(at);
+
+ QCA::ConvertResult r = keyLoader->convertResult();
+ if (r != QCA::ConvertGood) {
+ delete keyLoader;
+ prompter->fileFailed(fileName);
+ QMessageBox::information(0, tr("Error"),
+ tr("Error importing certificate and private key.\nReason: %1").arg(convertErrorToString(r)));
+ emit q->addFailed(req_id);
+ return;
+ }
+
+ prompter->fileSuccess(fileName);
+
+ QCA::KeyBundle kb = keyLoader->keyBundle();
+ delete keyLoader;
+
+ QCA::CertificateChain chain = kb.certificateChain();
+ QCA::Certificate cert = chain.primary();
+
+ QString name = getUniqueName(cert.commonName());
+
+ CertItem i;
+ i.d = new CertItem::Private;
+ i.d->name = name;
+ i.d->chain = chain;
+ i.d->havePrivate = true;
+ i.d->storageType = CertItem::File;
+ i.d->usable = true;
+ i.d->fileName = fileName;
+
+ int id = next_id++;
+
+ q->beginInsertRows(QModelIndex(), list.size(), list.size());
+ list += i;
+ idList += id;
+ q->endInsertRows();
+
+ emit q->addSuccess(req_id, id);
+ }
};
CertItemStore::CertItemStore(QObject *parent) :
- QAbstractListModel(parent)
+ QAbstractListModel(parent)
{
- d = new CertItemStorePrivate(this);
+ d = new CertItemStorePrivate(this);
}
CertItemStore::~CertItemStore()
{
- delete d;
+ delete d;
}
int CertItemStore::idFromRow(int row) const
{
- return d->idList[row];
+ return d->idList[row];
}
int CertItemStore::rowFromId(int id) const
{
- for(int n = 0; n < d->idList.count(); ++n)
- {
- if(d->idList[n] == id)
- return n;
- }
- return -1;
+ for (int n = 0; n < d->idList.count(); ++n) {
+ if (d->idList[n] == id) {
+ return n;
+ }
+ }
+ return -1;
}
CertItem CertItemStore::itemFromId(int id) const
{
- return d->list[rowFromId(id)];
+ return d->list[rowFromId(id)];
}
CertItem CertItemStore::itemFromRow(int row) const
{
- return d->list[row];
+ return d->list[row];
}
QList<CertItem> CertItemStore::items() const
{
- return d->list;
+ return d->list;
}
QStringList CertItemStore::save() const
{
- QStringList out;
- foreach(const CertItem &i, d->list)
- out += i.d->toString();
- return out;
+ QStringList out;
+ foreach (const CertItem &i, d->list) {
+ out += i.d->toString();
+ }
+ return out;
}
bool CertItemStore::load(const QStringList &in)
{
- QList<CertItem> addList;
- QList<int> addIdList;
- foreach(const QString &s, in)
- {
- CertItem i;
- i.d = new CertItem::Private;
- if(i.d->fromString(s))
- {
- addList += i;
- addIdList += d->next_id++;
- }
- }
+ QList<CertItem> addList;
+ QList<int> addIdList;
+ foreach (const QString &s, in) {
+ CertItem i;
+ i.d = new CertItem::Private;
+ if (i.d->fromString(s)) {
+ addList += i;
+ addIdList += d->next_id++;
+ }
+ }
- if(addList.isEmpty())
- return true;
+ if (addList.isEmpty()) {
+ return true;
+ }
- beginInsertRows(QModelIndex(), d->list.size(), d->list.size() + addList.count() - 1);
- d->list += addList;
- d->idList += addIdList;
- endInsertRows();
+ beginInsertRows(QModelIndex(), d->list.size(), d->list.size() + addList.count() - 1);
+ d->list += addList;
+ d->idList += addIdList;
+ endInsertRows();
- return true;
+ return true;
}
int CertItemStore::addFromFile(const QString &fileName)
{
- CertItemStorePrivate::LoaderItem i;
- i.req_id = d->next_req_id++;
- i.keyLoader = new QCA::KeyLoader(d);
- i.fileName = fileName;
- connect(i.keyLoader, SIGNAL(finished()), d, SLOT(loader_finished()));
- d->loaders += i;
- i.keyLoader->loadKeyBundleFromFile(fileName);
- return i.req_id;
+ CertItemStorePrivate::LoaderItem i;
+ i.req_id = d->next_req_id++;
+ i.keyLoader = new QCA::KeyLoader(d);
+ i.fileName = fileName;
+ connect(i.keyLoader, SIGNAL(finished()), d, SLOT(loader_finished()));
+ d->loaders += i;
+ i.keyLoader->loadKeyBundleFromFile(fileName);
+ return i.req_id;
}
int CertItemStore::addFromKeyStore(const QCA::KeyStoreEntry &entry)
{
- QCA::KeyBundle kb = entry.keyBundle();
+ QCA::KeyBundle kb = entry.keyBundle();
- QCA::CertificateChain chain = kb.certificateChain();
- QCA::Certificate cert = chain.primary();
+ QCA::CertificateChain chain = kb.certificateChain();
+ QCA::Certificate cert = chain.primary();
- QString name = d->getUniqueName(entry.name());
+ QString name = d->getUniqueName(entry.name());
- CertItem i;
- i.d = new CertItem::Private;
- i.d->name = name;
- i.d->chain = chain;
- i.d->havePrivate = true;
- i.d->storageType = CertItem::KeyStore;
- i.d->usable = true;
- i.d->keyStoreEntry = entry;
+ CertItem i;
+ i.d = new CertItem::Private;
+ i.d->name = name;
+ i.d->chain = chain;
+ i.d->havePrivate = true;
+ i.d->storageType = CertItem::KeyStore;
+ i.d->usable = true;
+ i.d->keyStoreEntry = entry;
- int id = d->next_id++;
+ int id = d->next_id++;
- beginInsertRows(QModelIndex(), d->list.size(), d->list.size());
- d->list += i;
- d->idList += id;
- endInsertRows();
+ beginInsertRows(QModelIndex(), d->list.size(), d->list.size());
+ d->list += i;
+ d->idList += id;
+ endInsertRows();
- int req_id = d->next_req_id++;
- QMetaObject::invokeMethod(this, "addSuccess", Qt::QueuedConnection, Q_ARG(int, req_id), Q_ARG(int, id));
- return req_id;
+ int req_id = d->next_req_id++;
+ QMetaObject::invokeMethod(this, "addSuccess", Qt::QueuedConnection, Q_ARG(int, req_id), Q_ARG(int, id));
+ return req_id;
}
int CertItemStore::addUser(const QCA::CertificateChain &chain)
{
- QCA::Certificate cert = chain.primary();
+ QCA::Certificate cert = chain.primary();
- QString name = d->getUniqueName(cert.commonName());
+ QString name = d->getUniqueName(cert.commonName());
- CertItem i;
- i.d = new CertItem::Private;
- i.d->name = name;
- i.d->chain = chain;
+ CertItem i;
+ i.d = new CertItem::Private;
+ i.d->name = name;
+ i.d->chain = chain;
- int id = d->next_id++;
+ int id = d->next_id++;
- beginInsertRows(QModelIndex(), d->list.size(), d->list.size());
- d->list += i;
- d->idList += id;
- endInsertRows();
+ beginInsertRows(QModelIndex(), d->list.size(), d->list.size());
+ d->list += i;
+ d->idList += id;
+ endInsertRows();
- int req_id = d->next_req_id++;
- QMetaObject::invokeMethod(this, "addSuccess", Qt::QueuedConnection, Q_ARG(int, req_id), Q_ARG(int, id));
- return req_id;
+ int req_id = d->next_req_id++;
+ QMetaObject::invokeMethod(this, "addSuccess", Qt::QueuedConnection, Q_ARG(int, req_id), Q_ARG(int, id));
+ return req_id;
}
void CertItemStore::updateChain(int id, const QCA::CertificateChain &chain)
{
- int at = rowFromId(id);
- d->list[at].d->chain = chain;
+ int at = rowFromId(id);
+ d->list[at].d->chain = chain;
}
void CertItemStore::removeItem(int id)
{
- int at = rowFromId(id);
+ int at = rowFromId(id);
- beginRemoveRows(QModelIndex(), at, at);
- d->list.removeAt(at);
- d->idList.removeAt(at);
- endRemoveRows();
+ beginRemoveRows(QModelIndex(), at, at);
+ d->list.removeAt(at);
+ d->idList.removeAt(at);
+ endRemoveRows();
}
void CertItemStore::setIcon(IconType type, const QPixmap &icon)
{
- d->iconset[type] = icon;
+ d->iconset[type] = icon;
}
int CertItemStore::rowCount(const QModelIndex &parent) const
{
- Q_UNUSED(parent);
- return d->list.count();
+ Q_UNUSED(parent);
+ return d->list.count();
}
QVariant CertItemStore::data(const QModelIndex &index, int role) const
{
- if(!index.isValid())
- return QVariant();
-
- int at = index.row();
- QList<CertItem> &list = d->list;
-
- if(at >= list.count())
- return QVariant();
-
- if(role == Qt::DisplayRole)
- {
- QString str = list[at].name();
- if(list[at].havePrivate() && !list[at].isUsable())
- str += QString(" ") + tr("(not usable)");
- return str;
- }
- else if(role == Qt::EditRole)
- return list[at].name();
- else if(role == Qt::DecorationRole)
- {
- if(list[at].havePrivate())
- return d->iconset[CertItemStore::IconKeyBundle];
- else
- return d->iconset[CertItemStore::IconCert];
- }
- else
- return QVariant();
+ if (!index.isValid()) {
+ return QVariant();
+ }
+
+ int at = index.row();
+ QList<CertItem> &list = d->list;
+
+ if (at >= list.count()) {
+ return QVariant();
+ }
+
+ if (role == Qt::DisplayRole) {
+ QString str = list[at].name();
+ if (list[at].havePrivate() && !list[at].isUsable()) {
+ str += QString(" ") + tr("(not usable)");
+ }
+ return str;
+ } else if (role == Qt::EditRole) {
+ return list[at].name();
+ } else if (role == Qt::DecorationRole) {
+ if (list[at].havePrivate()) {
+ return d->iconset[CertItemStore::IconKeyBundle];
+ } else {
+ return d->iconset[CertItemStore::IconCert];
+ }
+ } else {
+ return QVariant();
+ }
}
Qt::ItemFlags CertItemStore::flags(const QModelIndex &index) const
{
- if(!index.isValid())
- return Qt::ItemIsEnabled;
+ if (!index.isValid()) {
+ return Qt::ItemIsEnabled;
+ }
- return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
+ return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
}
bool CertItemStore::setData(const QModelIndex &index, const QVariant &value, int role)
{
- if(index.isValid() && role == Qt::EditRole)
- {
- QString str = value.toString();
- d->list[index.row()].d->name = str;
- emit dataChanged(index, index);
- return true;
- }
- return false;
+ if (index.isValid() && role == Qt::EditRole) {
+ QString str = value.toString();
+ d->list[index.row()].d->name = str;
+ emit dataChanged(index, index);
+ return true;
+ }
+ return false;
}
//----------------------------------------------------------------------------
// CertItemPrivateLoader
//----------------------------------------------------------------------------
class CertItemPrivateLoaderPrivate : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- CertItemPrivateLoader *q;
- CertItemStore *store;
- QCA::KeyLoader *loader;
- QString fileName;
- QCA::PrivateKey key;
-
- CertItemPrivateLoaderPrivate(CertItemPrivateLoader *_q) :
- QObject(_q),
- q(_q)
- {
- }
+ CertItemPrivateLoader *q;
+ CertItemStore *store;
+ QCA::KeyLoader *loader;
+ QString fileName;
+ QCA::PrivateKey key;
+
+ CertItemPrivateLoaderPrivate(CertItemPrivateLoader *_q) :
+ QObject(_q),
+ q(_q)
+ {
+ }
public slots:
- void loader_finished()
- {
- QCA::ConvertResult r = loader->convertResult();
- if(r != QCA::ConvertGood)
- {
- delete loader;
- loader = 0;
- store->d->prompter->fileFailed(fileName);
- QMessageBox::information(0, tr("Error"),
- tr("Error accessing private key.\nReason: %1").arg(CertItemStorePrivate::convertErrorToString(r)));
- emit q->finished();
- return;
- }
-
- store->d->prompter->fileSuccess(fileName);
-
- key = loader->keyBundle().privateKey();
- delete loader;
- loader = 0;
- emit q->finished();
- }
+ void loader_finished()
+ {
+ QCA::ConvertResult r = loader->convertResult();
+ if (r != QCA::ConvertGood) {
+ delete loader;
+ loader = 0;
+ store->d->prompter->fileFailed(fileName);
+ QMessageBox::information(0, tr("Error"),
+ tr("Error accessing private key.\nReason: %1").arg(CertItemStorePrivate::convertErrorToString(r)));
+ emit q->finished();
+ return;
+ }
+
+ store->d->prompter->fileSuccess(fileName);
+
+ key = loader->keyBundle().privateKey();
+ delete loader;
+ loader = 0;
+ emit q->finished();
+ }
};
CertItemPrivateLoader::CertItemPrivateLoader(CertItemStore *store, QObject *parent) :
- QObject(parent)
+ QObject(parent)
{
- d = new CertItemPrivateLoaderPrivate(this);
- d->store = store;
+ d = new CertItemPrivateLoaderPrivate(this);
+ d->store = store;
}
CertItemPrivateLoader::~CertItemPrivateLoader()
{
- delete d;
+ delete d;
}
void CertItemPrivateLoader::start(int id)
{
- CertItem i = d->store->itemFromId(id);
+ CertItem i = d->store->itemFromId(id);
- if(i.storageType() == CertItem::KeyStore)
- {
- d->key = i.d->keyStoreEntry.keyBundle().privateKey();
- QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
- return;
- }
+ if (i.storageType() == CertItem::KeyStore) {
+ d->key = i.d->keyStoreEntry.keyBundle().privateKey();
+ QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
+ return;
+ }
- d->key = QCA::PrivateKey();
- d->fileName = i.d->fileName;
- d->loader = new QCA::KeyLoader(d);
- connect(d->loader, SIGNAL(finished()), d, SLOT(loader_finished()));
- d->loader->loadKeyBundleFromFile(d->fileName);
+ d->key = QCA::PrivateKey();
+ d->fileName = i.d->fileName;
+ d->loader = new QCA::KeyLoader(d);
+ connect(d->loader, SIGNAL(finished()), d, SLOT(loader_finished()));
+ d->loader->loadKeyBundleFromFile(d->fileName);
}
QCA::PrivateKey CertItemPrivateLoader::privateKey() const
{
- return d->key;
+ return d->key;
}
#include "certitem.moc"
diff --git a/examples/cmssigner/certitem.h b/examples/cmssigner/certitem.h
index c1ae785b..7ebdeb4d 100644
--- a/examples/cmssigner/certitem.h
+++ b/examples/cmssigner/certitem.h
@@ -1,146 +1,144 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CERTITEM_H
#define CERTITEM_H
#include <QAbstractListModel>
#include <QSharedDataPointer>
class QString;
class QStringList;
namespace QCA
{
- class PrivateKey;
- class CertificateChain;
- class KeyStoreEntry;
+class PrivateKey;
+class CertificateChain;
+class KeyStoreEntry;
}
class CertItemStore;
class CertItemStorePrivate;
class CertItemPrivateLoaderPrivate;
class CertItem
{
public:
- enum StorageType
- {
- File,
- KeyStore
- };
-
- CertItem();
- CertItem(const CertItem &from);
- ~CertItem();
- CertItem & operator=(const CertItem &from);
-
- QString name() const;
- QCA::CertificateChain certificateChain() const;
- bool havePrivate() const;
- StorageType storageType() const; // private key storage type
- bool isUsable() const; // file/provider present
+ enum StorageType {
+ File,
+ KeyStore
+ };
+
+ CertItem();
+ CertItem(const CertItem &from);
+ ~CertItem();
+ CertItem &operator=(const CertItem &from);
+
+ QString name() const;
+ QCA::CertificateChain certificateChain() const;
+ bool havePrivate() const;
+ StorageType storageType() const; // private key storage type
+ bool isUsable() const; // file/provider present
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
- friend class CertItemStore;
- friend class CertItemStorePrivate;
- friend class CertItemPrivateLoader;
- friend class CertItemPrivateLoaderPrivate;
+ friend class CertItemStore;
+ friend class CertItemStorePrivate;
+ friend class CertItemPrivateLoader;
+ friend class CertItemPrivateLoaderPrivate;
};
class CertItemStore : public QAbstractListModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum IconType
- {
- IconCert,
- IconCrl,
- IconKeyBundle,
- IconPgpPub,
- IconPgpSec
- };
+ enum IconType {
+ IconCert,
+ IconCrl,
+ IconKeyBundle,
+ IconPgpPub,
+ IconPgpSec
+ };
- CertItemStore(QObject *parent = 0);
- ~CertItemStore();
+ CertItemStore(QObject *parent = 0);
+ ~CertItemStore();
- int idFromRow(int row) const;
- int rowFromId(int id) const;
- CertItem itemFromId(int id) const;
- CertItem itemFromRow(int row) const;
+ int idFromRow(int row) const;
+ int rowFromId(int id) const;
+ CertItem itemFromId(int id) const;
+ CertItem itemFromRow(int row) const;
- QList<CertItem> items() const;
+ QList<CertItem> items() const;
- QStringList save() const;
- bool load(const QStringList &in);
+ QStringList save() const;
+ bool load(const QStringList &in);
- // returns a reqId
- int addFromFile(const QString &fileName);
- int addFromKeyStore(const QCA::KeyStoreEntry &entry);
- int addUser(const QCA::CertificateChain &chain);
+ // returns a reqId
+ int addFromFile(const QString &fileName);
+ int addFromKeyStore(const QCA::KeyStoreEntry &entry);
+ int addUser(const QCA::CertificateChain &chain);
- void updateChain(int id, const QCA::CertificateChain &chain);
+ void updateChain(int id, const QCA::CertificateChain &chain);
- void removeItem(int id);
+ void removeItem(int id);
- void setIcon(IconType type, const QPixmap &icon);
+ void setIcon(IconType type, const QPixmap &icon);
- // reimplemented
- int rowCount(const QModelIndex &parent = QModelIndex()) const;
- QVariant data(const QModelIndex &index, int role) const;
- Qt::ItemFlags flags(const QModelIndex &index) const;
- bool setData(const QModelIndex &index, const QVariant &value, int role);
+ // reimplemented
+ int rowCount(const QModelIndex &parent = QModelIndex()) const;
+ QVariant data(const QModelIndex &index, int role) const;
+ Qt::ItemFlags flags(const QModelIndex &index) const;
+ bool setData(const QModelIndex &index, const QVariant &value, int role);
signals:
- void addSuccess(int reqId, int id);
- void addFailed(int reqId);
+ void addSuccess(int reqId, int id);
+ void addFailed(int reqId);
private:
- friend class CertItemStorePrivate;
- CertItemStorePrivate *d;
+ friend class CertItemStorePrivate;
+ CertItemStorePrivate *d;
- friend class CertItemPrivateLoader;
- friend class CertItemPrivateLoaderPrivate;
+ friend class CertItemPrivateLoader;
+ friend class CertItemPrivateLoaderPrivate;
};
class CertItemPrivateLoader : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit CertItemPrivateLoader(CertItemStore *store, QObject *parent = 0);
- ~CertItemPrivateLoader();
+ explicit CertItemPrivateLoader(CertItemStore *store, QObject *parent = 0);
+ ~CertItemPrivateLoader();
- void start(int id);
+ void start(int id);
- QCA::PrivateKey privateKey() const;
+ QCA::PrivateKey privateKey() const;
signals:
- void finished();
+ void finished();
private:
- friend class CertItemPrivateLoaderPrivate;
- CertItemPrivateLoaderPrivate *d;
+ friend class CertItemPrivateLoaderPrivate;
+ CertItemPrivateLoaderPrivate *d;
};
#endif
diff --git a/examples/cmssigner/certviewdlg.cpp b/examples/cmssigner/certviewdlg.cpp
index 04e26186..e65b0db1 100644
--- a/examples/cmssigner/certviewdlg.cpp
+++ b/examples/cmssigner/certviewdlg.cpp
@@ -1,166 +1,167 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "certviewdlg.h"
#include <QtCore>
#include <QtGui>
#include <QtCrypto>
#include "ui_certview.h"
// from qcatool
class InfoType
{
public:
- QCA::CertificateInfoType type;
- QString varname;
- QString shortname;
- QString name;
- QString desc;
-
- InfoType()
- {
- }
-
- InfoType(QCA::CertificateInfoType _type, const QString &_varname, const QString &_shortname, const QString &_name, const QString &_desc) :
- type(_type),
- varname(_varname),
- shortname(_shortname),
- name(_name),
- desc(_desc)
- {
- }
+ QCA::CertificateInfoType type;
+ QString varname;
+ QString shortname;
+ QString name;
+ QString desc;
+
+ InfoType()
+ {
+ }
+
+ InfoType(QCA::CertificateInfoType _type, const QString &_varname, const QString &_shortname, const QString &_name, const QString &_desc) :
+ type(_type),
+ varname(_varname),
+ shortname(_shortname),
+ name(_name),
+ desc(_desc)
+ {
+ }
};
static QList<InfoType> makeInfoTypeList(bool legacyEmail = false)
{
- QList<InfoType> out;
- out += InfoType(QCA::CommonName, "CommonName", "CN", CertViewDlg::tr("Common Name (CN)"), "Full name, domain, anything");
- out += InfoType(QCA::Email, "Email", "", CertViewDlg::tr("Email Address"), "");
- if(legacyEmail)
- out += InfoType(QCA::EmailLegacy, "EmailLegacy", "", CertViewDlg::tr("PKCS#9 Email Address"), "");
- out += InfoType(QCA::Organization, "Organization", "O", CertViewDlg::tr("Organization (O)"), "Company, group, etc");
- out += InfoType(QCA::OrganizationalUnit, "OrganizationalUnit", "OU", CertViewDlg::tr("Organizational Unit (OU)"), "Division/branch of organization");
- out += InfoType(QCA::Locality, "Locality", "", CertViewDlg::tr("Locality (L)"), "City, shire, part of a state");
- out += InfoType(QCA::State, "State", "", CertViewDlg::tr("State (ST)"), "State within the country");
- out += InfoType(QCA::Country, "Country", "C", CertViewDlg::tr("Country Code (C)"), "2-letter code");
- out += InfoType(QCA::IncorporationLocality, "IncorporationLocality", "", CertViewDlg::tr("Incorporation Locality"), "For EV certificates");
- out += InfoType(QCA::IncorporationState, "IncorporationState", "", CertViewDlg::tr("Incorporation State"), "For EV certificates");
- out += InfoType(QCA::IncorporationCountry, "IncorporationCountry", "", CertViewDlg::tr("Incorporation Country"), "For EV certificates");
- out += InfoType(QCA::URI, "URI", "", CertViewDlg::tr("URI"), "");
- out += InfoType(QCA::DNS, "DNS", "", CertViewDlg::tr("Domain Name"), "Domain (dnsName)");
- out += InfoType(QCA::IPAddress, "IPAddress", "", CertViewDlg::tr("IP Adddress"), "");
- out += InfoType(QCA::XMPP, "XMPP", "", CertViewDlg::tr("XMPP Address (JID)"), "From RFC 3920 (id-on-xmppAddr)");
- return out;
+ QList<InfoType> out;
+ out += InfoType(QCA::CommonName, "CommonName", "CN", CertViewDlg::tr("Common Name (CN)"), "Full name, domain, anything");
+ out += InfoType(QCA::Email, "Email", "", CertViewDlg::tr("Email Address"), "");
+ if (legacyEmail) {
+ out += InfoType(QCA::EmailLegacy, "EmailLegacy", "", CertViewDlg::tr("PKCS#9 Email Address"), "");
+ }
+ out += InfoType(QCA::Organization, "Organization", "O", CertViewDlg::tr("Organization (O)"), "Company, group, etc");
+ out += InfoType(QCA::OrganizationalUnit, "OrganizationalUnit", "OU", CertViewDlg::tr("Organizational Unit (OU)"), "Division/branch of organization");
+ out += InfoType(QCA::Locality, "Locality", "", CertViewDlg::tr("Locality (L)"), "City, shire, part of a state");
+ out += InfoType(QCA::State, "State", "", CertViewDlg::tr("State (ST)"), "State within the country");
+ out += InfoType(QCA::Country, "Country", "C", CertViewDlg::tr("Country Code (C)"), "2-letter code");
+ out += InfoType(QCA::IncorporationLocality, "IncorporationLocality", "", CertViewDlg::tr("Incorporation Locality"), "For EV certificates");
+ out += InfoType(QCA::IncorporationState, "IncorporationState", "", CertViewDlg::tr("Incorporation State"), "For EV certificates");
+ out += InfoType(QCA::IncorporationCountry, "IncorporationCountry", "", CertViewDlg::tr("Incorporation Country"), "For EV certificates");
+ out += InfoType(QCA::URI, "URI", "", CertViewDlg::tr("URI"), "");
+ out += InfoType(QCA::DNS, "DNS", "", CertViewDlg::tr("Domain Name"), "Domain (dnsName)");
+ out += InfoType(QCA::IPAddress, "IPAddress", "", CertViewDlg::tr("IP Adddress"), "");
+ out += InfoType(QCA::XMPP, "XMPP", "", CertViewDlg::tr("XMPP Address (JID)"), "From RFC 3920 (id-on-xmppAddr)");
+ return out;
}
static QString try_print_info(const QString &name, const QStringList &values)
{
- QString out;
- if(!values.isEmpty())
- {
- QString value = values.join(", ");
- out = QString(" ") + CertViewDlg::tr("%1: %2").arg(name, value) + '\n';
- }
- return out;
+ QString out;
+ if (!values.isEmpty()) {
+ QString value = values.join(", ");
+ out = QString(" ") + CertViewDlg::tr("%1: %2").arg(name, value) + '\n';
+ }
+ return out;
}
static QString print_info(const QString &title, const QCA::CertificateInfo &info)
{
- QString out;
- QList<InfoType> list = makeInfoTypeList();
- out += title + '\n';
- foreach(const InfoType &t, list)
- out += try_print_info(t.name, info.values(t.type));
- return out;
+ QString out;
+ QList<InfoType> list = makeInfoTypeList();
+ out += title + '\n';
+ foreach (const InfoType &t, list) {
+ out += try_print_info(t.name, info.values(t.type));
+ }
+ return out;
}
static QString cert_info_string(const QCA::Certificate &cert)
{
- QString out;
- out += CertViewDlg::tr("Serial Number: %1").arg(cert.serialNumber().toString()) + '\n';
- out += print_info(CertViewDlg::tr("Subject"), cert.subjectInfo());
- out += print_info(CertViewDlg::tr("Issuer"), cert.issuerInfo());
- out += CertViewDlg::tr("Validity") + '\n';
- out += QString(" ") + CertViewDlg::tr("Not before: %1").arg(cert.notValidBefore().toString()) + '\n';
- out += QString(" ") + CertViewDlg::tr("Not after: %1").arg(cert.notValidAfter().toString()) + '\n';
- return out;
+ QString out;
+ out += CertViewDlg::tr("Serial Number: %1").arg(cert.serialNumber().toString()) + '\n';
+ out += print_info(CertViewDlg::tr("Subject"), cert.subjectInfo());
+ out += print_info(CertViewDlg::tr("Issuer"), cert.issuerInfo());
+ out += CertViewDlg::tr("Validity") + '\n';
+ out += QString(" ") + CertViewDlg::tr("Not before: %1").arg(cert.notValidBefore().toString()) + '\n';
+ out += QString(" ") + CertViewDlg::tr("Not after: %1").arg(cert.notValidAfter().toString()) + '\n';
+ return out;
}
class CertViewDlg::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- CertViewDlg *q;
- Ui_CertView ui;
- QCA::CertificateChain chain;
-
- Private(CertViewDlg *_q) :
- QObject(_q),
- q(_q)
- {
- ui.setupUi(q);
- connect(ui.cb_chain, SIGNAL(activated(int)), SLOT(cb_activated(int)));
- ui.lb_info->setTextInteractionFlags(Qt::TextSelectableByMouse);
- }
-
- void update()
- {
- QStringList names = QCA::makeFriendlyNames(chain);
- ui.cb_chain->clear();
- foreach(const QString &s, names)
- ui.cb_chain->insertItem(ui.cb_chain->count(), s);
- updateInfo();
- }
-
- void updateInfo()
- {
- int x = ui.cb_chain->currentIndex();
- if(x == -1)
- {
- ui.lb_info->setText("");
- return;
- }
-
- ui.lb_info->setText(cert_info_string(chain[x]));
- }
+ CertViewDlg *q;
+ Ui_CertView ui;
+ QCA::CertificateChain chain;
+
+ Private(CertViewDlg *_q) :
+ QObject(_q),
+ q(_q)
+ {
+ ui.setupUi(q);
+ connect(ui.cb_chain, SIGNAL(activated(int)), SLOT(cb_activated(int)));
+ ui.lb_info->setTextInteractionFlags(Qt::TextSelectableByMouse);
+ }
+
+ void update()
+ {
+ QStringList names = QCA::makeFriendlyNames(chain);
+ ui.cb_chain->clear();
+ foreach (const QString &s, names) {
+ ui.cb_chain->insertItem(ui.cb_chain->count(), s);
+ }
+ updateInfo();
+ }
+
+ void updateInfo()
+ {
+ int x = ui.cb_chain->currentIndex();
+ if (x == -1) {
+ ui.lb_info->setText("");
+ return;
+ }
+
+ ui.lb_info->setText(cert_info_string(chain[x]));
+ }
private slots:
- void cb_activated(int)
- {
- updateInfo();
- }
+ void cb_activated(int)
+ {
+ updateInfo();
+ }
};
CertViewDlg::CertViewDlg(const QCA::CertificateChain &chain, QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- d = new Private(this);
- d->chain = chain;
- d->update();
+ d = new Private(this);
+ d->chain = chain;
+ d->update();
}
CertViewDlg::~CertViewDlg()
{
- delete d;
+ delete d;
}
#include "certviewdlg.moc"
diff --git a/examples/cmssigner/certviewdlg.h b/examples/cmssigner/certviewdlg.h
index 8e232bea..ed70d01e 100644
--- a/examples/cmssigner/certviewdlg.h
+++ b/examples/cmssigner/certviewdlg.h
@@ -1,44 +1,44 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef CERTVIEWDLG_H
#define CERTVIEWDLG_H
#include <QDialog>
namespace QCA
{
- class CertificateChain;
+class CertificateChain;
}
class CertViewDlg : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- explicit CertViewDlg(const QCA::CertificateChain &chain, QWidget *parent = 0);
- ~CertViewDlg();
+ explicit CertViewDlg(const QCA::CertificateChain &chain, QWidget *parent = 0);
+ ~CertViewDlg();
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
#endif
diff --git a/examples/cmssigner/keyselectdlg.cpp b/examples/cmssigner/keyselectdlg.cpp
index ef2335d0..ddf519ad 100644
--- a/examples/cmssigner/keyselectdlg.cpp
+++ b/examples/cmssigner/keyselectdlg.cpp
@@ -1,425 +1,408 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "keyselectdlg.h"
#include <QtCore>
#include <QtGui>
#include <QtCrypto>
#include <QPushButton>
#include <QMenu>
#include <QMessageBox>
#include "ui_keyselect.h"
#define ONLY_SHOW_KEYBUNDLE
-typedef QMap<KeySelectDlg::IconType,QPixmap> KeyStoreIconset;
+typedef QMap<KeySelectDlg::IconType, QPixmap> KeyStoreIconset;
class KeyStoreItemShared
{
public:
- KeyStoreIconset iconset;
- QString notAvailableString;
+ KeyStoreIconset iconset;
+ QString notAvailableString;
};
class KeyStoreItem : public QStandardItem
{
public:
- enum Type
- {
- Store = UserType,
- Entry
- };
-
- enum Role
- {
- NameRole = Qt::UserRole,
- SubTypeRole,
- AvailabilityRole,
- PositionRole
- };
-
- QPixmap entryTypeToIcon(QCA::KeyStoreEntry::Type type) const
- {
- QPixmap out;
- if(!_shared)
- return out;
- const KeyStoreIconset &iconset = _shared->iconset;
- switch(type)
- {
- case QCA::KeyStoreEntry::TypeKeyBundle: out = iconset[KeySelectDlg::IconKeyBundle]; break;
- case QCA::KeyStoreEntry::TypeCertificate: out = iconset[KeySelectDlg::IconCert]; break;
- case QCA::KeyStoreEntry::TypeCRL: out = iconset[KeySelectDlg::IconCrl]; break;
- case QCA::KeyStoreEntry::TypePGPSecretKey: out = iconset[KeySelectDlg::IconPgpSec]; break;
- case QCA::KeyStoreEntry::TypePGPPublicKey: out = iconset[KeySelectDlg::IconPgpPub]; break;
- default: break;
- }
- return out;
- }
-
- Type _type;
- KeyStoreItemShared *_shared;
-
- QCA::KeyStore *keyStore;
- QCA::KeyStoreEntry keyStoreEntry;
-
- KeyStoreItem(Type type, KeyStoreItemShared *shared) :
- _type(type),
- _shared(shared)
- {
- setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
- }
-
- void setStore(const QString &name, QCA::KeyStore::Type type)
- {
- setData(name, NameRole);
- setData((int)type, SubTypeRole);
- }
-
- void setEntry(const QString &name, QCA::KeyStoreEntry::Type type, bool available, int pos)
- {
- setData(name, NameRole);
- setData((int)type, SubTypeRole);
- setData(available, AvailabilityRole);
- setData(pos, PositionRole);
- }
-
- virtual QVariant data(int role) const
- {
- if(role == Qt::DisplayRole)
- {
- if(_type == Store)
- {
- return data(NameRole).toString();
- }
- else if(_type == Entry)
- {
- QString str = data(NameRole).toString();
- if(_shared && !data(AvailabilityRole).toBool())
- str += QString(" ") + _shared->notAvailableString;
- return str;
- }
- else
- return QStandardItem::data(role);
- }
- else if(role == Qt::DecorationRole)
- {
- if(_type == Entry)
- {
- QCA::KeyStoreEntry::Type type = (QCA::KeyStoreEntry::Type)data(SubTypeRole).toInt();
- return entryTypeToIcon(type);
- }
- else
- return QStandardItem::data(role);
- }
- else
- return QStandardItem::data(role);
- }
-
- virtual int type() const
- {
- return _type;
- }
-
- virtual QStandardItem *clone() const
- {
- return new KeyStoreItem(*this);
- }
+ enum Type {
+ Store = UserType,
+ Entry
+ };
+
+ enum Role {
+ NameRole = Qt::UserRole,
+ SubTypeRole,
+ AvailabilityRole,
+ PositionRole
+ };
+
+ QPixmap entryTypeToIcon(QCA::KeyStoreEntry::Type type) const
+ {
+ QPixmap out;
+ if (!_shared) {
+ return out;
+ }
+ const KeyStoreIconset &iconset = _shared->iconset;
+ switch (type) {
+ case QCA::KeyStoreEntry::TypeKeyBundle: out = iconset[KeySelectDlg::IconKeyBundle]; break;
+ case QCA::KeyStoreEntry::TypeCertificate: out = iconset[KeySelectDlg::IconCert]; break;
+ case QCA::KeyStoreEntry::TypeCRL: out = iconset[KeySelectDlg::IconCrl]; break;
+ case QCA::KeyStoreEntry::TypePGPSecretKey: out = iconset[KeySelectDlg::IconPgpSec]; break;
+ case QCA::KeyStoreEntry::TypePGPPublicKey: out = iconset[KeySelectDlg::IconPgpPub]; break;
+ default: break;
+ }
+ return out;
+ }
+
+ Type _type;
+ KeyStoreItemShared *_shared;
+
+ QCA::KeyStore *keyStore;
+ QCA::KeyStoreEntry keyStoreEntry;
+
+ KeyStoreItem(Type type, KeyStoreItemShared *shared) :
+ _type(type),
+ _shared(shared)
+ {
+ setFlags(Qt::ItemIsEnabled | Qt::ItemIsSelectable);
+ }
+
+ void setStore(const QString &name, QCA::KeyStore::Type type)
+ {
+ setData(name, NameRole);
+ setData((int)type, SubTypeRole);
+ }
+
+ void setEntry(const QString &name, QCA::KeyStoreEntry::Type type, bool available, int pos)
+ {
+ setData(name, NameRole);
+ setData((int)type, SubTypeRole);
+ setData(available, AvailabilityRole);
+ setData(pos, PositionRole);
+ }
+
+ virtual QVariant data(int role) const
+ {
+ if (role == Qt::DisplayRole) {
+ if (_type == Store) {
+ return data(NameRole).toString();
+ } else if (_type == Entry) {
+ QString str = data(NameRole).toString();
+ if (_shared && !data(AvailabilityRole).toBool()) {
+ str += QString(" ") + _shared->notAvailableString;
+ }
+ return str;
+ } else {
+ return QStandardItem::data(role);
+ }
+ } else if (role == Qt::DecorationRole) {
+ if (_type == Entry) {
+ QCA::KeyStoreEntry::Type type = (QCA::KeyStoreEntry::Type)data(SubTypeRole).toInt();
+ return entryTypeToIcon(type);
+ } else {
+ return QStandardItem::data(role);
+ }
+ } else {
+ return QStandardItem::data(role);
+ }
+ }
+
+ virtual int type() const
+ {
+ return _type;
+ }
+
+ virtual QStandardItem *clone() const
+ {
+ return new KeyStoreItem(*this);
+ }
};
class KeyStoreModel : public QStandardItemModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeyStoreItemShared shared;
-
- QCA::KeyStoreManager ksm;
-
- KeyStoreModel(QObject *parent = 0) :
- QStandardItemModel(parent), ksm(this)
- {
- shared.notAvailableString = tr("(not available)");
-
- // make sure keystores are started
- QCA::KeyStoreManager::start();
-
- connect(&ksm, SIGNAL(keyStoreAvailable(const QString &)), SLOT(ks_available(const QString &)));
- QStringList list = ksm.keyStores();
- foreach(const QString &s, list)
- ks_available(s);
-
- setSortRole(KeyStoreItem::PositionRole);
- }
-
- KeyStoreItem *itemFromStore(QCA::KeyStore *ks) const
- {
- for(int n = 0; n < rowCount(); ++n)
- {
- KeyStoreItem *i = (KeyStoreItem *)item(n);
- if(i->keyStore == ks)
- return i;
- }
- return 0;
- }
+ KeyStoreItemShared shared;
+
+ QCA::KeyStoreManager ksm;
+
+ KeyStoreModel(QObject *parent = 0) :
+ QStandardItemModel(parent), ksm(this)
+ {
+ shared.notAvailableString = tr("(not available)");
+
+ // make sure keystores are started
+ QCA::KeyStoreManager::start();
+
+ connect(&ksm, SIGNAL(keyStoreAvailable(QString)), SLOT(ks_available(QString)));
+ QStringList list = ksm.keyStores();
+ foreach (const QString &s, list) {
+ ks_available(s);
+ }
+
+ setSortRole(KeyStoreItem::PositionRole);
+ }
+
+ KeyStoreItem *itemFromStore(QCA::KeyStore *ks) const
+ {
+ for (int n = 0; n < rowCount(); ++n) {
+ KeyStoreItem *i = (KeyStoreItem *)item(n);
+ if (i->keyStore == ks) {
+ return i;
+ }
+ }
+ return 0;
+ }
private slots:
- void ks_available(const QString &keyStoreId)
- {
- QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, &ksm);
+ void ks_available(const QString &keyStoreId)
+ {
+ QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, &ksm);
#ifdef ONLY_SHOW_KEYBUNDLE
- // only list stores containing keybundles (non-pgp identities)
- if(!ks->holdsIdentities() || ks->type() == QCA::KeyStore::PGPKeyring)
- return;
+ // only list stores containing keybundles (non-pgp identities)
+ if (!ks->holdsIdentities() || ks->type() == QCA::KeyStore::PGPKeyring) {
+ return;
+ }
#endif
- connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
- connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
+ connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
+ connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
- KeyStoreItem *store_item = new KeyStoreItem(KeyStoreItem::Store, &shared);
- store_item->setStore(ks->name(), ks->type());
- store_item->keyStore = ks;
- ks->startAsynchronousMode();
- appendRow(store_item);
- }
+ KeyStoreItem *store_item = new KeyStoreItem(KeyStoreItem::Store, &shared);
+ store_item->setStore(ks->name(), ks->type());
+ store_item->keyStore = ks;
+ ks->startAsynchronousMode();
+ appendRow(store_item);
+ }
- void ks_updated()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
- KeyStoreItem *store_item = itemFromStore(ks);
- Q_ASSERT(store_item);
+ void ks_updated()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+ KeyStoreItem *store_item = itemFromStore(ks);
+ Q_ASSERT(store_item);
- QList<QCA::KeyStoreEntry> newEntries = ks->entryList();
+ QList<QCA::KeyStoreEntry> newEntries = ks->entryList();
#ifdef ONLY_SHOW_KEYBUNDLE
- // ignore entries that are not keybundles
- for(int n = 0; n < newEntries.count(); ++n)
- {
- if(newEntries[n].type() != QCA::KeyStoreEntry::TypeKeyBundle)
- {
- newEntries.removeAt(n);
- --n; // adjust position
- }
- }
+ // ignore entries that are not keybundles
+ for (int n = 0; n < newEntries.count(); ++n) {
+ if (newEntries[n].type() != QCA::KeyStoreEntry::TypeKeyBundle) {
+ newEntries.removeAt(n);
+ --n; // adjust position
+ }
+ }
#endif
- // update the store item itself
- store_item->setStore(ks->name(), ks->type());
-
- // handle removed child entries
- for(int n = 0; n < store_item->rowCount(); ++n)
- {
- KeyStoreItem *i = (KeyStoreItem *)store_item->child(n);
-
- // is the existing entry in the new list?
- bool found = false;
- foreach(const QCA::KeyStoreEntry &ne, newEntries)
- {
- if(ne.id() == i->keyStoreEntry.id())
- {
- found = true;
- break;
- }
- }
-
- // if not, remove it
- if(!found)
- {
- store_item->removeRow(n);
- --n; // adjust position
- }
- }
-
- // handle added/updated child entries
- for(int n = 0; n < newEntries.count(); ++n)
- {
- const QCA::KeyStoreEntry &ne = newEntries[n];
-
- // was this entry in the original list?
- KeyStoreItem *entry_item = 0;
- for(int k = 0; k < store_item->rowCount(); ++k)
- {
- KeyStoreItem *i = (KeyStoreItem *)store_item->child(k);
- if(i->keyStoreEntry.id() == ne.id())
- {
- entry_item = i;
- break;
- }
- }
-
- // if not, add it
- if(!entry_item)
- {
- entry_item = new KeyStoreItem(KeyStoreItem::Entry, &shared);
- entry_item->keyStoreEntry = ne;
- entry_item->setEntry(newEntries[n].name(), newEntries[n].type(), newEntries[n].isAvailable(), n);
- store_item->appendRow(entry_item);
- }
- // if so, update it
- else
- {
- entry_item->keyStoreEntry = ne;
- entry_item->setEntry(newEntries[n].name(), newEntries[n].type(), newEntries[n].isAvailable(), n);
- }
- }
-
- store_item->sortChildren(0);
- }
-
- void ks_unavailable()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
- KeyStoreItem *store_item = itemFromStore(ks);
- Q_ASSERT(store_item);
-
- store_item->removeRows(0, store_item->rowCount());
- removeRow(store_item->row());
- delete ks;
- }
+ // update the store item itself
+ store_item->setStore(ks->name(), ks->type());
+
+ // handle removed child entries
+ for (int n = 0; n < store_item->rowCount(); ++n) {
+ KeyStoreItem *i = (KeyStoreItem *)store_item->child(n);
+
+ // is the existing entry in the new list?
+ bool found = false;
+ foreach (const QCA::KeyStoreEntry &ne, newEntries) {
+ if (ne.id() == i->keyStoreEntry.id()) {
+ found = true;
+ break;
+ }
+ }
+
+ // if not, remove it
+ if (!found) {
+ store_item->removeRow(n);
+ --n; // adjust position
+ }
+ }
+
+ // handle added/updated child entries
+ for (int n = 0; n < newEntries.count(); ++n) {
+ const QCA::KeyStoreEntry &ne = newEntries[n];
+
+ // was this entry in the original list?
+ KeyStoreItem *entry_item = 0;
+ for (int k = 0; k < store_item->rowCount(); ++k) {
+ KeyStoreItem *i = (KeyStoreItem *)store_item->child(k);
+ if (i->keyStoreEntry.id() == ne.id()) {
+ entry_item = i;
+ break;
+ }
+ }
+
+ // if not, add it
+ if (!entry_item) {
+ entry_item = new KeyStoreItem(KeyStoreItem::Entry, &shared);
+ entry_item->keyStoreEntry = ne;
+ entry_item->setEntry(newEntries[n].name(), newEntries[n].type(), newEntries[n].isAvailable(), n);
+ store_item->appendRow(entry_item);
+ }
+ // if so, update it
+ else {
+ entry_item->keyStoreEntry = ne;
+ entry_item->setEntry(newEntries[n].name(), newEntries[n].type(), newEntries[n].isAvailable(), n);
+ }
+ }
+
+ store_item->sortChildren(0);
+ }
+
+ void ks_unavailable()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+ KeyStoreItem *store_item = itemFromStore(ks);
+ Q_ASSERT(store_item);
+
+ store_item->removeRows(0, store_item->rowCount());
+ removeRow(store_item->row());
+ delete ks;
+ }
};
class KeySelectDlg::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeySelectDlg *q;
- Ui_KeySelect ui;
- KeyStoreModel *model;
- QCA::KeyStoreEntry cur_entry;
- QAction *actionView;
-
- Private(KeySelectDlg *_q) :
- QObject(_q),
- q(_q)
- {
- ui.setupUi(q);
-
- model = new KeyStoreModel(this);
- connect(&model->ksm, SIGNAL(busyStarted()), SLOT(ksm_busyStarted()));
- connect(&model->ksm, SIGNAL(busyFinished()), SLOT(ksm_busyFinished()));
- if(model->ksm.isBusy())
- ksm_busyStarted();
-
- ui.lv_stores->header()->hide();
- ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
- ui.lv_stores->setModel(model);
- ui.lv_stores->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui.lv_stores->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(stores_selectionChanged(const QItemSelection &, const QItemSelection &)));
- connect(ui.lv_stores, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(stores_customContextMenuRequested(const QPoint &)));
-
- actionView = new QAction(tr("&View"), this);
- connect(actionView, SIGNAL(triggered()), SLOT(view()));
- actionView->setEnabled(false);
- }
+ KeySelectDlg *q;
+ Ui_KeySelect ui;
+ KeyStoreModel *model;
+ QCA::KeyStoreEntry cur_entry;
+ QAction *actionView;
+
+ Private(KeySelectDlg *_q) :
+ QObject(_q),
+ q(_q)
+ {
+ ui.setupUi(q);
+
+ model = new KeyStoreModel(this);
+ connect(&model->ksm, SIGNAL(busyStarted()), SLOT(ksm_busyStarted()));
+ connect(&model->ksm, SIGNAL(busyFinished()), SLOT(ksm_busyFinished()));
+ if (model->ksm.isBusy()) {
+ ksm_busyStarted();
+ }
+
+ ui.lv_stores->header()->hide();
+ ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
+ ui.lv_stores->setModel(model);
+ ui.lv_stores->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(ui.lv_stores->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(stores_selectionChanged(QItemSelection,QItemSelection)));
+ connect(ui.lv_stores, SIGNAL(customContextMenuRequested(QPoint)), SLOT(stores_customContextMenuRequested(QPoint)));
+
+ actionView = new QAction(tr("&View"), this);
+ connect(actionView, SIGNAL(triggered()), SLOT(view()));
+ actionView->setEnabled(false);
+ }
private slots:
- void ksm_busyStarted()
- {
- ui.lb_busy->setText(tr("Looking for devices..."));
- }
-
- void ksm_busyFinished()
- {
- ui.lb_busy->setText("");
- }
-
- void stores_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
- {
- Q_UNUSED(deselected);
-
- KeyStoreItem *i = 0;
- if(!selected.indexes().isEmpty())
- {
- QModelIndex index = selected.indexes().first();
- i = (KeyStoreItem *)model->itemFromIndex(index);
- }
-
- bool viewable = false;
- bool choosable = false;
- if(i && i->type() == KeyStoreItem::Entry)
- {
- QCA::KeyStoreEntry entry = i->keyStoreEntry;
- if(entry.type() == QCA::KeyStoreEntry::TypeKeyBundle)
- {
- viewable = true;
- choosable = true;
- cur_entry = entry;
- }
- }
-
- if(!choosable)
- cur_entry = QCA::KeyStoreEntry();
-
- actionView->setEnabled(viewable);
-
- QPushButton *ok = ui.buttonBox->button(QDialogButtonBox::Ok);
- if(choosable && !ok->isEnabled())
- ok->setEnabled(true);
- else if(!choosable && ok->isEnabled())
- ok->setEnabled(false);
- }
-
- void stores_customContextMenuRequested(const QPoint &pos)
- {
- QItemSelection selection = ui.lv_stores->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
-
- QModelIndex index = selection.indexes().first();
- KeyStoreItem *i = (KeyStoreItem *)model->itemFromIndex(index);
- if(i && i->type() == KeyStoreItem::Entry)
- {
- QMenu menu(q);
- menu.addAction(actionView);
- menu.exec(ui.lv_stores->viewport()->mapToGlobal(pos));
- }
- }
-
- void view()
- {
- emit q->viewCertificate(cur_entry.keyBundle().certificateChain());
- }
+ void ksm_busyStarted()
+ {
+ ui.lb_busy->setText(tr("Looking for devices..."));
+ }
+
+ void ksm_busyFinished()
+ {
+ ui.lb_busy->setText("");
+ }
+
+ void stores_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
+ {
+ Q_UNUSED(deselected);
+
+ KeyStoreItem *i = 0;
+ if (!selected.indexes().isEmpty()) {
+ QModelIndex index = selected.indexes().first();
+ i = (KeyStoreItem *)model->itemFromIndex(index);
+ }
+
+ bool viewable = false;
+ bool choosable = false;
+ if (i && i->type() == KeyStoreItem::Entry) {
+ QCA::KeyStoreEntry entry = i->keyStoreEntry;
+ if (entry.type() == QCA::KeyStoreEntry::TypeKeyBundle) {
+ viewable = true;
+ choosable = true;
+ cur_entry = entry;
+ }
+ }
+
+ if (!choosable) {
+ cur_entry = QCA::KeyStoreEntry();
+ }
+
+ actionView->setEnabled(viewable);
+
+ QPushButton *ok = ui.buttonBox->button(QDialogButtonBox::Ok);
+ if (choosable && !ok->isEnabled()) {
+ ok->setEnabled(true);
+ } else if (!choosable && ok->isEnabled()) {
+ ok->setEnabled(false);
+ }
+ }
+
+ void stores_customContextMenuRequested(const QPoint &pos)
+ {
+ QItemSelection selection = ui.lv_stores->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+
+ QModelIndex index = selection.indexes().first();
+ KeyStoreItem *i = (KeyStoreItem *)model->itemFromIndex(index);
+ if (i && i->type() == KeyStoreItem::Entry) {
+ QMenu menu(q);
+ menu.addAction(actionView);
+ menu.exec(ui.lv_stores->viewport()->mapToGlobal(pos));
+ }
+ }
+
+ void view()
+ {
+ emit q->viewCertificate(cur_entry.keyBundle().certificateChain());
+ }
};
KeySelectDlg::KeySelectDlg(QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
KeySelectDlg::~KeySelectDlg()
{
- delete d;
+ delete d;
}
void KeySelectDlg::setIcon(IconType type, const QPixmap &icon)
{
- d->model->shared.iconset[type] = icon;
+ d->model->shared.iconset[type] = icon;
}
void KeySelectDlg::accept()
{
- QCA::KeyStoreEntry entry = d->cur_entry;
- QDialog::accept();
- emit selected(entry);
+ QCA::KeyStoreEntry entry = d->cur_entry;
+ QDialog::accept();
+ emit selected(entry);
}
#include "keyselectdlg.moc"
diff --git a/examples/cmssigner/keyselectdlg.h b/examples/cmssigner/keyselectdlg.h
index 72abf79d..eef3d7b5 100644
--- a/examples/cmssigner/keyselectdlg.h
+++ b/examples/cmssigner/keyselectdlg.h
@@ -1,66 +1,65 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef KEYSELECTDLG_H
#define KEYSELECTDLG_H
#include <QDialog>
class QPixmap;
namespace QCA
{
- class CertificateChain;
- class KeyStoreEntry;
+class CertificateChain;
+class KeyStoreEntry;
}
class KeySelectDlg : public QDialog
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum IconType
- {
- IconCert,
- IconCrl,
- IconKeyBundle,
- IconPgpPub,
- IconPgpSec
- };
+ enum IconType {
+ IconCert,
+ IconCrl,
+ IconKeyBundle,
+ IconPgpPub,
+ IconPgpSec
+ };
- KeySelectDlg(QWidget *parent = 0);
- ~KeySelectDlg();
+ KeySelectDlg(QWidget *parent = 0);
+ ~KeySelectDlg();
- void setIcon(IconType type, const QPixmap &icon);
+ void setIcon(IconType type, const QPixmap &icon);
signals:
- void selected(const QCA::KeyStoreEntry &entry);
- void viewCertificate(const QCA::CertificateChain &chain);
+ void selected(const QCA::KeyStoreEntry &entry);
+ void viewCertificate(const QCA::CertificateChain &chain);
protected slots:
- virtual void accept();
+ virtual void accept();
private:
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
#endif
diff --git a/examples/cmssigner/main.cpp b/examples/cmssigner/main.cpp
index 5afae6f7..cff7a6ee 100644
--- a/examples/cmssigner/main.cpp
+++ b/examples/cmssigner/main.cpp
@@ -1,960 +1,946 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <QtCore>
#include <QtGui>
#include <QtCrypto>
#include <QMessageBox>
#include <QFileDialog>
#include "ui_mainwin.h"
#include "certviewdlg.h"
#include "keyselectdlg.h"
#include "pkcs11configdlg/pkcs11configdlg.h"
#include "certitem.h"
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
#define VERSION "1.0.0"
class Icons
{
public:
- QPixmap cert, crl, keybundle, pgppub, pgpsec;
+ QPixmap cert, crl, keybundle, pgppub, pgpsec;
};
Icons *g_icons = 0;
//----------------------------------------------------------------------------
// Operation
//----------------------------------------------------------------------------
class Operation : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- Operation(QObject *parent = 0) :
- QObject(parent)
- {
- }
+ Operation(QObject *parent = 0) :
+ QObject(parent)
+ {
+ }
signals:
- void error(const QString &str);
+ void error(const QString &str);
};
static QString validityToString(QCA::Validity v)
{
- QString s;
- switch(v)
- {
- case QCA::ValidityGood:
- s = Operation::tr("Validated");
- break;
- case QCA::ErrorRejected:
- s = Operation::tr("Root CA is marked to reject the specified purpose");
- break;
- case QCA::ErrorUntrusted:
- s = Operation::tr("Certificate not trusted for the required purpose");
- break;
- case QCA::ErrorSignatureFailed:
- s = Operation::tr("Invalid signature");
- break;
- case QCA::ErrorInvalidCA:
- s = Operation::tr("Invalid CA certificate");
- break;
- case QCA::ErrorInvalidPurpose:
- s = Operation::tr("Invalid certificate purpose");
- break;
- case QCA::ErrorSelfSigned:
- s = Operation::tr("Certificate is self-signed");
- break;
- case QCA::ErrorRevoked:
- s = Operation::tr("Certificate has been revoked");
- break;
- case QCA::ErrorPathLengthExceeded:
- s = Operation::tr("Maximum certificate chain length exceeded");
- break;
- case QCA::ErrorExpired:
- s = Operation::tr("Certificate has expired");
- break;
- case QCA::ErrorExpiredCA:
- s = Operation::tr("CA has expired");
- break;
- case QCA::ErrorValidityUnknown:
- default:
- s = Operation::tr("General certificate validation error");
- break;
- }
- return s;
+ QString s;
+ switch (v) {
+ case QCA::ValidityGood:
+ s = Operation::tr("Validated");
+ break;
+ case QCA::ErrorRejected:
+ s = Operation::tr("Root CA is marked to reject the specified purpose");
+ break;
+ case QCA::ErrorUntrusted:
+ s = Operation::tr("Certificate not trusted for the required purpose");
+ break;
+ case QCA::ErrorSignatureFailed:
+ s = Operation::tr("Invalid signature");
+ break;
+ case QCA::ErrorInvalidCA:
+ s = Operation::tr("Invalid CA certificate");
+ break;
+ case QCA::ErrorInvalidPurpose:
+ s = Operation::tr("Invalid certificate purpose");
+ break;
+ case QCA::ErrorSelfSigned:
+ s = Operation::tr("Certificate is self-signed");
+ break;
+ case QCA::ErrorRevoked:
+ s = Operation::tr("Certificate has been revoked");
+ break;
+ case QCA::ErrorPathLengthExceeded:
+ s = Operation::tr("Maximum certificate chain length exceeded");
+ break;
+ case QCA::ErrorExpired:
+ s = Operation::tr("Certificate has expired");
+ break;
+ case QCA::ErrorExpiredCA:
+ s = Operation::tr("CA has expired");
+ break;
+ case QCA::ErrorValidityUnknown:
+ default:
+ s = Operation::tr("General certificate validation error");
+ break;
+ }
+ return s;
}
static QString smErrorToString(QCA::SecureMessage::Error e)
{
- QString s;
- switch(e)
- {
- case QCA::SecureMessage::ErrorPassphrase:
- s = Operation::tr("Invalid passphrase.");
- break;
- case QCA::SecureMessage::ErrorFormat:
- s = Operation::tr("Bad input format.");
- break;
- case QCA::SecureMessage::ErrorSignerExpired:
- s = Operation::tr("Signer key is expired.");
- break;
- case QCA::SecureMessage::ErrorSignerInvalid:
- s = Operation::tr("Signer key is invalid.");
- break;
- case QCA::SecureMessage::ErrorEncryptExpired:
- s = Operation::tr("Encrypting key is expired.");
- break;
- case QCA::SecureMessage::ErrorEncryptUntrusted:
- s = Operation::tr("Encrypting key is untrusted.");
- break;
- case QCA::SecureMessage::ErrorEncryptInvalid:
- s = Operation::tr("Encrypting key is invalid.");
- break;
- case QCA::SecureMessage::ErrorNeedCard:
- s = Operation::tr("Card was needed but not found.");
- break;
- case QCA::SecureMessage::ErrorCertKeyMismatch:
- s = Operation::tr("Certificate and private key don't match.");
- break;
- case QCA::SecureMessage::ErrorUnknown:
- default:
- s = Operation::tr("General error.");
- break;
- }
- return s;
+ QString s;
+ switch (e) {
+ case QCA::SecureMessage::ErrorPassphrase:
+ s = Operation::tr("Invalid passphrase.");
+ break;
+ case QCA::SecureMessage::ErrorFormat:
+ s = Operation::tr("Bad input format.");
+ break;
+ case QCA::SecureMessage::ErrorSignerExpired:
+ s = Operation::tr("Signer key is expired.");
+ break;
+ case QCA::SecureMessage::ErrorSignerInvalid:
+ s = Operation::tr("Signer key is invalid.");
+ break;
+ case QCA::SecureMessage::ErrorEncryptExpired:
+ s = Operation::tr("Encrypting key is expired.");
+ break;
+ case QCA::SecureMessage::ErrorEncryptUntrusted:
+ s = Operation::tr("Encrypting key is untrusted.");
+ break;
+ case QCA::SecureMessage::ErrorEncryptInvalid:
+ s = Operation::tr("Encrypting key is invalid.");
+ break;
+ case QCA::SecureMessage::ErrorNeedCard:
+ s = Operation::tr("Card was needed but not found.");
+ break;
+ case QCA::SecureMessage::ErrorCertKeyMismatch:
+ s = Operation::tr("Certificate and private key don't match.");
+ break;
+ case QCA::SecureMessage::ErrorUnknown:
+ default:
+ s = Operation::tr("General error.");
+ break;
+ }
+ return s;
}
static QString smsIdentityToString(const QCA::SecureMessageSignature &sig)
{
- QString s;
- switch(sig.identityResult())
- {
- case QCA::SecureMessageSignature::Valid:
- break;
- case QCA::SecureMessageSignature::InvalidSignature:
- s = Operation::tr("Invalid signature");
- break;
- case QCA::SecureMessageSignature::InvalidKey:
- s = Operation::tr("Invalid key: %1").arg(validityToString(sig.keyValidity()));
- break;
- case QCA::SecureMessageSignature::NoKey:
- s = Operation::tr("Key not found");
- break;
- default: // this should not really be possible
- s = Operation::tr("Unknown");
- break;
- }
- return s;
+ QString s;
+ switch (sig.identityResult()) {
+ case QCA::SecureMessageSignature::Valid:
+ break;
+ case QCA::SecureMessageSignature::InvalidSignature:
+ s = Operation::tr("Invalid signature");
+ break;
+ case QCA::SecureMessageSignature::InvalidKey:
+ s = Operation::tr("Invalid key: %1").arg(validityToString(sig.keyValidity()));
+ break;
+ case QCA::SecureMessageSignature::NoKey:
+ s = Operation::tr("Key not found");
+ break;
+ default: // this should not really be possible
+ s = Operation::tr("Unknown");
+ break;
+ }
+ return s;
}
class SignOperation : public Operation
{
- Q_OBJECT
+ Q_OBJECT
private:
- QByteArray in;
- CertItemStore *store;
- int id;
- QCA::CMS *cms;
- CertItemPrivateLoader *loader;
- QCA::SecureMessage *msg;
- int pending;
+ QByteArray in;
+ CertItemStore *store;
+ int id;
+ QCA::CMS *cms;
+ CertItemPrivateLoader *loader;
+ QCA::SecureMessage *msg;
+ int pending;
public:
- SignOperation(const QByteArray &_in, CertItemStore *_store, int _id, QCA::CMS *_cms, QObject *parent = 0) :
- Operation(parent),
- in(_in),
- store(_store),
- id(_id),
- cms(_cms),
- msg(0)
- {
- loader = new CertItemPrivateLoader(store, this);
- connect(loader, SIGNAL(finished()), SLOT(loader_finished()));
- loader->start(id);
- }
+ SignOperation(const QByteArray &_in, CertItemStore *_store, int _id, QCA::CMS *_cms, QObject *parent = 0) :
+ Operation(parent),
+ in(_in),
+ store(_store),
+ id(_id),
+ cms(_cms),
+ msg(0)
+ {
+ loader = new CertItemPrivateLoader(store, this);
+ connect(loader, SIGNAL(finished()), SLOT(loader_finished()));
+ loader->start(id);
+ }
signals:
- void loadError();
- void finished(const QString &sig);
+ void loadError();
+ void finished(const QString &sig);
private slots:
- void loader_finished()
- {
- QCA::PrivateKey privateKey = loader->privateKey();
- delete loader;
- loader = 0;
-
- if(privateKey.isNull())
- {
- emit loadError();
- return;
- }
-
- CertItem item = store->itemFromId(id);
-
- QCA::SecureMessageKey signer;
- signer.setX509CertificateChain(item.certificateChain());
- signer.setX509PrivateKey(privateKey);
-
- msg = new QCA::SecureMessage(cms);
- connect(msg, SIGNAL(bytesWritten(int)), SLOT(msg_bytesWritten(int)));
- connect(msg, SIGNAL(finished()), SLOT(msg_finished()));
- msg->setFormat(QCA::SecureMessage::Ascii);
- msg->setSigner(signer);
- msg->startSign(QCA::SecureMessage::Detached);
-
- pending = 0;
- update();
- }
-
- void update()
- {
- QByteArray buf = in.mid(0, 16384 - pending); // 16k chunks
- in = in.mid(buf.size());
- pending += buf.size();
- msg->update(buf);
- }
-
- void msg_bytesWritten(int x)
- {
- pending -= x;
-
- if(in.isEmpty() && pending == 0)
- msg->end();
- else
- update();
- }
-
- void msg_finished()
- {
- if(!msg->success())
- {
- QString str = smErrorToString(msg->errorCode());
- delete msg;
- msg = 0;
- emit error(tr("Error during sign operation.\nReason: %1").arg(str));
- return;
- }
-
- QByteArray result = msg->signature();
- delete msg;
- msg = 0;
- emit finished(QString::fromLatin1(result));
- }
+ void loader_finished()
+ {
+ QCA::PrivateKey privateKey = loader->privateKey();
+ delete loader;
+ loader = 0;
+
+ if (privateKey.isNull()) {
+ emit loadError();
+ return;
+ }
+
+ CertItem item = store->itemFromId(id);
+
+ QCA::SecureMessageKey signer;
+ signer.setX509CertificateChain(item.certificateChain());
+ signer.setX509PrivateKey(privateKey);
+
+ msg = new QCA::SecureMessage(cms);
+ connect(msg, SIGNAL(bytesWritten(int)), SLOT(msg_bytesWritten(int)));
+ connect(msg, SIGNAL(finished()), SLOT(msg_finished()));
+ msg->setFormat(QCA::SecureMessage::Ascii);
+ msg->setSigner(signer);
+ msg->startSign(QCA::SecureMessage::Detached);
+
+ pending = 0;
+ update();
+ }
+
+ void update()
+ {
+ QByteArray buf = in.mid(0, 16384 - pending); // 16k chunks
+ in = in.mid(buf.size());
+ pending += buf.size();
+ msg->update(buf);
+ }
+
+ void msg_bytesWritten(int x)
+ {
+ pending -= x;
+
+ if (in.isEmpty() && pending == 0) {
+ msg->end();
+ } else {
+ update();
+ }
+ }
+
+ void msg_finished()
+ {
+ if (!msg->success()) {
+ QString str = smErrorToString(msg->errorCode());
+ delete msg;
+ msg = 0;
+ emit error(tr("Error during sign operation.\nReason: %1").arg(str));
+ return;
+ }
+
+ QByteArray result = msg->signature();
+ delete msg;
+ msg = 0;
+ emit finished(QString::fromLatin1(result));
+ }
};
class VerifyOperation : public Operation
{
- Q_OBJECT
+ Q_OBJECT
private:
- QByteArray in, sig;
- QCA::CMS *cms;
- QCA::SecureMessage *msg;
- int pending;
+ QByteArray in, sig;
+ QCA::CMS *cms;
+ QCA::SecureMessage *msg;
+ int pending;
public:
- QCA::SecureMessageSignature signer;
-
- VerifyOperation(const QByteArray &_in, const QByteArray &_sig, QCA::CMS *_cms, QObject *parent = 0) :
- Operation(parent),
- in(_in),
- sig(_sig),
- cms(_cms),
- msg(0)
- {
- msg = new QCA::SecureMessage(cms);
- connect(msg, SIGNAL(bytesWritten(int)), SLOT(msg_bytesWritten(int)));
- connect(msg, SIGNAL(finished()), SLOT(msg_finished()));
- msg->setFormat(QCA::SecureMessage::Ascii);
- msg->startVerify(sig);
-
- pending = 0;
- update();
- }
+ QCA::SecureMessageSignature signer;
+
+ VerifyOperation(const QByteArray &_in, const QByteArray &_sig, QCA::CMS *_cms, QObject *parent = 0) :
+ Operation(parent),
+ in(_in),
+ sig(_sig),
+ cms(_cms),
+ msg(0)
+ {
+ msg = new QCA::SecureMessage(cms);
+ connect(msg, SIGNAL(bytesWritten(int)), SLOT(msg_bytesWritten(int)));
+ connect(msg, SIGNAL(finished()), SLOT(msg_finished()));
+ msg->setFormat(QCA::SecureMessage::Ascii);
+ msg->startVerify(sig);
+
+ pending = 0;
+ update();
+ }
signals:
- void finished();
+ void finished();
private slots:
- void update()
- {
- QByteArray buf = in.mid(0, 16384 - pending); // 16k chunks
- in = in.mid(buf.size());
- pending += buf.size();
- msg->update(buf);
- }
-
- void msg_bytesWritten(int x)
- {
- pending -= x;
-
- if(in.isEmpty() && pending == 0)
- msg->end();
- else
- update();
- }
-
- void msg_finished()
- {
- if(!msg->success())
- {
- QString str = smErrorToString(msg->errorCode());
- delete msg;
- msg = 0;
- emit error(tr("Error during verify operation.\nReason: %1").arg(str));
- return;
- }
-
- signer = msg->signer();
- delete msg;
- msg = 0;
-
- if(signer.identityResult() != QCA::SecureMessageSignature::Valid)
- {
- QString str = smsIdentityToString(signer);
- emit error(tr("Verification failed!\nReason: %1").arg(str));
- return;
- }
-
- emit finished();
- }
+ void update()
+ {
+ QByteArray buf = in.mid(0, 16384 - pending); // 16k chunks
+ in = in.mid(buf.size());
+ pending += buf.size();
+ msg->update(buf);
+ }
+
+ void msg_bytesWritten(int x)
+ {
+ pending -= x;
+
+ if (in.isEmpty() && pending == 0) {
+ msg->end();
+ } else {
+ update();
+ }
+ }
+
+ void msg_finished()
+ {
+ if (!msg->success()) {
+ QString str = smErrorToString(msg->errorCode());
+ delete msg;
+ msg = 0;
+ emit error(tr("Error during verify operation.\nReason: %1").arg(str));
+ return;
+ }
+
+ signer = msg->signer();
+ delete msg;
+ msg = 0;
+
+ if (signer.identityResult() != QCA::SecureMessageSignature::Valid) {
+ QString str = smsIdentityToString(signer);
+ emit error(tr("Verification failed!\nReason: %1").arg(str));
+ return;
+ }
+
+ emit finished();
+ }
};
//----------------------------------------------------------------------------
// MainWin
//----------------------------------------------------------------------------
static QString get_fingerprint(const QCA::Certificate &cert)
{
- QString hex = QCA::Hash("sha1").hashToString(cert.toDER());
- QString out;
- for(int n = 0; n < hex.count(); ++n)
- {
- if(n != 0 && n % 2 == 0)
- out += ':';
- out += hex[n];
- }
- return out;
+ QString hex = QCA::Hash("sha1").hashToString(cert.toDER());
+ QString out;
+ for (int n = 0; n < hex.count(); ++n) {
+ if (n != 0 && n % 2 == 0) {
+ out += ':';
+ }
+ out += hex[n];
+ }
+ return out;
}
class MainWin : public QMainWindow
{
- Q_OBJECT
+ Q_OBJECT
private:
- Ui_MainWin ui;
- CertItemStore *users, *roots;
- QCA::CMS *cms;
- Operation *op;
- QAction *actionView, *actionRename, *actionRemove;
- QCA::Certificate self_signed_verify_cert;
- int auto_import_req_id;
+ Ui_MainWin ui;
+ CertItemStore *users, *roots;
+ QCA::CMS *cms;
+ Operation *op;
+ QAction *actionView, *actionRename, *actionRemove;
+ QCA::Certificate self_signed_verify_cert;
+ int auto_import_req_id;
public:
- MainWin(QWidget *parent = 0) :
- QMainWindow(parent),
- op(0),
- auto_import_req_id(-1)
- {
- ui.setupUi(this);
-
- g_icons = new Icons;
- g_icons->cert = QPixmap(":/gfx/icons/cert16.png");
- g_icons->crl = QPixmap(":/gfx/icons/crl16.png");
- g_icons->keybundle = QPixmap(":/gfx/icons/keybundle16.png");
- g_icons->pgppub = QPixmap(":/gfx/icons/publickey16.png");
- g_icons->pgpsec = QPixmap(":/gfx/icons/keypair16.png");
- if(g_icons->cert.isNull() || g_icons->crl.isNull() || g_icons->keybundle.isNull() || g_icons->pgppub.isNull() || g_icons->pgpsec.isNull())
- printf("Warning: not all icons loaded\n");
-
- users = new CertItemStore(this);
- roots = new CertItemStore(this);
-
- setIcons(users);
- setIcons(roots);
-
- connect(users, SIGNAL(addSuccess(int, int)), SLOT(users_addSuccess(int, int)));
- connect(users, SIGNAL(addFailed(int)), SLOT(users_addFailed(int)));
-
- actionView = new QAction(tr("&View"), this);
- actionRename = new QAction(tr("Re&name"), this);
- actionRemove = new QAction(tr("Rem&ove"), this);
-
- connect(ui.actionLoadIdentityFile, SIGNAL(triggered()), SLOT(load_file()));
- connect(ui.actionLoadIdentityEntry, SIGNAL(triggered()), SLOT(load_device()));
- connect(ui.actionLoadAuthority, SIGNAL(triggered()), SLOT(load_root()));
- connect(ui.actionConfigurePkcs11, SIGNAL(triggered()), SLOT(mod_config()));
- connect(ui.actionQuit, SIGNAL(triggered()), SLOT(close()));
- connect(ui.actionAbout, SIGNAL(triggered()), SLOT(about()));
- connect(ui.pb_sign, SIGNAL(clicked()), SLOT(do_sign()));
- connect(ui.pb_verify, SIGNAL(clicked()), SLOT(do_verify()));
-
- connect(actionView, SIGNAL(triggered()), SLOT(item_view()));
- connect(actionRename, SIGNAL(triggered()), SLOT(item_rename()));
- connect(actionRemove, SIGNAL(triggered()), SLOT(item_remove()));
-
- ui.pb_sign->setEnabled(false);
-
- ui.lv_users->setModel(users);
- connect(ui.lv_users->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(users_selectionChanged(const QItemSelection &, const QItemSelection &)));
-
- ui.lv_users->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui.lv_users, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(users_customContextMenuRequested(const QPoint &)));
-
- ui.lv_authorities->setModel(roots);
-
- ui.lv_authorities->setContextMenuPolicy(Qt::CustomContextMenu);
- connect(ui.lv_authorities, SIGNAL(customContextMenuRequested(const QPoint &)), SLOT(roots_customContextMenuRequested(const QPoint &)));
-
- cms = new QCA::CMS(this);
-
- QStringList ulist, rlist;
- {
- QSettings settings("Affinix", "CMS Signer");
- ulist = settings.value("users").toStringList();
- rlist = settings.value("roots").toStringList();
- }
-
- users->load(ulist);
- roots->load(rlist);
- }
-
- ~MainWin()
- {
- QStringList ulist = users->save();
- QStringList rlist = roots->save();
-
- QSettings settings("Affinix", "CMS Signer");
- settings.setValue("users", ulist);
- settings.setValue("roots", rlist);
-
- delete g_icons;
- g_icons = 0;
- }
-
- void setIcons(CertItemStore *store)
- {
- store->setIcon(CertItemStore::IconCert, g_icons->cert);
- store->setIcon(CertItemStore::IconCrl, g_icons->crl);
- store->setIcon(CertItemStore::IconKeyBundle, g_icons->keybundle);
- store->setIcon(CertItemStore::IconPgpPub, g_icons->pgppub);
- store->setIcon(CertItemStore::IconPgpSec, g_icons->pgpsec);
- }
-
- QCA::CertificateCollection allCerts()
- {
- QCA::CertificateCollection col;
-
- // system store
- col += QCA::systemStore();
-
- // additional roots configured in application
- foreach(const CertItem &i, roots->items())
- col.addCertificate(i.certificateChain().primary());
-
- // user chains
- foreach(const CertItem &i, users->items())
- {
- foreach(const QCA::Certificate &cert, i.certificateChain())
- col.addCertificate(cert);
- }
-
- return col;
- }
-
- QCA::CertificateChain complete(const QCA::CertificateChain &chain)
- {
- return chain.complete(allCerts().certificates());
- }
+ MainWin(QWidget *parent = 0) :
+ QMainWindow(parent),
+ op(0),
+ auto_import_req_id(-1)
+ {
+ ui.setupUi(this);
+
+ g_icons = new Icons;
+ g_icons->cert = QPixmap(":/gfx/icons/cert16.png");
+ g_icons->crl = QPixmap(":/gfx/icons/crl16.png");
+ g_icons->keybundle = QPixmap(":/gfx/icons/keybundle16.png");
+ g_icons->pgppub = QPixmap(":/gfx/icons/publickey16.png");
+ g_icons->pgpsec = QPixmap(":/gfx/icons/keypair16.png");
+ if (g_icons->cert.isNull() || g_icons->crl.isNull() || g_icons->keybundle.isNull() || g_icons->pgppub.isNull() || g_icons->pgpsec.isNull()) {
+ printf("Warning: not all icons loaded\n");
+ }
+
+ users = new CertItemStore(this);
+ roots = new CertItemStore(this);
+
+ setIcons(users);
+ setIcons(roots);
+
+ connect(users, SIGNAL(addSuccess(int,int)), SLOT(users_addSuccess(int,int)));
+ connect(users, SIGNAL(addFailed(int)), SLOT(users_addFailed(int)));
+
+ actionView = new QAction(tr("&View"), this);
+ actionRename = new QAction(tr("Re&name"), this);
+ actionRemove = new QAction(tr("Rem&ove"), this);
+
+ connect(ui.actionLoadIdentityFile, SIGNAL(triggered()), SLOT(load_file()));
+ connect(ui.actionLoadIdentityEntry, SIGNAL(triggered()), SLOT(load_device()));
+ connect(ui.actionLoadAuthority, SIGNAL(triggered()), SLOT(load_root()));
+ connect(ui.actionConfigurePkcs11, SIGNAL(triggered()), SLOT(mod_config()));
+ connect(ui.actionQuit, SIGNAL(triggered()), SLOT(close()));
+ connect(ui.actionAbout, SIGNAL(triggered()), SLOT(about()));
+ connect(ui.pb_sign, SIGNAL(clicked()), SLOT(do_sign()));
+ connect(ui.pb_verify, SIGNAL(clicked()), SLOT(do_verify()));
+
+ connect(actionView, SIGNAL(triggered()), SLOT(item_view()));
+ connect(actionRename, SIGNAL(triggered()), SLOT(item_rename()));
+ connect(actionRemove, SIGNAL(triggered()), SLOT(item_remove()));
+
+ ui.pb_sign->setEnabled(false);
+
+ ui.lv_users->setModel(users);
+ connect(ui.lv_users->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(users_selectionChanged(QItemSelection,QItemSelection)));
+
+ ui.lv_users->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(ui.lv_users, SIGNAL(customContextMenuRequested(QPoint)), SLOT(users_customContextMenuRequested(QPoint)));
+
+ ui.lv_authorities->setModel(roots);
+
+ ui.lv_authorities->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(ui.lv_authorities, SIGNAL(customContextMenuRequested(QPoint)), SLOT(roots_customContextMenuRequested(QPoint)));
+
+ cms = new QCA::CMS(this);
+
+ QStringList ulist, rlist;
+ {
+ QSettings settings("Affinix", "CMS Signer");
+ ulist = settings.value("users").toStringList();
+ rlist = settings.value("roots").toStringList();
+ }
+
+ users->load(ulist);
+ roots->load(rlist);
+ }
+
+ ~MainWin()
+ {
+ QStringList ulist = users->save();
+ QStringList rlist = roots->save();
+
+ QSettings settings("Affinix", "CMS Signer");
+ settings.setValue("users", ulist);
+ settings.setValue("roots", rlist);
+
+ delete g_icons;
+ g_icons = 0;
+ }
+
+ void setIcons(CertItemStore *store)
+ {
+ store->setIcon(CertItemStore::IconCert, g_icons->cert);
+ store->setIcon(CertItemStore::IconCrl, g_icons->crl);
+ store->setIcon(CertItemStore::IconKeyBundle, g_icons->keybundle);
+ store->setIcon(CertItemStore::IconPgpPub, g_icons->pgppub);
+ store->setIcon(CertItemStore::IconPgpSec, g_icons->pgpsec);
+ }
+
+ QCA::CertificateCollection allCerts()
+ {
+ QCA::CertificateCollection col;
+
+ // system store
+ col += QCA::systemStore();
+
+ // additional roots configured in application
+ foreach (const CertItem &i, roots->items()) {
+ col.addCertificate(i.certificateChain().primary());
+ }
+
+ // user chains
+ foreach (const CertItem &i, users->items()) {
+ foreach (const QCA::Certificate &cert, i.certificateChain()) {
+ col.addCertificate(cert);
+ }
+ }
+
+ return col;
+ }
+
+ QCA::CertificateChain complete(const QCA::CertificateChain &chain)
+ {
+ return chain.complete(allCerts().certificates());
+ }
private slots:
- void load_file()
- {
- QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("X.509 Identities (*.p12 *.pfx)"));
- if(fileName.isEmpty())
- return;
-
- setEnabled(false);
- users->addFromFile(fileName);
- }
-
- void load_device()
- {
- KeySelectDlg *w = new KeySelectDlg(this);
- w->setAttribute(Qt::WA_DeleteOnClose, true);
- w->setWindowModality(Qt::WindowModal);
- connect(w, SIGNAL(selected(const QCA::KeyStoreEntry &)), SLOT(load_device_finished(const QCA::KeyStoreEntry &)));
- connect(w, SIGNAL(viewCertificate(const QCA::CertificateChain &)), SLOT(keyselect_viewCertificate(const QCA::CertificateChain &)));
- w->setIcon(KeySelectDlg::IconCert, g_icons->cert);
- w->setIcon(KeySelectDlg::IconCrl, g_icons->crl);
- w->setIcon(KeySelectDlg::IconKeyBundle, g_icons->keybundle);
- w->setIcon(KeySelectDlg::IconPgpPub, g_icons->pgppub);
- w->setIcon(KeySelectDlg::IconPgpSec, g_icons->pgpsec);
- w->show();
- }
-
- void load_device_finished(const QCA::KeyStoreEntry &entry)
- {
- users->addFromKeyStore(entry);
+ void load_file()
+ {
+ QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("X.509 Identities (*.p12 *.pfx)"));
+ if (fileName.isEmpty()) {
+ return;
+ }
+
+ setEnabled(false);
+ users->addFromFile(fileName);
+ }
+
+ void load_device()
+ {
+ KeySelectDlg *w = new KeySelectDlg(this);
+ w->setAttribute(Qt::WA_DeleteOnClose, true);
+ w->setWindowModality(Qt::WindowModal);
+ connect(w, SIGNAL(selected(QCA::KeyStoreEntry)), SLOT(load_device_finished(QCA::KeyStoreEntry)));
+ connect(w, SIGNAL(viewCertificate(QCA::CertificateChain)), SLOT(keyselect_viewCertificate(QCA::CertificateChain)));
+ w->setIcon(KeySelectDlg::IconCert, g_icons->cert);
+ w->setIcon(KeySelectDlg::IconCrl, g_icons->crl);
+ w->setIcon(KeySelectDlg::IconKeyBundle, g_icons->keybundle);
+ w->setIcon(KeySelectDlg::IconPgpPub, g_icons->pgppub);
+ w->setIcon(KeySelectDlg::IconPgpSec, g_icons->pgpsec);
+ w->show();
+ }
+
+ void load_device_finished(const QCA::KeyStoreEntry &entry)
+ {
+ users->addFromKeyStore(entry);
+ }
+
+ void load_root()
+ {
+ QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("X.509 Certificates (*.pem *.crt)"));
+ if (fileName.isEmpty()) {
+ return;
+ }
+
+ QCA::Certificate cert = QCA::Certificate::fromPEMFile(fileName);
+ if (cert.isNull()) {
+ QMessageBox::information(this, tr("Error"), tr("Error opening certificate file."));
+ return;
+ }
+
+ roots->addUser(cert);
+ }
+
+ void users_addSuccess(int req_id, int id)
+ {
+ if (req_id == auto_import_req_id) {
+ auto_import_req_id = -1;
+
+ CertItem i = users->itemFromId(id);
+
+ QMessageBox::information(this, tr("User added"), tr(
+ "This signature was made by a previously unknown user, and so the "
+ "user has now been added to the keyring as \"%1\"."
+ ).arg(i.name()));
+
+ verify_next();
+ return;
}
- void load_root()
- {
- QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"), QString(), tr("X.509 Certificates (*.pem *.crt)"));
- if(fileName.isEmpty())
- return;
-
- QCA::Certificate cert = QCA::Certificate::fromPEMFile(fileName);
- if(cert.isNull())
- {
- QMessageBox::information(this, tr("Error"), tr("Error opening certificate file."));
- return;
- }
-
- roots->addUser(cert);
- }
-
- void users_addSuccess(int req_id, int id)
- {
- if(req_id == auto_import_req_id)
- {
- auto_import_req_id = -1;
-
- CertItem i = users->itemFromId(id);
-
- QMessageBox::information(this, tr("User added"), tr(
- "This signature was made by a previously unknown user, and so the "
- "user has now been added to the keyring as \"%1\"."
- ).arg(i.name()));
-
- verify_next();
- return;
- }
-
- ui.lv_users->selectionModel()->select(users->index(users->rowFromId(id)), QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
-
- setEnabled(true);
- }
-
- void users_addFailed(int req_id)
- {
- Q_UNUSED(req_id);
-
- setEnabled(true);
- }
-
- void mod_config()
- {
- if(!Pkcs11ConfigDlg::isSupported())
- {
- QMessageBox::information(this, tr("Error"), tr("No provider available supporting standard PKCS#11 configuration."));
- return;
- }
-
- Pkcs11ConfigDlg *w = new Pkcs11ConfigDlg(this);
- w->setAttribute(Qt::WA_DeleteOnClose, true);
- w->setWindowModality(Qt::WindowModal);
- w->show();
- }
-
- void users_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
- {
- Q_UNUSED(deselected);
-
- int at = -1;
- if(!selected.indexes().isEmpty())
- {
- QModelIndex index = selected.indexes().first();
- at = index.row();
- }
-
- bool usable = false;
- if(at != -1 && users->itemFromRow(at).isUsable())
- usable = true;
-
- if(usable && !ui.pb_sign->isEnabled())
- ui.pb_sign->setEnabled(true);
- else if(!usable && ui.pb_sign->isEnabled())
- ui.pb_sign->setEnabled(false);
- }
-
- void item_view()
- {
- if(ui.lv_users->hasFocus())
- {
- QItemSelection selection = ui.lv_users->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- users_view(index.row());
- }
- else // lv_authorities
- {
- QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- roots_view(index.row());
- }
- }
-
- void item_rename()
- {
- if(ui.lv_users->hasFocus())
- {
- QItemSelection selection = ui.lv_users->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- users_rename(index.row());
- }
- else // lv_authorities
- {
- QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- roots_rename(index.row());
- }
- }
-
- void item_remove()
- {
- if(ui.lv_users->hasFocus())
- {
- QItemSelection selection = ui.lv_users->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- users_remove(index.row());
- }
- else // lv_authorities
- {
- QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- roots_remove(index.row());
- }
- }
-
- void users_view(int at)
- {
- CertItem i = users->itemFromRow(at);
- CertViewDlg *w = new CertViewDlg(complete(i.certificateChain()), this);
- w->setAttribute(Qt::WA_DeleteOnClose, true);
- w->show();
- }
-
- void users_rename(int at)
- {
- QModelIndex index = users->index(at);
- ui.lv_users->setFocus();
- ui.lv_users->setCurrentIndex(index);
- ui.lv_users->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
- ui.lv_users->edit(index);
- }
-
- void users_remove(int at)
- {
- users->removeItem(users->idFromRow(at));
- }
-
- void roots_view(int at)
- {
- CertItem i = roots->itemFromRow(at);
- CertViewDlg *w = new CertViewDlg(complete(i.certificateChain()), this);
- w->setAttribute(Qt::WA_DeleteOnClose, true);
- w->show();
- }
-
- void roots_rename(int at)
- {
- QModelIndex index = roots->index(at);
- ui.lv_authorities->setFocus();
- ui.lv_authorities->setCurrentIndex(index);
- ui.lv_authorities->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
- ui.lv_authorities->edit(index);
- }
-
- void roots_remove(int at)
- {
- roots->removeItem(roots->idFromRow(at));
- }
-
- void keyselect_viewCertificate(const QCA::CertificateChain &chain)
- {
- CertViewDlg *w = new CertViewDlg(complete(chain), (QWidget *)sender());
- w->setAttribute(Qt::WA_DeleteOnClose, true);
- w->show();
- }
-
- void users_customContextMenuRequested(const QPoint &pos)
- {
- QItemSelection selection = ui.lv_users->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
-
- QMenu menu(this);
- menu.addAction(actionView);
- menu.addAction(actionRename);
- menu.addAction(actionRemove);
- menu.exec(ui.lv_users->viewport()->mapToGlobal(pos));
- }
-
- void roots_customContextMenuRequested(const QPoint &pos)
- {
- QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
-
- QMenu menu(this);
- menu.addAction(actionView);
- menu.addAction(actionRename);
- menu.addAction(actionRemove);
- menu.exec(ui.lv_authorities->viewport()->mapToGlobal(pos));
- }
-
- void do_sign()
- {
- QItemSelection selection = ui.lv_users->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- int at = index.row();
-
- setEnabled(false);
-
- op = new SignOperation(ui.te_data->toPlainText().toUtf8(), users, users->idFromRow(at), cms, this);
- connect(op, SIGNAL(loadError()), SLOT(sign_loadError()));
- connect(op, SIGNAL(finished(const QString &)), SLOT(sign_finished(const QString &)));
- connect(op, SIGNAL(error(const QString &)), SLOT(sign_error(const QString &)));
- }
-
- void do_verify()
- {
- // prepare root certs
- QCA::CertificateCollection col;
-
- // system store
- col += QCA::systemStore();
-
- // additional roots configured in application
- foreach(const CertItem &i, roots->items())
- col.addCertificate(i.certificateChain().primary());
-
- // consider self-signed users as roots
- // (it is therefore not possible with this application to
- // have people in your keyring that you don't trust)
- foreach(const CertItem &i, users->items())
- {
- QCA::Certificate cert = i.certificateChain().primary();
- if(cert.isSelfSigned())
- col.addCertificate(cert);
- }
-
- // the self signed verify cert, if applicable
- if(!self_signed_verify_cert.isNull())
- {
- col.addCertificate(self_signed_verify_cert);
- self_signed_verify_cert = QCA::Certificate();
- }
-
- cms->setTrustedCertificates(col);
-
- setEnabled(false);
-
- op = new VerifyOperation(ui.te_data->toPlainText().toUtf8(), ui.te_sig->toPlainText().toUtf8(), cms, this);
- connect(op, SIGNAL(finished()), SLOT(verify_finished()));
- connect(op, SIGNAL(error(const QString &)), SLOT(verify_error(const QString &)));
- }
-
- void about()
- {
- int ver = qcaVersion();
- int maj = (ver >> 16) & 0xff;
- int min = (ver >> 8) & 0xff;
- int bug = ver & 0xff;
- QString verstr;
- verstr.sprintf("%d.%d.%d", maj, min, bug);
-
- QString str;
- str += tr("CMS Signer version %1 by Justin Karneges").arg(VERSION) + '\n';
- str += tr("A simple tool for creating and verifying digital signatures.") + '\n';
- str += '\n';
- str += tr("Using QCA version %1").arg(verstr) + '\n';
- str += '\n';
- str += tr("Icons by Jason Kim") + '\n';
-
- QCA::ProviderList list = QCA::providers();
- foreach(QCA::Provider *p, list)
- {
- QString credit = p->credit();
- if(!credit.isEmpty())
- {
- str += '\n';
- str += credit;
- }
- }
-
- QMessageBox::about(this, tr("About CMS Signer"), str);
- }
-
- void sign_loadError()
- {
- delete op;
- op = 0;
-
- setEnabled(true);
- }
-
- void sign_finished(const QString &sig)
- {
- delete op;
- op = 0;
-
- ui.te_sig->setPlainText(sig);
-
- setEnabled(true);
- }
-
- void sign_error(const QString &msg)
- {
- delete op;
- op = 0;
-
- setEnabled(true);
-
- QMessageBox::information(this, tr("Error"), msg);
- }
-
- void verify_finished()
- {
- QCA::SecureMessageSignature signer = ((VerifyOperation *)op)->signer;
- delete op;
- op = 0;
-
- // import the cert?
- QCA::SecureMessageKey skey = signer.key();
- if(!skey.isNull())
- {
- QCA::CertificateChain chain = skey.x509CertificateChain();
-
- int at = -1;
- QList<CertItem> items = users->items();
- for(int n = 0; n < items.count(); ++n)
- {
- const CertItem &i = items[n];
- if(i.certificateChain().primary() == chain.primary())
- {
- at = n;
- break;
- }
- }
-
- // add
- if(at == -1)
- {
- auto_import_req_id = users->addUser(chain);
- return;
- }
- // update
- else
- {
- users->updateChain(users->idFromRow(at), chain);
- }
- }
-
- verify_next();
- }
-
- void verify_next()
- {
- setEnabled(true);
-
- QMessageBox::information(this, tr("Verify"), tr("Signature verified successfully."));
- }
-
- void verify_error(const QString &msg)
- {
- QCA::SecureMessageSignature signer = ((VerifyOperation *)op)->signer;
- delete op;
- op = 0;
-
- QCA::SecureMessageKey skey = signer.key();
- if(signer.keyValidity() == QCA::ErrorSelfSigned && !skey.isNull())
- {
- QCA::CertificateChain chain = skey.x509CertificateChain();
- if(chain.count() == 1 && chain.primary().isSelfSigned())
- {
- QCA::Certificate cert = chain.primary();
-
- int ret = QMessageBox::warning(this, tr("Self-signed certificate"), tr(
- "<qt>The signature is made by an unknown user, and the certificate is self-signed.<br>\n"
- "<br>\n"
- "<nobr>Common Name: %1</nobr><br>\n"
- "<nobr>SHA1 Fingerprint: %2</nobr><br>\n"
- "<br>\n"
- "Trust the certificate?</qt>"
- ).arg(cert.commonName(), get_fingerprint(cert)),
- QMessageBox::Yes | QMessageBox::No,
- QMessageBox::No);
-
- if(ret == QMessageBox::Yes)
- {
- self_signed_verify_cert = cert;
- do_verify();
- return;
- }
- }
- }
-
- setEnabled(true);
-
- QMessageBox::information(this, tr("Error"), msg);
- }
+ ui.lv_users->selectionModel()->select(users->index(users->rowFromId(id)), QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
+
+ setEnabled(true);
+ }
+
+ void users_addFailed(int req_id)
+ {
+ Q_UNUSED(req_id);
+
+ setEnabled(true);
+ }
+
+ void mod_config()
+ {
+ if (!Pkcs11ConfigDlg::isSupported()) {
+ QMessageBox::information(this, tr("Error"), tr("No provider available supporting standard PKCS#11 configuration."));
+ return;
+ }
+
+ Pkcs11ConfigDlg *w = new Pkcs11ConfigDlg(this);
+ w->setAttribute(Qt::WA_DeleteOnClose, true);
+ w->setWindowModality(Qt::WindowModal);
+ w->show();
+ }
+
+ void users_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
+ {
+ Q_UNUSED(deselected);
+
+ int at = -1;
+ if (!selected.indexes().isEmpty()) {
+ QModelIndex index = selected.indexes().first();
+ at = index.row();
+ }
+
+ bool usable = false;
+ if (at != -1 && users->itemFromRow(at).isUsable()) {
+ usable = true;
+ }
+
+ if (usable && !ui.pb_sign->isEnabled()) {
+ ui.pb_sign->setEnabled(true);
+ } else if (!usable && ui.pb_sign->isEnabled()) {
+ ui.pb_sign->setEnabled(false);
+ }
+ }
+
+ void item_view()
+ {
+ if (ui.lv_users->hasFocus()) {
+ QItemSelection selection = ui.lv_users->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ users_view(index.row());
+ } else { // lv_authorities
+ QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ roots_view(index.row());
+ }
+ }
+
+ void item_rename()
+ {
+ if (ui.lv_users->hasFocus()) {
+ QItemSelection selection = ui.lv_users->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ users_rename(index.row());
+ } else { // lv_authorities
+ QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ roots_rename(index.row());
+ }
+ }
+
+ void item_remove()
+ {
+ if (ui.lv_users->hasFocus()) {
+ QItemSelection selection = ui.lv_users->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ users_remove(index.row());
+ } else { // lv_authorities
+ QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ roots_remove(index.row());
+ }
+ }
+
+ void users_view(int at)
+ {
+ CertItem i = users->itemFromRow(at);
+ CertViewDlg *w = new CertViewDlg(complete(i.certificateChain()), this);
+ w->setAttribute(Qt::WA_DeleteOnClose, true);
+ w->show();
+ }
+
+ void users_rename(int at)
+ {
+ QModelIndex index = users->index(at);
+ ui.lv_users->setFocus();
+ ui.lv_users->setCurrentIndex(index);
+ ui.lv_users->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
+ ui.lv_users->edit(index);
+ }
+
+ void users_remove(int at)
+ {
+ users->removeItem(users->idFromRow(at));
+ }
+
+ void roots_view(int at)
+ {
+ CertItem i = roots->itemFromRow(at);
+ CertViewDlg *w = new CertViewDlg(complete(i.certificateChain()), this);
+ w->setAttribute(Qt::WA_DeleteOnClose, true);
+ w->show();
+ }
+
+ void roots_rename(int at)
+ {
+ QModelIndex index = roots->index(at);
+ ui.lv_authorities->setFocus();
+ ui.lv_authorities->setCurrentIndex(index);
+ ui.lv_authorities->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
+ ui.lv_authorities->edit(index);
+ }
+
+ void roots_remove(int at)
+ {
+ roots->removeItem(roots->idFromRow(at));
+ }
+
+ void keyselect_viewCertificate(const QCA::CertificateChain &chain)
+ {
+ CertViewDlg *w = new CertViewDlg(complete(chain), (QWidget *)sender());
+ w->setAttribute(Qt::WA_DeleteOnClose, true);
+ w->show();
+ }
+
+ void users_customContextMenuRequested(const QPoint &pos)
+ {
+ QItemSelection selection = ui.lv_users->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+
+ QMenu menu(this);
+ menu.addAction(actionView);
+ menu.addAction(actionRename);
+ menu.addAction(actionRemove);
+ menu.exec(ui.lv_users->viewport()->mapToGlobal(pos));
+ }
+
+ void roots_customContextMenuRequested(const QPoint &pos)
+ {
+ QItemSelection selection = ui.lv_authorities->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+
+ QMenu menu(this);
+ menu.addAction(actionView);
+ menu.addAction(actionRename);
+ menu.addAction(actionRemove);
+ menu.exec(ui.lv_authorities->viewport()->mapToGlobal(pos));
+ }
+
+ void do_sign()
+ {
+ QItemSelection selection = ui.lv_users->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ int at = index.row();
+
+ setEnabled(false);
+
+ op = new SignOperation(ui.te_data->toPlainText().toUtf8(), users, users->idFromRow(at), cms, this);
+ connect(op, SIGNAL(loadError()), SLOT(sign_loadError()));
+ connect(op, SIGNAL(finished(QString)), SLOT(sign_finished(QString)));
+ connect(op, SIGNAL(error(QString)), SLOT(sign_error(QString)));
+ }
+
+ void do_verify()
+ {
+ // prepare root certs
+ QCA::CertificateCollection col;
+
+ // system store
+ col += QCA::systemStore();
+
+ // additional roots configured in application
+ foreach (const CertItem &i, roots->items()) {
+ col.addCertificate(i.certificateChain().primary());
+ }
+
+ // consider self-signed users as roots
+ // (it is therefore not possible with this application to
+ // have people in your keyring that you don't trust)
+ foreach (const CertItem &i, users->items()) {
+ QCA::Certificate cert = i.certificateChain().primary();
+ if (cert.isSelfSigned()) {
+ col.addCertificate(cert);
+ }
+ }
+
+ // the self signed verify cert, if applicable
+ if (!self_signed_verify_cert.isNull()) {
+ col.addCertificate(self_signed_verify_cert);
+ self_signed_verify_cert = QCA::Certificate();
+ }
+
+ cms->setTrustedCertificates(col);
+
+ setEnabled(false);
+
+ op = new VerifyOperation(ui.te_data->toPlainText().toUtf8(), ui.te_sig->toPlainText().toUtf8(), cms, this);
+ connect(op, SIGNAL(finished()), SLOT(verify_finished()));
+ connect(op, SIGNAL(error(QString)), SLOT(verify_error(QString)));
+ }
+
+ void about()
+ {
+ int ver = qcaVersion();
+ int maj = (ver >> 16) & 0xff;
+ int min = (ver >> 8) & 0xff;
+ int bug = ver & 0xff;
+ QString verstr;
+ verstr.sprintf("%d.%d.%d", maj, min, bug);
+
+ QString str;
+ str += tr("CMS Signer version %1 by Justin Karneges").arg(VERSION) + '\n';
+ str += tr("A simple tool for creating and verifying digital signatures.") + '\n';
+ str += '\n';
+ str += tr("Using QCA version %1").arg(verstr) + '\n';
+ str += '\n';
+ str += tr("Icons by Jason Kim") + '\n';
+
+ QCA::ProviderList list = QCA::providers();
+ foreach (QCA::Provider *p, list) {
+ QString credit = p->credit();
+ if (!credit.isEmpty()) {
+ str += '\n';
+ str += credit;
+ }
+ }
+
+ QMessageBox::about(this, tr("About CMS Signer"), str);
+ }
+
+ void sign_loadError()
+ {
+ delete op;
+ op = 0;
+
+ setEnabled(true);
+ }
+
+ void sign_finished(const QString &sig)
+ {
+ delete op;
+ op = 0;
+
+ ui.te_sig->setPlainText(sig);
+
+ setEnabled(true);
+ }
+
+ void sign_error(const QString &msg)
+ {
+ delete op;
+ op = 0;
+
+ setEnabled(true);
+
+ QMessageBox::information(this, tr("Error"), msg);
+ }
+
+ void verify_finished()
+ {
+ QCA::SecureMessageSignature signer = ((VerifyOperation *)op)->signer;
+ delete op;
+ op = 0;
+
+ // import the cert?
+ QCA::SecureMessageKey skey = signer.key();
+ if (!skey.isNull()) {
+ QCA::CertificateChain chain = skey.x509CertificateChain();
+
+ int at = -1;
+ QList<CertItem> items = users->items();
+ for (int n = 0; n < items.count(); ++n) {
+ const CertItem &i = items[n];
+ if (i.certificateChain().primary() == chain.primary()) {
+ at = n;
+ break;
+ }
+ }
+
+ // add
+ if (at == -1) {
+ auto_import_req_id = users->addUser(chain);
+ return;
+ }
+ // update
+ else {
+ users->updateChain(users->idFromRow(at), chain);
+ }
+ }
+
+ verify_next();
+ }
+
+ void verify_next()
+ {
+ setEnabled(true);
+
+ QMessageBox::information(this, tr("Verify"), tr("Signature verified successfully."));
+ }
+
+ void verify_error(const QString &msg)
+ {
+ QCA::SecureMessageSignature signer = ((VerifyOperation *)op)->signer;
+ delete op;
+ op = 0;
+
+ QCA::SecureMessageKey skey = signer.key();
+ if (signer.keyValidity() == QCA::ErrorSelfSigned && !skey.isNull()) {
+ QCA::CertificateChain chain = skey.x509CertificateChain();
+ if (chain.count() == 1 && chain.primary().isSelfSigned()) {
+ QCA::Certificate cert = chain.primary();
+
+ int ret = QMessageBox::warning(this, tr("Self-signed certificate"), tr(
+ "<qt>The signature is made by an unknown user, and the certificate is self-signed.<br>\n"
+ "<br>\n"
+ "<nobr>Common Name: %1</nobr><br>\n"
+ "<nobr>SHA1 Fingerprint: %2</nobr><br>\n"
+ "<br>\n"
+ "Trust the certificate?</qt>"
+ ).arg(cert.commonName(), get_fingerprint(cert)),
+ QMessageBox::Yes | QMessageBox::No,
+ QMessageBox::No);
+
+ if (ret == QMessageBox::Yes) {
+ self_signed_verify_cert = cert;
+ do_verify();
+ return;
+ }
+ }
+ }
+
+ setEnabled(true);
+
+ QMessageBox::information(this, tr("Error"), msg);
+ }
};
int main(int argc, char **argv)
{
- QCA::Initializer qcaInit;
- QApplication qapp(argc, argv);
+ QCA::Initializer qcaInit;
+ QApplication qapp(argc, argv);
- qapp.setApplicationName(MainWin::tr("CMS Signer"));
+ qapp.setApplicationName(MainWin::tr("CMS Signer"));
- if(!QCA::isSupported("cert,crl,cms"))
- {
- QMessageBox::critical(0, qapp.applicationName() + ": " + MainWin::tr("Error"),
- MainWin::tr("No support for CMS is available. Please install an appropriate QCA plugin, such as qca-ossl."));
- return 1;
- }
+ if (!QCA::isSupported("cert,crl,cms")) {
+ QMessageBox::critical(0, qapp.applicationName() + ": " + MainWin::tr("Error"),
+ MainWin::tr("No support for CMS is available. Please install an appropriate QCA plugin, such as qca-ossl."));
+ return 1;
+ }
- QCA::KeyStoreManager::start();
+ QCA::KeyStoreManager::start();
- MainWin mainWin;
- mainWin.show();
- return qapp.exec();
+ MainWin mainWin;
+ mainWin.show();
+ return qapp.exec();
}
#include "main.moc"
diff --git a/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.cpp b/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.cpp
index 01b3b821..f8244351 100644
--- a/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.cpp
+++ b/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.cpp
@@ -1,816 +1,811 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "pkcs11configdlg.h"
#include <QtCore>
#include <QtGui>
#include <QtCrypto>
#include <QMessageBox>
#include <QFileDialog>
#include "ui_pkcs11config.h"
//----------------------------------------------------------------------------
// Pkcs11ProviderConfig
//----------------------------------------------------------------------------
class Pkcs11ProviderConfig
{
public:
- bool allow_protected_authentication;
- bool cert_private;
- bool enabled;
- QString library;
- QString name;
- int private_mask;
- QString slotevent_method;
- int slotevent_timeout;
-
- Pkcs11ProviderConfig() :
- allow_protected_authentication(true),
- cert_private(false),
- enabled(false),
- private_mask(0),
- slotevent_method("auto"),
- slotevent_timeout(0)
- {
- }
-
- QVariantMap toVariantMap() const
- {
- QVariantMap out;
- out["allow_protected_authentication"] = allow_protected_authentication;
- out["cert_private"] = cert_private;
- out["enabled"] = enabled;
- out["library"] = library;
- out["name"] = name;
- out["private_mask"] = private_mask;
- out["slotevent_method"] = slotevent_method;
- out["slotevent_timeout"] = slotevent_timeout;
- return out;
- }
-
- bool fromVariantMap(const QVariantMap &in)
- {
- allow_protected_authentication = in["allow_protected_authentication"].toBool();
- cert_private = in["cert_private"].toBool();
- enabled = in["enabled"].toBool();
- library = in["library"].toString();
- name = in["name"].toString();
- private_mask = in["private_mask"].toInt();
- slotevent_method = in["slotevent_method"].toString();
- slotevent_timeout = in["slotevent_timeout"].toInt();
- return true;
- }
+ bool allow_protected_authentication;
+ bool cert_private;
+ bool enabled;
+ QString library;
+ QString name;
+ int private_mask;
+ QString slotevent_method;
+ int slotevent_timeout;
+
+ Pkcs11ProviderConfig() :
+ allow_protected_authentication(true),
+ cert_private(false),
+ enabled(false),
+ private_mask(0),
+ slotevent_method("auto"),
+ slotevent_timeout(0)
+ {
+ }
+
+ QVariantMap toVariantMap() const
+ {
+ QVariantMap out;
+ out["allow_protected_authentication"] = allow_protected_authentication;
+ out["cert_private"] = cert_private;
+ out["enabled"] = enabled;
+ out["library"] = library;
+ out["name"] = name;
+ out["private_mask"] = private_mask;
+ out["slotevent_method"] = slotevent_method;
+ out["slotevent_timeout"] = slotevent_timeout;
+ return out;
+ }
+
+ bool fromVariantMap(const QVariantMap &in)
+ {
+ allow_protected_authentication = in["allow_protected_authentication"].toBool();
+ cert_private = in["cert_private"].toBool();
+ enabled = in["enabled"].toBool();
+ library = in["library"].toString();
+ name = in["name"].toString();
+ private_mask = in["private_mask"].toInt();
+ slotevent_method = in["slotevent_method"].toString();
+ slotevent_timeout = in["slotevent_timeout"].toInt();
+ return true;
+ }
};
//----------------------------------------------------------------------------
// Pkcs11Config
//----------------------------------------------------------------------------
class Pkcs11Config
{
public:
- bool allow_load_rootca;
- bool allow_protected_authentication;
- int log_level;
- int pin_cache;
- QList<Pkcs11ProviderConfig> providers;
-
- QVariantMap orig_config;
-
- Pkcs11Config() :
- allow_load_rootca(false),
- allow_protected_authentication(true),
- log_level(0),
- pin_cache(-1)
- {
- }
-
- QVariantMap toVariantMap() const
- {
- QVariantMap out = orig_config;
-
- // form type
- out["formtype"] = "http://affinix.com/qca/forms/qca-pkcs11#1.0";
-
- // base settings
- out["allow_load_rootca"] = allow_load_rootca;
- out["allow_protected_authentication"] = allow_protected_authentication;
- out["log_level"] = log_level;
- out["pin_cache"] = pin_cache;
-
- // provider settings (always write at least 10 providers)
- for(int n = 0; n < 10 || n < providers.count(); ++n)
- {
- QString prefix = QString().sprintf("provider_%02d_", n);
-
- Pkcs11ProviderConfig provider;
- if(n < providers.count())
- provider = providers[n];
-
- QVariantMap subconfig = provider.toVariantMap();
- QMapIterator<QString,QVariant> it(subconfig);
- while(it.hasNext())
- {
- it.next();
- out.insert(prefix + it.key(), it.value());
- }
- }
-
- return out;
- }
-
- bool fromVariantMap(const QVariantMap &in)
- {
- if(in["formtype"] != "http://affinix.com/qca/forms/qca-pkcs11#1.0")
- return false;
-
- allow_load_rootca = in["allow_load_rootca"].toBool();
- allow_protected_authentication = in["allow_protected_authentication"].toBool();
- log_level = in["log_level"].toInt();
- pin_cache = in["pin_cache"].toInt();
-
- for(int n = 0;; ++n)
- {
- QString prefix = QString().sprintf("provider_%02d_", n);
-
- // collect all key/values with this prefix into a
- // a separate container, leaving out the prefix
- // from the keys.
- QVariantMap subconfig;
- QMapIterator<QString,QVariant> it(in);
- while(it.hasNext())
- {
- it.next();
- if(it.key().startsWith(prefix))
- subconfig.insert(it.key().mid(prefix.length()), it.value());
- }
-
- // if there are no config items with this prefix, we're done
- if(subconfig.isEmpty())
- break;
-
- Pkcs11ProviderConfig provider;
- if(!provider.fromVariantMap(subconfig))
- return false;
-
- // skip unnamed entries
- if(provider.name.isEmpty())
- continue;
-
- // skip duplicate entries
- bool have_name_already = false;
- foreach(const Pkcs11ProviderConfig &i, providers)
- {
- if(i.name == provider.name)
- {
- have_name_already = true;
- break;
- }
- }
- if(have_name_already)
- continue;
-
- providers += provider;
- }
-
- orig_config = in;
- return true;
- }
+ bool allow_load_rootca;
+ bool allow_protected_authentication;
+ int log_level;
+ int pin_cache;
+ QList<Pkcs11ProviderConfig> providers;
+
+ QVariantMap orig_config;
+
+ Pkcs11Config() :
+ allow_load_rootca(false),
+ allow_protected_authentication(true),
+ log_level(0),
+ pin_cache(-1)
+ {
+ }
+
+ QVariantMap toVariantMap() const
+ {
+ QVariantMap out = orig_config;
+
+ // form type
+ out["formtype"] = "http://affinix.com/qca/forms/qca-pkcs11#1.0";
+
+ // base settings
+ out["allow_load_rootca"] = allow_load_rootca;
+ out["allow_protected_authentication"] = allow_protected_authentication;
+ out["log_level"] = log_level;
+ out["pin_cache"] = pin_cache;
+
+ // provider settings (always write at least 10 providers)
+ for (int n = 0; n < 10 || n < providers.count(); ++n) {
+ QString prefix = QString().sprintf("provider_%02d_", n);
+
+ Pkcs11ProviderConfig provider;
+ if (n < providers.count()) {
+ provider = providers[n];
+ }
+
+ QVariantMap subconfig = provider.toVariantMap();
+ QMapIterator<QString, QVariant> it(subconfig);
+ while (it.hasNext()) {
+ it.next();
+ out.insert(prefix + it.key(), it.value());
+ }
+ }
+
+ return out;
+ }
+
+ bool fromVariantMap(const QVariantMap &in)
+ {
+ if (in["formtype"] != "http://affinix.com/qca/forms/qca-pkcs11#1.0") {
+ return false;
+ }
+
+ allow_load_rootca = in["allow_load_rootca"].toBool();
+ allow_protected_authentication = in["allow_protected_authentication"].toBool();
+ log_level = in["log_level"].toInt();
+ pin_cache = in["pin_cache"].toInt();
+
+ for (int n = 0;; ++n) {
+ QString prefix = QString().sprintf("provider_%02d_", n);
+
+ // collect all key/values with this prefix into a
+ // a separate container, leaving out the prefix
+ // from the keys.
+ QVariantMap subconfig;
+ QMapIterator<QString, QVariant> it(in);
+ while (it.hasNext()) {
+ it.next();
+ if (it.key().startsWith(prefix)) {
+ subconfig.insert(it.key().mid(prefix.length()), it.value());
+ }
+ }
+
+ // if there are no config items with this prefix, we're done
+ if (subconfig.isEmpty()) {
+ break;
+ }
+
+ Pkcs11ProviderConfig provider;
+ if (!provider.fromVariantMap(subconfig)) {
+ return false;
+ }
+
+ // skip unnamed entries
+ if (provider.name.isEmpty()) {
+ continue;
+ }
+
+ // skip duplicate entries
+ bool have_name_already = false;
+ foreach (const Pkcs11ProviderConfig &i, providers) {
+ if (i.name == provider.name) {
+ have_name_already = true;
+ break;
+ }
+ }
+ if (have_name_already) {
+ continue;
+ }
+
+ providers += provider;
+ }
+
+ orig_config = in;
+ return true;
+ }
};
//----------------------------------------------------------------------------
// ModuleListModel
//----------------------------------------------------------------------------
class ModuleListModel : public QAbstractListModel
{
- Q_OBJECT
+ Q_OBJECT
public:
- QList<Pkcs11ProviderConfig> list;
-
- ModuleListModel(QObject *parent = 0) :
- QAbstractListModel(parent)
- {
- }
-
- int rowCount(const QModelIndex &parent = QModelIndex()) const
- {
- Q_UNUSED(parent);
- return list.count();
- }
-
- QVariant data(const QModelIndex &index, int role) const
- {
- if(!index.isValid())
- return QVariant();
-
- if(index.row() >= list.count())
- return QVariant();
-
- if(role == Qt::DisplayRole)
- return list[index.row()].name;
- else if(role == Qt::EditRole)
- return list[index.row()].name;
- else
- return QVariant();
- }
-
- Qt::ItemFlags flags(const QModelIndex &index) const
- {
- if(!index.isValid())
- return Qt::ItemIsEnabled;
-
- return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
- }
-
- bool setData(const QModelIndex &index, const QVariant &value, int role)
- {
- if(index.isValid() && role == Qt::EditRole)
- {
- QString str = value.toString();
-
- if(str.isEmpty())
- {
- emit editFailed(index, tr("Module name cannot be blank."));
- return false;
- }
-
- bool have_name_already = false;
- int at = index.row();
- for(int n = 0; n < list.count(); ++n)
- {
- const Pkcs11ProviderConfig &i = list[n];
-
- // skip self
- if(n == at)
- continue;
-
- if(i.name == str)
- {
- have_name_already = true;
- break;
- }
- }
- if(have_name_already)
- {
- emit editFailed(index, tr("There is already a module with this name."));
- return false;
- }
-
- list[index.row()].name = str;
- emit dataChanged(index, index);
- return true;
- }
- return false;
- }
-
- void addItems(const QList<Pkcs11ProviderConfig> &items)
- {
- if(items.isEmpty())
- return;
-
- beginInsertRows(QModelIndex(), list.size(), list.size() + items.count() - 1);
- list += items;
- endInsertRows();
- }
-
- void addItem(const Pkcs11ProviderConfig &i)
- {
- beginInsertRows(QModelIndex(), list.size(), list.size());
- list += i;
- endInsertRows();
- }
-
- void removeItem(int at)
- {
- beginRemoveRows(QModelIndex(), at, at);
- list.removeAt(at);
- endRemoveRows();
- }
+ QList<Pkcs11ProviderConfig> list;
+
+ ModuleListModel(QObject *parent = 0) :
+ QAbstractListModel(parent)
+ {
+ }
+
+ int rowCount(const QModelIndex &parent = QModelIndex()) const
+ {
+ Q_UNUSED(parent);
+ return list.count();
+ }
+
+ QVariant data(const QModelIndex &index, int role) const
+ {
+ if (!index.isValid()) {
+ return QVariant();
+ }
+
+ if (index.row() >= list.count()) {
+ return QVariant();
+ }
+
+ if (role == Qt::DisplayRole) {
+ return list[index.row()].name;
+ } else if (role == Qt::EditRole) {
+ return list[index.row()].name;
+ } else {
+ return QVariant();
+ }
+ }
+
+ Qt::ItemFlags flags(const QModelIndex &index) const
+ {
+ if (!index.isValid()) {
+ return Qt::ItemIsEnabled;
+ }
+
+ return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
+ }
+
+ bool setData(const QModelIndex &index, const QVariant &value, int role)
+ {
+ if (index.isValid() && role == Qt::EditRole) {
+ QString str = value.toString();
+
+ if (str.isEmpty()) {
+ emit editFailed(index, tr("Module name cannot be blank."));
+ return false;
+ }
+
+ bool have_name_already = false;
+ int at = index.row();
+ for (int n = 0; n < list.count(); ++n) {
+ const Pkcs11ProviderConfig &i = list[n];
+
+ // skip self
+ if (n == at) {
+ continue;
+ }
+
+ if (i.name == str) {
+ have_name_already = true;
+ break;
+ }
+ }
+ if (have_name_already) {
+ emit editFailed(index, tr("There is already a module with this name."));
+ return false;
+ }
+
+ list[index.row()].name = str;
+ emit dataChanged(index, index);
+ return true;
+ }
+ return false;
+ }
+
+ void addItems(const QList<Pkcs11ProviderConfig> &items)
+ {
+ if (items.isEmpty()) {
+ return;
+ }
+
+ beginInsertRows(QModelIndex(), list.size(), list.size() + items.count() - 1);
+ list += items;
+ endInsertRows();
+ }
+
+ void addItem(const Pkcs11ProviderConfig &i)
+ {
+ beginInsertRows(QModelIndex(), list.size(), list.size());
+ list += i;
+ endInsertRows();
+ }
+
+ void removeItem(int at)
+ {
+ beginRemoveRows(QModelIndex(), at, at);
+ list.removeAt(at);
+ endRemoveRows();
+ }
signals:
- void editFailed(const QModelIndex &index, const QString &reasonString);
+ void editFailed(const QModelIndex &index, const QString &reasonString);
};
//----------------------------------------------------------------------------
// Pkcs11ConfigDlg
//----------------------------------------------------------------------------
static QCA::Provider *get_pkcs11_provider(QVariantMap *_config = 0)
{
- QCA::ProviderList providers = QCA::providers();
- providers += QCA::defaultProvider();
-
- QCA::Provider *provider = 0;
- QVariantMap config;
- foreach(QCA::Provider *p, providers)
- {
- config = QCA::getProviderConfig(p->name());
- if(!config.isEmpty() && config["formtype"] == "http://affinix.com/qca/forms/qca-pkcs11#1.0")
- {
- provider = p;
- break;
- }
- }
-
- if(provider && _config)
- *_config = config;
-
- return provider;
+ QCA::ProviderList providers = QCA::providers();
+ providers += QCA::defaultProvider();
+
+ QCA::Provider *provider = 0;
+ QVariantMap config;
+ foreach (QCA::Provider *p, providers) {
+ config = QCA::getProviderConfig(p->name());
+ if (!config.isEmpty() && config["formtype"] == "http://affinix.com/qca/forms/qca-pkcs11#1.0") {
+ provider = p;
+ break;
+ }
+ }
+
+ if (provider && _config) {
+ *_config = config;
+ }
+
+ return provider;
}
class Pkcs11ConfigDlg::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- Pkcs11ConfigDlg *q;
- Ui_Pkcs11Config ui;
- QString providerName;
- ModuleListModel *model;
- Pkcs11Config config;
- bool dirty;
-
- // for safe dialog closing behavior during QListView editing
- bool allow_close;
- bool done;
-
- // for ignoring modifications that we cause when populating fields
- bool ignore_dataChanged;
-
- Private(Pkcs11ConfigDlg *_q, const QString &_providerName, const QVariantMap &configmap) :
- QObject(_q),
- q(_q),
- providerName(_providerName),
- dirty(false),
- allow_close(true),
- done(false),
- ignore_dataChanged(true)
- {
- ui.setupUi(q);
- q->resize(q->minimumSize());
-
- model = new ModuleListModel(this);
- qRegisterMetaType<QModelIndex>("QModelIndex");
- // do this queued for two reasons:
- // 1) if we throw an error dialog, it will occur after the
- // row text has reverted, and the call stack completed
- // (the latter may not be required, but it helps me
- // sleep).
- // 2) if the user accepts/rejects the dialog while editing,
- // it is easy to ensure that the signal is not processed
- // (if it gets delivered at all).
- connect(model,
- SIGNAL(editFailed(const QModelIndex &, const QString &)),
- SLOT(model_editFailed(const QModelIndex &, const QString &)),
- Qt::QueuedConnection);
-
- // set up widgets
- ui.rb_pincache_nolimit->setChecked(true);
- ui.sb_pincache_time->setEnabled(false);
- ui.sb_pincache_time->setValue(300);
- ui.lv_modules->setModel(model);
- ui.lv_modules->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
- ui.pb_remove->setEnabled(false);
- ui.tb_details->setEnabled(false);
- ui.gb_poll->setEnabled(false);
- ui.rb_polldefault->setChecked(true);
- ui.sb_pollcustom->setEnabled(false);
- ui.sb_pollcustom->setValue(5);
- ui.ck_modeauto->setChecked(true);
-
- // disable this by default, enable on dataChanged
- ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
-
- // general
- connect(ui.ck_allowroot, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.ck_allowprotected, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.sb_loglevel, SIGNAL(valueChanged(int)), SLOT(dataChanged()));
- connect(ui.gb_pincache, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.rb_pincache_nolimit, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.rb_pincache_time, SIGNAL(toggled(bool)), ui.sb_pincache_time, SLOT(setEnabled(bool)));
- connect(ui.rb_pincache_time, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.sb_pincache_time, SIGNAL(valueChanged(int)), SLOT(dataChanged()));
-
- // modules
- connect(model, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), SLOT(dataChanged()));
- connect(ui.lv_modules->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(module_selectionChanged(const QItemSelection &, const QItemSelection &)));
- connect(ui.pb_add, SIGNAL(clicked()), SLOT(module_add()));
- connect(ui.pb_remove, SIGNAL(clicked()), SLOT(module_remove()));
- connect(ui.le_library, SIGNAL(textChanged(const QString &)), SLOT(dataChanged()));
- connect(ui.pb_browse, SIGNAL(clicked()), SLOT(library_browse()));
- connect(ui.cb_slotmethod, SIGNAL(currentIndexChanged(int)), SLOT(slotmethod_currentIndexChanged(int)));
- connect(ui.rb_polldefault, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.rb_pollcustom, SIGNAL(toggled(bool)), ui.sb_pollcustom, SLOT(setEnabled(bool)));
- connect(ui.rb_pollcustom, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.sb_pollcustom, SIGNAL(valueChanged(int)), SLOT(dataChanged()));
- connect(ui.ck_modallowprotected, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.ck_certprivate, SIGNAL(toggled(bool)), SLOT(dataChanged()));
- connect(ui.ck_modeauto, SIGNAL(toggled(bool)), SLOT(modeauto_toggled(bool)));
- connect(ui.ck_modesign, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
- connect(ui.ck_modesignrecover, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
- connect(ui.ck_modedecrypt, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
- connect(ui.ck_modeunwrap, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
-
- // is this a valid config?
- if(!providerName.isEmpty() && config.fromVariantMap(configmap))
- {
- // if so, load everything up
- ui.ck_allowroot->setChecked(config.allow_load_rootca);
- ui.ck_allowprotected->setChecked(config.allow_protected_authentication);
- ui.sb_loglevel->setValue(config.log_level);
- if(config.pin_cache != 0)
- {
- ui.gb_pincache->setChecked(true);
- if(config.pin_cache <= -1)
- ui.rb_pincache_nolimit->setChecked(true);
- else
- {
- ui.rb_pincache_time->setChecked(true);
- ui.sb_pincache_time->setValue(config.pin_cache);
- }
- }
-
- model->addItems(config.providers);
- if(!model->list.isEmpty())
- {
- QModelIndex index = model->index(0);
- ui.lv_modules->setCurrentIndex(index);
- ui.lv_modules->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
- }
- ui.buttonBox->setFocus();
- ui.buttonBox->button(QDialogButtonBox::Cancel)->setFocus();
- }
- else
- {
- // otherwise, disable everything
- ui.gb_general->setEnabled(false);
- ui.gb_modules->setEnabled(false);
- ui.buttonBox->setFocus();
- ui.buttonBox->button(QDialogButtonBox::Cancel)->setFocus();
- }
-
- ignore_dataChanged = false;
- }
-
- void save_module(int at)
- {
- // save all options (except the name, which is handled by the model)
- Pkcs11ProviderConfig &i = model->list[at];
-
- i.library = ui.le_library->text();
- i.enabled = true;
-
- int x = ui.cb_slotmethod->currentIndex();
- if(x == 0)
- i.slotevent_method = "auto";
- else if(x == 1)
- i.slotevent_method = "trigger";
- else // 2
- i.slotevent_method = "poll";
- if(x == 2)
- {
- if(ui.rb_polldefault->isChecked())
- i.slotevent_timeout = 0;
- else
- i.slotevent_timeout = ui.sb_pollcustom->value();
- }
- else
- i.slotevent_timeout = 0;
-
- i.allow_protected_authentication = ui.ck_modallowprotected->isChecked();
- i.cert_private = ui.ck_certprivate->isChecked();
-
- i.private_mask = 0;
- if(ui.ck_modesign->isChecked())
- i.private_mask |= 1;
- if(ui.ck_modesignrecover->isChecked())
- i.private_mask |= 2;
- if(ui.ck_modedecrypt->isChecked())
- i.private_mask |= 4;
- if(ui.ck_modeunwrap->isChecked())
- i.private_mask |= 8;
- }
-
- void save()
- {
- // save currently selected module, which may not be saved yet
- QItemSelection selection = ui.lv_modules->selectionModel()->selection();
- if(!selection.indexes().isEmpty())
- {
- QModelIndex index = selection.indexes().first();
- save_module(index.row());
- }
-
- config.allow_load_rootca = ui.ck_allowroot->isChecked();
- config.allow_protected_authentication = ui.ck_allowprotected->isChecked();
- config.log_level = ui.sb_loglevel->value();
- if(ui.gb_pincache->isChecked())
- {
- if(ui.rb_pincache_nolimit->isChecked())
- config.pin_cache = -1;
- else
- config.pin_cache = ui.sb_pincache_time->value();
- }
- else
- config.pin_cache = 0;
-
- config.providers = model->list;
-
- QVariantMap configmap = config.toVariantMap();
- QCA::setProviderConfig(providerName, configmap);
- QCA::saveProviderConfig(providerName);
- }
+ Pkcs11ConfigDlg *q;
+ Ui_Pkcs11Config ui;
+ QString providerName;
+ ModuleListModel *model;
+ Pkcs11Config config;
+ bool dirty;
+
+ // for safe dialog closing behavior during QListView editing
+ bool allow_close;
+ bool done;
+
+ // for ignoring modifications that we cause when populating fields
+ bool ignore_dataChanged;
+
+ Private(Pkcs11ConfigDlg *_q, const QString &_providerName, const QVariantMap &configmap) :
+ QObject(_q),
+ q(_q),
+ providerName(_providerName),
+ dirty(false),
+ allow_close(true),
+ done(false),
+ ignore_dataChanged(true)
+ {
+ ui.setupUi(q);
+ q->resize(q->minimumSize());
+
+ model = new ModuleListModel(this);
+ qRegisterMetaType<QModelIndex>("QModelIndex");
+ // do this queued for two reasons:
+ // 1) if we throw an error dialog, it will occur after the
+ // row text has reverted, and the call stack completed
+ // (the latter may not be required, but it helps me
+ // sleep).
+ // 2) if the user accepts/rejects the dialog while editing,
+ // it is easy to ensure that the signal is not processed
+ // (if it gets delivered at all).
+ connect(model,
+ SIGNAL(editFailed(QModelIndex,QString)),
+ SLOT(model_editFailed(QModelIndex,QString)),
+ Qt::QueuedConnection);
+
+ // set up widgets
+ ui.rb_pincache_nolimit->setChecked(true);
+ ui.sb_pincache_time->setEnabled(false);
+ ui.sb_pincache_time->setValue(300);
+ ui.lv_modules->setModel(model);
+ ui.lv_modules->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::SelectedClicked | QAbstractItemView::EditKeyPressed);
+ ui.pb_remove->setEnabled(false);
+ ui.tb_details->setEnabled(false);
+ ui.gb_poll->setEnabled(false);
+ ui.rb_polldefault->setChecked(true);
+ ui.sb_pollcustom->setEnabled(false);
+ ui.sb_pollcustom->setValue(5);
+ ui.ck_modeauto->setChecked(true);
+
+ // disable this by default, enable on dataChanged
+ ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
+
+ // general
+ connect(ui.ck_allowroot, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.ck_allowprotected, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.sb_loglevel, SIGNAL(valueChanged(int)), SLOT(dataChanged()));
+ connect(ui.gb_pincache, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.rb_pincache_nolimit, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.rb_pincache_time, SIGNAL(toggled(bool)), ui.sb_pincache_time, SLOT(setEnabled(bool)));
+ connect(ui.rb_pincache_time, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.sb_pincache_time, SIGNAL(valueChanged(int)), SLOT(dataChanged()));
+
+ // modules
+ connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), SLOT(dataChanged()));
+ connect(ui.lv_modules->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(module_selectionChanged(QItemSelection,QItemSelection)));
+ connect(ui.pb_add, SIGNAL(clicked()), SLOT(module_add()));
+ connect(ui.pb_remove, SIGNAL(clicked()), SLOT(module_remove()));
+ connect(ui.le_library, SIGNAL(textChanged(QString)), SLOT(dataChanged()));
+ connect(ui.pb_browse, SIGNAL(clicked()), SLOT(library_browse()));
+ connect(ui.cb_slotmethod, SIGNAL(currentIndexChanged(int)), SLOT(slotmethod_currentIndexChanged(int)));
+ connect(ui.rb_polldefault, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.rb_pollcustom, SIGNAL(toggled(bool)), ui.sb_pollcustom, SLOT(setEnabled(bool)));
+ connect(ui.rb_pollcustom, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.sb_pollcustom, SIGNAL(valueChanged(int)), SLOT(dataChanged()));
+ connect(ui.ck_modallowprotected, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.ck_certprivate, SIGNAL(toggled(bool)), SLOT(dataChanged()));
+ connect(ui.ck_modeauto, SIGNAL(toggled(bool)), SLOT(modeauto_toggled(bool)));
+ connect(ui.ck_modesign, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
+ connect(ui.ck_modesignrecover, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
+ connect(ui.ck_modedecrypt, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
+ connect(ui.ck_modeunwrap, SIGNAL(toggled(bool)), SLOT(modenonauto_toggled(bool)));
+
+ // is this a valid config?
+ if (!providerName.isEmpty() && config.fromVariantMap(configmap)) {
+ // if so, load everything up
+ ui.ck_allowroot->setChecked(config.allow_load_rootca);
+ ui.ck_allowprotected->setChecked(config.allow_protected_authentication);
+ ui.sb_loglevel->setValue(config.log_level);
+ if (config.pin_cache != 0) {
+ ui.gb_pincache->setChecked(true);
+ if (config.pin_cache <= -1) {
+ ui.rb_pincache_nolimit->setChecked(true);
+ } else {
+ ui.rb_pincache_time->setChecked(true);
+ ui.sb_pincache_time->setValue(config.pin_cache);
+ }
+ }
+
+ model->addItems(config.providers);
+ if (!model->list.isEmpty()) {
+ QModelIndex index = model->index(0);
+ ui.lv_modules->setCurrentIndex(index);
+ ui.lv_modules->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
+ }
+ ui.buttonBox->setFocus();
+ ui.buttonBox->button(QDialogButtonBox::Cancel)->setFocus();
+ } else {
+ // otherwise, disable everything
+ ui.gb_general->setEnabled(false);
+ ui.gb_modules->setEnabled(false);
+ ui.buttonBox->setFocus();
+ ui.buttonBox->button(QDialogButtonBox::Cancel)->setFocus();
+ }
+
+ ignore_dataChanged = false;
+ }
+
+ void save_module(int at)
+ {
+ // save all options (except the name, which is handled by the model)
+ Pkcs11ProviderConfig &i = model->list[at];
+
+ i.library = ui.le_library->text();
+ i.enabled = true;
+
+ int x = ui.cb_slotmethod->currentIndex();
+ if (x == 0) {
+ i.slotevent_method = "auto";
+ } else if (x == 1) {
+ i.slotevent_method = "trigger";
+ } else { // 2
+ i.slotevent_method = "poll";
+ }
+ if (x == 2) {
+ if (ui.rb_polldefault->isChecked()) {
+ i.slotevent_timeout = 0;
+ } else {
+ i.slotevent_timeout = ui.sb_pollcustom->value();
+ }
+ } else {
+ i.slotevent_timeout = 0;
+ }
+
+ i.allow_protected_authentication = ui.ck_modallowprotected->isChecked();
+ i.cert_private = ui.ck_certprivate->isChecked();
+
+ i.private_mask = 0;
+ if (ui.ck_modesign->isChecked()) {
+ i.private_mask |= 1;
+ }
+ if (ui.ck_modesignrecover->isChecked()) {
+ i.private_mask |= 2;
+ }
+ if (ui.ck_modedecrypt->isChecked()) {
+ i.private_mask |= 4;
+ }
+ if (ui.ck_modeunwrap->isChecked()) {
+ i.private_mask |= 8;
+ }
+ }
+
+ void save()
+ {
+ // save currently selected module, which may not be saved yet
+ QItemSelection selection = ui.lv_modules->selectionModel()->selection();
+ if (!selection.indexes().isEmpty()) {
+ QModelIndex index = selection.indexes().first();
+ save_module(index.row());
+ }
+
+ config.allow_load_rootca = ui.ck_allowroot->isChecked();
+ config.allow_protected_authentication = ui.ck_allowprotected->isChecked();
+ config.log_level = ui.sb_loglevel->value();
+ if (ui.gb_pincache->isChecked()) {
+ if (ui.rb_pincache_nolimit->isChecked()) {
+ config.pin_cache = -1;
+ } else {
+ config.pin_cache = ui.sb_pincache_time->value();
+ }
+ } else {
+ config.pin_cache = 0;
+ }
+
+ config.providers = model->list;
+
+ QVariantMap configmap = config.toVariantMap();
+ QCA::setProviderConfig(providerName, configmap);
+ QCA::saveProviderConfig(providerName);
+ }
private slots:
- void model_editFailed(const QModelIndex &index, const QString &reasonString)
- {
- // if the dialog has already been dismissed, then don't
- // bother with handling the editing failure
- if(done)
- return;
-
- // show error dialog, and don't allow dimissing the dialog
- // during. we need this, because the the dismiss request
- // can be queued, and end up being invoked during the
- // QMessageBox nested eventloop.
- allow_close = false;
- QMessageBox::information(q, tr("Module Configuration"), reasonString);
- allow_close = true;
-
- // return to edit mode for the item
- ui.lv_modules->setFocus();
- ui.lv_modules->setCurrentIndex(index);
- ui.lv_modules->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
- ui.lv_modules->edit(index);
- }
-
- void dataChanged()
- {
- if(ignore_dataChanged)
- return;
-
- if(dirty)
- return;
-
- dirty = true;
- ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
- }
-
- void module_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
- {
- if(!deselected.indexes().isEmpty())
- {
- QModelIndex index = deselected.indexes().first();
- save_module(index.row());
- }
-
- ignore_dataChanged = true;
-
- if(!selected.indexes().isEmpty())
- {
- if(deselected.indexes().isEmpty())
- {
- ui.pb_remove->setEnabled(true);
- ui.tb_details->setEnabled(true);
- }
-
- QModelIndex index = selected.indexes().first();
- const Pkcs11ProviderConfig &i = model->list[index.row()];
-
- ui.le_library->setText(i.library);
-
- if(i.slotevent_method == "trigger")
- ui.cb_slotmethod->setCurrentIndex(1);
- else if(i.slotevent_method == "poll")
- {
- ui.cb_slotmethod->setCurrentIndex(2);
- if(i.slotevent_timeout <= 0)
- ui.rb_polldefault->setChecked(true);
- else
- {
- ui.rb_pollcustom->setChecked(true);
- ui.sb_pollcustom->setValue(i.slotevent_timeout);
- }
- }
- else // auto
- ui.cb_slotmethod->setCurrentIndex(0);
- if(i.slotevent_method != "poll")
- {
- ui.rb_polldefault->setChecked(true);
- ui.sb_pollcustom->setValue(5);
- }
-
- ui.ck_modallowprotected->setChecked(i.allow_protected_authentication);
- ui.ck_certprivate->setChecked(i.cert_private);
-
- if(i.private_mask == 0)
- ui.ck_modeauto->setChecked(true);
- else
- {
- ui.ck_modesign->setChecked(i.private_mask & 1);
- ui.ck_modesignrecover->setChecked(i.private_mask & 2);
- ui.ck_modedecrypt->setChecked(i.private_mask & 4);
- ui.ck_modeunwrap->setChecked(i.private_mask & 8);
- }
- }
- else if(selected.indexes().isEmpty() && !deselected.indexes().isEmpty())
- {
- // restore defaults for all details widgets
- ui.le_library->setText(QString());
- ui.cb_slotmethod->setCurrentIndex(0);
- ui.rb_polldefault->setChecked(true);
- ui.sb_pollcustom->setValue(5);
- ui.ck_modallowprotected->setChecked(false);
- ui.ck_certprivate->setChecked(false);
- ui.ck_modeauto->setChecked(true);
-
- // flip to first page, disable
- ui.tb_details->setCurrentIndex(0);
- ui.pb_remove->setEnabled(false);
- ui.tb_details->setEnabled(false);
- }
-
- ignore_dataChanged = false;
- }
-
- void module_add()
- {
- // find unused default name
- QString name;
- for(int n = 1;; ++n)
- {
- if(n == 1)
- name = tr("New Module");
- else
- name = tr("New Module (%1)").arg(n);
-
- bool have_name_already = false;
- for(int n = 0; n < model->list.count(); ++n)
- {
- const Pkcs11ProviderConfig &i = model->list[n];
- if(i.name == name)
- {
- have_name_already = true;
- break;
- }
- }
- if(!have_name_already)
- break;
- }
-
- Pkcs11ProviderConfig i;
- i.name = name;
- i.enabled = true;
- model->addItem(i);
-
- dataChanged();
-
- QModelIndex index = model->index(model->list.count() - 1);
-
- // flip to first page
- ui.tb_details->setCurrentIndex(0);
-
- // edit this item
- ui.lv_modules->setFocus();
- ui.lv_modules->setCurrentIndex(index);
- ui.lv_modules->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
- ui.lv_modules->edit(index);
- }
-
- void module_remove()
- {
- QItemSelection selection = ui.lv_modules->selectionModel()->selection();
- if(selection.indexes().isEmpty())
- return;
- QModelIndex index = selection.indexes().first();
- model->removeItem(index.row());
-
- dataChanged();
- }
-
- void library_browse()
- {
- QString fileName = QFileDialog::getOpenFileName(q, tr("Select PKCS#11 Module"), QString(), tr("PKCS#11 Modules (*.*)"));
- if(fileName.isEmpty())
- return;
-
- ui.le_library->setText(fileName);
- }
-
- void slotmethod_currentIndexChanged(int index)
- {
- if(index == 2) // Polling
- ui.gb_poll->setEnabled(true);
- else
- ui.gb_poll->setEnabled(false);
-
- dataChanged();
- }
-
- void modeauto_toggled(bool checked)
- {
- if(checked)
- {
- if(ui.ck_modesign->isChecked())
- ui.ck_modesign->setChecked(false);
- if(ui.ck_modesignrecover->isChecked())
- ui.ck_modesignrecover->setChecked(false);
- if(ui.ck_modedecrypt->isChecked())
- ui.ck_modedecrypt->setChecked(false);
- if(ui.ck_modeunwrap->isChecked())
- ui.ck_modeunwrap->setChecked(false);
- }
- else
- {
- if(!ui.ck_modesign->isChecked()
- && !ui.ck_modesignrecover->isChecked()
- && !ui.ck_modedecrypt->isChecked()
- && !ui.ck_modeunwrap->isChecked())
- {
- ui.ck_modesign->setChecked(true);
- ui.ck_modesignrecover->setChecked(true);
- ui.ck_modedecrypt->setChecked(true);
- ui.ck_modeunwrap->setChecked(true);
- }
- }
-
- dataChanged();
- }
-
- void modenonauto_toggled(bool checked)
- {
- if(checked)
- {
- if(ui.ck_modeauto->isChecked())
- ui.ck_modeauto->setChecked(false);
- }
- else
- {
- if(!ui.ck_modesign->isChecked()
- && !ui.ck_modesignrecover->isChecked()
- && !ui.ck_modedecrypt->isChecked()
- && !ui.ck_modeunwrap->isChecked())
- {
- ui.ck_modeauto->setChecked(true);
- }
- }
-
- dataChanged();
- }
+ void model_editFailed(const QModelIndex &index, const QString &reasonString)
+ {
+ // if the dialog has already been dismissed, then don't
+ // bother with handling the editing failure
+ if (done) {
+ return;
+ }
+
+ // show error dialog, and don't allow dimissing the dialog
+ // during. we need this, because the the dismiss request
+ // can be queued, and end up being invoked during the
+ // QMessageBox nested eventloop.
+ allow_close = false;
+ QMessageBox::information(q, tr("Module Configuration"), reasonString);
+ allow_close = true;
+
+ // return to edit mode for the item
+ ui.lv_modules->setFocus();
+ ui.lv_modules->setCurrentIndex(index);
+ ui.lv_modules->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
+ ui.lv_modules->edit(index);
+ }
+
+ void dataChanged()
+ {
+ if (ignore_dataChanged) {
+ return;
+ }
+
+ if (dirty) {
+ return;
+ }
+
+ dirty = true;
+ ui.buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
+ }
+
+ void module_selectionChanged(const QItemSelection &selected, const QItemSelection &deselected)
+ {
+ if (!deselected.indexes().isEmpty()) {
+ QModelIndex index = deselected.indexes().first();
+ save_module(index.row());
+ }
+
+ ignore_dataChanged = true;
+
+ if (!selected.indexes().isEmpty()) {
+ if (deselected.indexes().isEmpty()) {
+ ui.pb_remove->setEnabled(true);
+ ui.tb_details->setEnabled(true);
+ }
+
+ QModelIndex index = selected.indexes().first();
+ const Pkcs11ProviderConfig &i = model->list[index.row()];
+
+ ui.le_library->setText(i.library);
+
+ if (i.slotevent_method == "trigger") {
+ ui.cb_slotmethod->setCurrentIndex(1);
+ } else if (i.slotevent_method == "poll") {
+ ui.cb_slotmethod->setCurrentIndex(2);
+ if (i.slotevent_timeout <= 0) {
+ ui.rb_polldefault->setChecked(true);
+ } else {
+ ui.rb_pollcustom->setChecked(true);
+ ui.sb_pollcustom->setValue(i.slotevent_timeout);
+ }
+ } else { // auto
+ ui.cb_slotmethod->setCurrentIndex(0);
+ }
+ if (i.slotevent_method != "poll") {
+ ui.rb_polldefault->setChecked(true);
+ ui.sb_pollcustom->setValue(5);
+ }
+
+ ui.ck_modallowprotected->setChecked(i.allow_protected_authentication);
+ ui.ck_certprivate->setChecked(i.cert_private);
+
+ if (i.private_mask == 0) {
+ ui.ck_modeauto->setChecked(true);
+ } else {
+ ui.ck_modesign->setChecked(i.private_mask & 1);
+ ui.ck_modesignrecover->setChecked(i.private_mask & 2);
+ ui.ck_modedecrypt->setChecked(i.private_mask & 4);
+ ui.ck_modeunwrap->setChecked(i.private_mask & 8);
+ }
+ } else if (selected.indexes().isEmpty() && !deselected.indexes().isEmpty()) {
+ // restore defaults for all details widgets
+ ui.le_library->setText(QString());
+ ui.cb_slotmethod->setCurrentIndex(0);
+ ui.rb_polldefault->setChecked(true);
+ ui.sb_pollcustom->setValue(5);
+ ui.ck_modallowprotected->setChecked(false);
+ ui.ck_certprivate->setChecked(false);
+ ui.ck_modeauto->setChecked(true);
+
+ // flip to first page, disable
+ ui.tb_details->setCurrentIndex(0);
+ ui.pb_remove->setEnabled(false);
+ ui.tb_details->setEnabled(false);
+ }
+
+ ignore_dataChanged = false;
+ }
+
+ void module_add()
+ {
+ // find unused default name
+ QString name;
+ for (int n = 1;; ++n) {
+ if (n == 1) {
+ name = tr("New Module");
+ } else {
+ name = tr("New Module (%1)").arg(n);
+ }
+
+ bool have_name_already = false;
+ for (int n = 0; n < model->list.count(); ++n) {
+ const Pkcs11ProviderConfig &i = model->list[n];
+ if (i.name == name) {
+ have_name_already = true;
+ break;
+ }
+ }
+ if (!have_name_already) {
+ break;
+ }
+ }
+
+ Pkcs11ProviderConfig i;
+ i.name = name;
+ i.enabled = true;
+ model->addItem(i);
+
+ dataChanged();
+
+ QModelIndex index = model->index(model->list.count() - 1);
+
+ // flip to first page
+ ui.tb_details->setCurrentIndex(0);
+
+ // edit this item
+ ui.lv_modules->setFocus();
+ ui.lv_modules->setCurrentIndex(index);
+ ui.lv_modules->selectionModel()->select(index, QItemSelectionModel::Clear | QItemSelectionModel::Select | QItemSelectionModel::Current);
+ ui.lv_modules->edit(index);
+ }
+
+ void module_remove()
+ {
+ QItemSelection selection = ui.lv_modules->selectionModel()->selection();
+ if (selection.indexes().isEmpty()) {
+ return;
+ }
+ QModelIndex index = selection.indexes().first();
+ model->removeItem(index.row());
+
+ dataChanged();
+ }
+
+ void library_browse()
+ {
+ QString fileName = QFileDialog::getOpenFileName(q, tr("Select PKCS#11 Module"), QString(), tr("PKCS#11 Modules (*.*)"));
+ if (fileName.isEmpty()) {
+ return;
+ }
+
+ ui.le_library->setText(fileName);
+ }
+
+ void slotmethod_currentIndexChanged(int index)
+ {
+ if (index == 2) { // Polling
+ ui.gb_poll->setEnabled(true);
+ } else {
+ ui.gb_poll->setEnabled(false);
+ }
+
+ dataChanged();
+ }
+
+ void modeauto_toggled(bool checked)
+ {
+ if (checked) {
+ if (ui.ck_modesign->isChecked()) {
+ ui.ck_modesign->setChecked(false);
+ }
+ if (ui.ck_modesignrecover->isChecked()) {
+ ui.ck_modesignrecover->setChecked(false);
+ }
+ if (ui.ck_modedecrypt->isChecked()) {
+ ui.ck_modedecrypt->setChecked(false);
+ }
+ if (ui.ck_modeunwrap->isChecked()) {
+ ui.ck_modeunwrap->setChecked(false);
+ }
+ } else {
+ if (!ui.ck_modesign->isChecked()
+ && !ui.ck_modesignrecover->isChecked()
+ && !ui.ck_modedecrypt->isChecked()
+ && !ui.ck_modeunwrap->isChecked()) {
+ ui.ck_modesign->setChecked(true);
+ ui.ck_modesignrecover->setChecked(true);
+ ui.ck_modedecrypt->setChecked(true);
+ ui.ck_modeunwrap->setChecked(true);
+ }
+ }
+
+ dataChanged();
+ }
+
+ void modenonauto_toggled(bool checked)
+ {
+ if (checked) {
+ if (ui.ck_modeauto->isChecked()) {
+ ui.ck_modeauto->setChecked(false);
+ }
+ } else {
+ if (!ui.ck_modesign->isChecked()
+ && !ui.ck_modesignrecover->isChecked()
+ && !ui.ck_modedecrypt->isChecked()
+ && !ui.ck_modeunwrap->isChecked()) {
+ ui.ck_modeauto->setChecked(true);
+ }
+ }
+
+ dataChanged();
+ }
};
Pkcs11ConfigDlg::Pkcs11ConfigDlg(QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- QVariantMap config;
- QCA::Provider *p = get_pkcs11_provider(&config);
- if(p)
- d = new Private(this, p->name(), config);
- else
- d = new Private(this, QString(), QVariantMap());
+ QVariantMap config;
+ QCA::Provider *p = get_pkcs11_provider(&config);
+ if (p) {
+ d = new Private(this, p->name(), config);
+ } else {
+ d = new Private(this, QString(), QVariantMap());
+ }
}
Pkcs11ConfigDlg::Pkcs11ConfigDlg(const QString &providerName, const QVariantMap &config, QWidget *parent) :
- QDialog(parent)
+ QDialog(parent)
{
- d = new Private(this, providerName, config);
+ d = new Private(this, providerName, config);
}
Pkcs11ConfigDlg::~Pkcs11ConfigDlg()
{
- delete d;
+ delete d;
}
void Pkcs11ConfigDlg::done(int r)
{
- if(!d->allow_close)
- return;
-
- d->done = true;
- if(r == Accepted)
- d->save();
- QDialog::done(r);
+ if (!d->allow_close) {
+ return;
+ }
+
+ d->done = true;
+ if (r == Accepted) {
+ d->save();
+ }
+ QDialog::done(r);
}
bool Pkcs11ConfigDlg::isSupported()
{
- return (get_pkcs11_provider() ? true : false);
+ return (get_pkcs11_provider() ? true : false);
}
#include "pkcs11configdlg.moc"
diff --git a/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.h b/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.h
index 6a225ff8..a09df6f4 100644
--- a/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.h
+++ b/examples/cmssigner/pkcs11configdlg/pkcs11configdlg.h
@@ -1,47 +1,47 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef PKCS11CONFIGDLG_H
#define PKCS11CONFIGDLG_H
#include <QDialog>
#include <QVariantMap>
// support for the 'http://affinix.com/qca/forms/qca-pkcs11#1.0' provider form
class Pkcs11ConfigDlg : public QDialog
{
public:
- Pkcs11ConfigDlg(QWidget *parent = 0);
- Pkcs11ConfigDlg(const QString &providerName, const QVariantMap &config, QWidget *parent = 0);
- ~Pkcs11ConfigDlg();
+ Pkcs11ConfigDlg(QWidget *parent = 0);
+ Pkcs11ConfigDlg(const QString &providerName, const QVariantMap &config, QWidget *parent = 0);
+ ~Pkcs11ConfigDlg();
- static bool isSupported();
+ static bool isSupported();
protected slots:
- virtual void done(int r);
+ virtual void done(int r);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
#endif
diff --git a/examples/cmssigner/prompter.cpp b/examples/cmssigner/prompter.cpp
index 98f223c3..ae5549ed 100644
--- a/examples/cmssigner/prompter.cpp
+++ b/examples/cmssigner/prompter.cpp
@@ -1,321 +1,297 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "prompter.h"
#include <QtCore>
#include <QtGui>
#include <QtCrypto>
#include <QMessageBox>
#include <QInputDialog>
#include <QApplication>
class Prompter::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- Prompter *q;
-
- class Item
- {
- public:
- int id;
- QCA::Event event;
- };
-
- QCA::EventHandler handler;
- QList<Item> pending;
- bool prompting;
- QMessageBox *token_prompt;
- bool auto_accept;
-
- QCA::KeyStoreManager ksm;
- QList<QCA::KeyStore*> keyStores;
-
- Private(Prompter *_q) :
- QObject(_q),
- q(_q),
- handler(this),
- prompting(false),
- token_prompt(0),
- ksm(this)
- {
- connect(&handler, SIGNAL(eventReady(int, const QCA::Event &)), SLOT(ph_eventReady(int, const QCA::Event &)));
- handler.start();
-
- connect(&ksm, SIGNAL(keyStoreAvailable(const QString &)), SLOT(ks_available(const QString &)));
- foreach(const QString &keyStoreId, ksm.keyStores())
- ks_available(keyStoreId);
- }
-
- ~Private()
- {
- qDeleteAll(keyStores);
-
- while(!pending.isEmpty())
- handler.reject(pending.takeFirst().id);
- }
+ Prompter *q;
+
+ class Item
+ {
+ public:
+ int id;
+ QCA::Event event;
+ };
+
+ QCA::EventHandler handler;
+ QList<Item> pending;
+ bool prompting;
+ QMessageBox *token_prompt;
+ bool auto_accept;
+
+ QCA::KeyStoreManager ksm;
+ QList<QCA::KeyStore *> keyStores;
+
+ Private(Prompter *_q) :
+ QObject(_q),
+ q(_q),
+ handler(this),
+ prompting(false),
+ token_prompt(0),
+ ksm(this)
+ {
+ connect(&handler, SIGNAL(eventReady(int,QCA::Event)), SLOT(ph_eventReady(int,QCA::Event)));
+ handler.start();
+
+ connect(&ksm, SIGNAL(keyStoreAvailable(QString)), SLOT(ks_available(QString)));
+ foreach (const QString &keyStoreId, ksm.keyStores()) {
+ ks_available(keyStoreId);
+ }
+ }
+
+ ~Private()
+ {
+ qDeleteAll(keyStores);
+
+ while (!pending.isEmpty()) {
+ handler.reject(pending.takeFirst().id);
+ }
+ }
private slots:
- void ph_eventReady(int id, const QCA::Event &event)
- {
- Item i;
- i.id = id;
- i.event = event;
- pending += i;
- nextEvent();
- }
-
- void nextEvent()
- {
- if(prompting || pending.isEmpty())
- return;
-
- prompting = true;
-
- const Item &i = pending.first();
- const int &id = i.id;
- const QCA::Event &event = i.event;
-
- if(event.type() == QCA::Event::Password)
- {
- QCA::SecureArray known = q->knownPassword(event);
- if(!known.isEmpty())
- {
- handler.submitPassword(id, known);
- goto end;
- }
-
- QString type = Prompter::tr("password");
- if(event.passwordStyle() == QCA::Event::StylePassphrase)
- type = Prompter::tr("passphrase");
- else if(event.passwordStyle() == QCA::Event::StylePIN)
- type = Prompter::tr("PIN");
-
- QString str;
- if(event.source() == QCA::Event::KeyStore)
- {
- QString name;
- QCA::KeyStoreEntry entry = event.keyStoreEntry();
- if(!entry.isNull())
- {
- name = entry.name();
- }
- else
- {
- if(event.keyStoreInfo().type() == QCA::KeyStore::SmartCard)
- name = Prompter::tr("the '%1' token").arg(event.keyStoreInfo().name());
- else
- name = event.keyStoreInfo().name();
- }
- str = Prompter::tr("Enter %1 for %2").arg(type, name);
- }
- else if(!event.fileName().isEmpty())
- {
- QFileInfo fi(event.fileName());
- str = Prompter::tr("Enter %1 for %2:").arg(type, fi.fileName());
- }
- else
- str = Prompter::tr("Enter %1:").arg(type);
-
- bool ok;
- QString pass = QInputDialog::getText(0, QApplication::instance()->applicationName() + ": " + tr("Prompt"), str, QLineEdit::Password, QString(), &ok);
- if(ok)
- {
- QCA::SecureArray password = pass.toUtf8();
- q->userSubmitted(password, event);
- handler.submitPassword(id, password);
- }
- else
- handler.reject(id);
- }
- else if(event.type() == QCA::Event::Token)
- {
- // even though we're being prompted for a missing token,
- // we should still check if the token is present, due to
- // a possible race between insert and token request.
- bool found = false;
-
- // token-only
- if(event.keyStoreEntry().isNull())
- {
- foreach(QCA::KeyStore *ks, keyStores)
- {
- if(ks->id() == event.keyStoreInfo().id())
- {
- found = true;
- break;
- }
- }
- }
- // token-entry
- else
- {
- QCA::KeyStoreEntry kse = event.keyStoreEntry();
-
- QCA::KeyStore *ks = 0;
- foreach(QCA::KeyStore *i, keyStores)
- {
- if(i->id() == event.keyStoreInfo().id())
- {
- ks = i;
- break;
- }
- }
- if(ks)
- {
- QList<QCA::KeyStoreEntry> list = ks->entryList();
- foreach(const QCA::KeyStoreEntry &e, list)
- {
- if(e.id() == kse.id() && kse.isAvailable())
- {
- found = true;
- break;
- }
- }
- }
- }
- if(found)
- {
- // auto-accept
- handler.tokenOkay(id);
- return;
- }
-
- QCA::KeyStoreEntry entry = event.keyStoreEntry();
- QString name;
- if(!entry.isNull())
- {
- name = Prompter::tr("Please make %1 (of %2) available").arg(entry.name(), entry.storeName());
- }
- else
- {
- name = Prompter::tr("Please insert the '%1' token").arg(event.keyStoreInfo().name());
- }
-
- QString str = Prompter::tr("%1 and click OK.").arg(name);
-
- QMessageBox msgBox(QMessageBox::Information, QApplication::instance()->applicationName() + ": " + tr("Prompt"), str, QMessageBox::Ok | QMessageBox::Cancel, 0);
- token_prompt = &msgBox;
- auto_accept = false;
- if(msgBox.exec() == QMessageBox::Ok || auto_accept)
- handler.tokenOkay(id);
- else
- handler.reject(id);
- token_prompt = 0;
- }
- else
- handler.reject(id);
-
- end:
- pending.removeFirst();
- prompting = false;
-
- if(!pending.isEmpty())
- QMetaObject::invokeMethod(this, "nextEvent", Qt::QueuedConnection);
- }
-
- void ks_available(const QString &keyStoreId)
- {
- QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, &ksm);
- connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
- connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
- keyStores += ks;
- ks->startAsynchronousMode();
-
- // are we currently in a token-only prompt?
- if(token_prompt && pending.first().event.type() == QCA::Event::Token && pending.first().event.keyStoreEntry().isNull())
- {
- // was the token we're looking for just inserted?
- if(pending.first().event.keyStoreInfo().id() == keyStoreId)
- {
- // auto-accept
- auto_accept = true;
- token_prompt->accept();
- }
- }
- }
-
- void ks_unavailable()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
- keyStores.removeAll(ks);
- delete ks;
- }
-
- void ks_updated()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
-
- // are we currently in a token-entry prompt?
- if(token_prompt && pending.first().event.type() == QCA::Event::Token && !pending.first().event.keyStoreEntry().isNull())
- {
- QCA::KeyStoreEntry kse = pending.first().event.keyStoreEntry();
-
- // was the token of the entry we're looking for updated?
- if(pending.first().event.keyStoreInfo().id() == ks->id())
- {
- // is the entry available?
- bool avail = false;
- QList<QCA::KeyStoreEntry> list = ks->entryList();
- foreach(const QCA::KeyStoreEntry &e, list)
- {
- if(e.id() == kse.id())
- {
- avail = kse.isAvailable();
- break;
- }
- }
- if(avail)
- {
- // auto-accept
- auto_accept = true;
- token_prompt->accept();
- }
- }
- }
- }
+ void ph_eventReady(int id, const QCA::Event &event)
+ {
+ Item i;
+ i.id = id;
+ i.event = event;
+ pending += i;
+ nextEvent();
+ }
+
+ void nextEvent()
+ {
+ if (prompting || pending.isEmpty()) {
+ return;
+ }
+
+ prompting = true;
+
+ const Item &i = pending.first();
+ const int &id = i.id;
+ const QCA::Event &event = i.event;
+
+ if (event.type() == QCA::Event::Password) {
+ QCA::SecureArray known = q->knownPassword(event);
+ if (!known.isEmpty()) {
+ handler.submitPassword(id, known);
+ goto end;
+ }
+
+ QString type = Prompter::tr("password");
+ if (event.passwordStyle() == QCA::Event::StylePassphrase) {
+ type = Prompter::tr("passphrase");
+ } else if (event.passwordStyle() == QCA::Event::StylePIN) {
+ type = Prompter::tr("PIN");
+ }
+
+ QString str;
+ if (event.source() == QCA::Event::KeyStore) {
+ QString name;
+ QCA::KeyStoreEntry entry = event.keyStoreEntry();
+ if (!entry.isNull()) {
+ name = entry.name();
+ } else {
+ if (event.keyStoreInfo().type() == QCA::KeyStore::SmartCard) {
+ name = Prompter::tr("the '%1' token").arg(event.keyStoreInfo().name());
+ } else {
+ name = event.keyStoreInfo().name();
+ }
+ }
+ str = Prompter::tr("Enter %1 for %2").arg(type, name);
+ } else if (!event.fileName().isEmpty()) {
+ QFileInfo fi(event.fileName());
+ str = Prompter::tr("Enter %1 for %2:").arg(type, fi.fileName());
+ } else {
+ str = Prompter::tr("Enter %1:").arg(type);
+ }
+
+ bool ok;
+ QString pass = QInputDialog::getText(0, QApplication::instance()->applicationName() + ": " + tr("Prompt"), str, QLineEdit::Password, QString(), &ok);
+ if (ok) {
+ QCA::SecureArray password = pass.toUtf8();
+ q->userSubmitted(password, event);
+ handler.submitPassword(id, password);
+ } else {
+ handler.reject(id);
+ }
+ } else if (event.type() == QCA::Event::Token) {
+ // even though we're being prompted for a missing token,
+ // we should still check if the token is present, due to
+ // a possible race between insert and token request.
+ bool found = false;
+
+ // token-only
+ if (event.keyStoreEntry().isNull()) {
+ foreach (QCA::KeyStore *ks, keyStores) {
+ if (ks->id() == event.keyStoreInfo().id()) {
+ found = true;
+ break;
+ }
+ }
+ }
+ // token-entry
+ else {
+ QCA::KeyStoreEntry kse = event.keyStoreEntry();
+
+ QCA::KeyStore *ks = 0;
+ foreach (QCA::KeyStore *i, keyStores) {
+ if (i->id() == event.keyStoreInfo().id()) {
+ ks = i;
+ break;
+ }
+ }
+ if (ks) {
+ QList<QCA::KeyStoreEntry> list = ks->entryList();
+ foreach (const QCA::KeyStoreEntry &e, list) {
+ if (e.id() == kse.id() && kse.isAvailable()) {
+ found = true;
+ break;
+ }
+ }
+ }
+ }
+ if (found) {
+ // auto-accept
+ handler.tokenOkay(id);
+ return;
+ }
+
+ QCA::KeyStoreEntry entry = event.keyStoreEntry();
+ QString name;
+ if (!entry.isNull()) {
+ name = Prompter::tr("Please make %1 (of %2) available").arg(entry.name(), entry.storeName());
+ } else {
+ name = Prompter::tr("Please insert the '%1' token").arg(event.keyStoreInfo().name());
+ }
+
+ QString str = Prompter::tr("%1 and click OK.").arg(name);
+
+ QMessageBox msgBox(QMessageBox::Information, QApplication::instance()->applicationName() + ": " + tr("Prompt"), str, QMessageBox::Ok | QMessageBox::Cancel, 0);
+ token_prompt = &msgBox;
+ auto_accept = false;
+ if (msgBox.exec() == QMessageBox::Ok || auto_accept) {
+ handler.tokenOkay(id);
+ } else {
+ handler.reject(id);
+ }
+ token_prompt = 0;
+ } else {
+ handler.reject(id);
+ }
+
+ end:
+ pending.removeFirst();
+ prompting = false;
+
+ if (!pending.isEmpty()) {
+ QMetaObject::invokeMethod(this, "nextEvent", Qt::QueuedConnection);
+ }
+ }
+
+ void ks_available(const QString &keyStoreId)
+ {
+ QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, &ksm);
+ connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
+ connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
+ keyStores += ks;
+ ks->startAsynchronousMode();
+
+ // are we currently in a token-only prompt?
+ if (token_prompt && pending.first().event.type() == QCA::Event::Token && pending.first().event.keyStoreEntry().isNull()) {
+ // was the token we're looking for just inserted?
+ if (pending.first().event.keyStoreInfo().id() == keyStoreId) {
+ // auto-accept
+ auto_accept = true;
+ token_prompt->accept();
+ }
+ }
+ }
+
+ void ks_unavailable()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+ keyStores.removeAll(ks);
+ delete ks;
+ }
+
+ void ks_updated()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+
+ // are we currently in a token-entry prompt?
+ if (token_prompt && pending.first().event.type() == QCA::Event::Token && !pending.first().event.keyStoreEntry().isNull()) {
+ QCA::KeyStoreEntry kse = pending.first().event.keyStoreEntry();
+
+ // was the token of the entry we're looking for updated?
+ if (pending.first().event.keyStoreInfo().id() == ks->id()) {
+ // is the entry available?
+ bool avail = false;
+ QList<QCA::KeyStoreEntry> list = ks->entryList();
+ foreach (const QCA::KeyStoreEntry &e, list) {
+ if (e.id() == kse.id()) {
+ avail = kse.isAvailable();
+ break;
+ }
+ }
+ if (avail) {
+ // auto-accept
+ auto_accept = true;
+ token_prompt->accept();
+ }
+ }
+ }
+ }
};
Prompter::Prompter(QObject *parent) :
- QObject(parent)
+ QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
Prompter::~Prompter()
{
- delete d;
+ delete d;
}
QCA::SecureArray Prompter::knownPassword(const QCA::Event &event)
{
- Q_UNUSED(event);
- return QCA::SecureArray();
+ Q_UNUSED(event);
+ return QCA::SecureArray();
}
void Prompter::userSubmitted(const QCA::SecureArray &password, const QCA::Event &event)
{
- Q_UNUSED(password);
- Q_UNUSED(event);
+ Q_UNUSED(password);
+ Q_UNUSED(event);
}
#include "prompter.moc"
diff --git a/examples/cmssigner/prompter.h b/examples/cmssigner/prompter.h
index daa9d907..fd289ee8 100644
--- a/examples/cmssigner/prompter.h
+++ b/examples/cmssigner/prompter.h
@@ -1,57 +1,57 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef PROMPTER_H
#define PROMPTER_H
#include <QObject>
namespace QCA
{
- class SecureArray;
- class Event;
+class SecureArray;
+class Event;
}
class Prompter : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- Prompter(QObject *parent = 0);
- ~Prompter();
+ Prompter(QObject *parent = 0);
+ ~Prompter();
protected:
- // called with every password event, to check for a known value.
- // reimplement it to provide known/cached passwords.
- virtual QCA::SecureArray knownPassword(const QCA::Event &event);
+ // called with every password event, to check for a known value.
+ // reimplement it to provide known/cached passwords.
+ virtual QCA::SecureArray knownPassword(const QCA::Event &event);
- // called when a user-entered password is submitted. note that this
- // does not mean the password was correct. to know if the password
- // was correct, you'll have to match up the event information with
- // the operation that triggered it.
- virtual void userSubmitted(const QCA::SecureArray &password, const QCA::Event &event);
+ // called when a user-entered password is submitted. note that this
+ // does not mean the password was correct. to know if the password
+ // was correct, you'll have to match up the event information with
+ // the operation that triggered it.
+ virtual void userSubmitted(const QCA::SecureArray &password, const QCA::Event &event);
private:
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
#endif
diff --git a/examples/eventhandlerdemo/eventhandlerdemo.cpp b/examples/eventhandlerdemo/eventhandlerdemo.cpp
index aa1c844f..61c2f7bb 100644
--- a/examples/eventhandlerdemo/eventhandlerdemo.cpp
+++ b/examples/eventhandlerdemo/eventhandlerdemo.cpp
@@ -1,165 +1,165 @@
/*
Copyright (C) 2007 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <iostream>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
/**
We need a class on the client side to handle password requests.
*/
class ClientPassphraseHandler: public QObject
{
Q_OBJECT
public:
- ClientPassphraseHandler(QObject *parent = 0) : QObject( parent )
+ ClientPassphraseHandler(QObject *parent = 0) : QObject(parent)
{
// When the PasswordAsker or TokenAsker needs to interact
// with the user, it raises a signal. We connect that to a
// local slot to get the required information.
- connect( &m_handler, SIGNAL( eventReady(int, const QCA::Event &) ),
- SLOT( my_eventReady(int, const QCA::Event &) ) );
+ connect(&m_handler, SIGNAL(eventReady(int,QCA::Event)),
+ SLOT(my_eventReady(int,QCA::Event)));
// Now that we are set up, we can start the EventHandler. Nothing
// will happen if you don't call this method.
m_handler.start();
}
private slots:
// This slot gets called when the provider needs a token inserted,
// or to get a passphrase / password / PIN.
void my_eventReady(int id, const QCA::Event &event)
{
// We can sanity check the event
- if ( event.isNull() ) {
+ if (event.isNull()) {
return;
}
// Events can be associated with a a keystore or a file/bytearray
// You can tell which by looking at the Source
- if ( event.source() == QCA::Event::KeyStore ) {
+ if (event.source() == QCA::Event::KeyStore) {
std::cout << "Event is associated with a key store operation" << std::endl;
- } else if ( event.source() == QCA::Event::Data ) {
+ } else if (event.source() == QCA::Event::Data) {
std::cout << "Event is associated with a file or some other data" << std::endl;
// if the event comes from a file type operation, you can get the
// name / label using fileName()
- std::cout << " Filename: " << qPrintable( event.fileName() ) << std::endl;
+ std::cout << " Filename: " << qPrintable(event.fileName()) << std::endl;
} else {
std::cout << "Unexpected Source for Event" << std::endl;
}
// There are different kinds of events.
- if ( event.type() == QCA::Event::Token ) {
+ if (event.type() == QCA::Event::Token) {
// You would typically ask the user to insert the token here
std::cout << "Request for token" << std::endl;
// we just fake it for this demo.
- m_handler.tokenOkay( id );
+ m_handler.tokenOkay(id);
// you could use m_handler.reject( id ) to refuse the token request
- } else if ( event.type() == QCA::Event::Password ) {
+ } else if (event.type() == QCA::Event::Password) {
std::cout << "Request for password, passphrase or PIN" << std::endl;
// and within the Password type, we have a few different styles.
- if ( event.passwordStyle() == QCA::Event::StylePassword ) {
+ if (event.passwordStyle() == QCA::Event::StylePassword) {
std::cout << " [Password request]" << std::endl;
- } else if ( event.passwordStyle() == QCA::Event::StylePassphrase ) {
+ } else if (event.passwordStyle() == QCA::Event::StylePassphrase) {
std::cout << " [Passphrase request]" << std::endl;
- } else if ( event.passwordStyle() == QCA::Event::StylePIN ){
+ } else if (event.passwordStyle() == QCA::Event::StylePIN) {
std::cout << " [PIN request]" << std::endl;
} else {
std::cout << " [unexpect request style]" << std::endl;
}
// You would typically request the password/PIN/passphrase.
// again, we just fake it.
- m_handler.submitPassword( id, QCA::SecureArray( "hello" ) );
+ m_handler.submitPassword(id, QCA::SecureArray("hello"));
} else {
std::cout << "Unexpected event type" << std::endl;
}
}
private:
QCA::EventHandler m_handler;
};
void asker_procedure();
class AskerThread : public QThread
{
Q_OBJECT
protected:
virtual void run()
{
asker_procedure();
}
};
int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication exampleApp(argc, argv);
ClientPassphraseHandler cph;
// handler and asker cannot occur in the same thread
AskerThread askerThread;
QObject::connect(&askerThread, SIGNAL(finished()), &exampleApp, SLOT(quit()));
askerThread.start();
exampleApp.exec();
return 0;
}
void asker_procedure()
{
QCA::PasswordAsker pwAsker;
- pwAsker.ask( QCA::Event::StylePassword, "foo.tmp", 0 );
+ pwAsker.ask(QCA::Event::StylePassword, "foo.tmp", 0);
pwAsker.waitForResponse();
std::cout << "Password was: " << pwAsker.password().toByteArray().data() << std::endl;
std::cout << std::endl << "Now do token:" << std::endl;
QCA::TokenAsker tokenAsker;
- tokenAsker.ask( QCA::KeyStoreInfo( QCA::KeyStore::SmartCard, "Token Id", "Token Name" ), QCA::KeyStoreEntry(), 0 );
+ tokenAsker.ask(QCA::KeyStoreInfo(QCA::KeyStore::SmartCard, "Token Id", "Token Name"), QCA::KeyStoreEntry(), 0);
tokenAsker.waitForResponse();
- if ( tokenAsker.accepted() ) {
+ if (tokenAsker.accepted()) {
std::cout << "Token was accepted" << std::endl;
} else {
std::cout << "Token was not accepted" << std::endl;
}
}
#include "eventhandlerdemo.moc"
diff --git a/examples/hashtest/hashtest.cpp b/examples/hashtest/hashtest.cpp
index 7758e5c1..e40d1296 100644
--- a/examples/hashtest/hashtest.cpp
+++ b/examples/hashtest/hashtest.cpp
@@ -1,78 +1,78 @@
/*
Copyright (C) 2004 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto/QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <stdio.h>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
- // the Initializer object sets things up, and
- // also does cleanup when it goes out of scope
- QCA::Initializer init;
+ // the Initializer object sets things up, and
+ // also does cleanup when it goes out of scope
+ QCA::Initializer init;
- QCoreApplication app(argc, argv);
+ QCoreApplication app(argc, argv);
- // we use the first argument if provided, or
- // use "hello" if no arguments
- QCA::SecureArray arg = (argc >= 2) ? argv[1] : "hello";
+ // we use the first argument if provided, or
+ // use "hello" if no arguments
+ QCA::SecureArray arg = (argc >= 2) ? argv[1] : "hello";
- // must always check that an algorithm is supported before using it
- if( !QCA::isSupported("sha1") )
- printf("SHA1 not supported!\n");
- else {
- // this shows the "all in one" approach
- QString result = QCA::Hash("sha1").hashToString(arg);
- printf("sha1(\"%s\") = [%s]\n", arg.data(), qPrintable(result));
- }
+ // must always check that an algorithm is supported before using it
+ if (!QCA::isSupported("sha1")) {
+ printf("SHA1 not supported!\n");
+ } else {
+ // this shows the "all in one" approach
+ QString result = QCA::Hash("sha1").hashToString(arg);
+ printf("sha1(\"%s\") = [%s]\n", arg.data(), qPrintable(result));
+ }
- // must always check that an algorithm is supported before using it
- if( !QCA::isSupported("md5") )
- printf("MD5 not supported!\n");
- else {
- // this shows the incremental approach. Naturally
- // for this simple job, we could use the "all in one"
- // approach - this is an example, after all :-)
- QCA::SecureArray part1(arg.toByteArray().left(3)); // three chars - "hel"
- QCA::SecureArray part2(arg.toByteArray().mid(3)); // the rest - "lo"
+ // must always check that an algorithm is supported before using it
+ if (!QCA::isSupported("md5")) {
+ printf("MD5 not supported!\n");
+ } else {
+ // this shows the incremental approach. Naturally
+ // for this simple job, we could use the "all in one"
+ // approach - this is an example, after all :-)
+ QCA::SecureArray part1(arg.toByteArray().left(3)); // three chars - "hel"
+ QCA::SecureArray part2(arg.toByteArray().mid(3)); // the rest - "lo"
- // create the required object.
- QCA::Hash hashObject("md5");
- // we split it into two parts to show incremental update
- hashObject.update(part1);
- hashObject.update(part2);
- // no more updates after calling final.
- QCA::SecureArray resultArray = hashObject.final();
- // convert the result into printable hexadecimal.
- QString result = QCA::arrayToHex(resultArray.toByteArray());
- printf("md5(\"%s\") = [%s]\n", arg.data(), qPrintable(result));
- }
+ // create the required object.
+ QCA::Hash hashObject("md5");
+ // we split it into two parts to show incremental update
+ hashObject.update(part1);
+ hashObject.update(part2);
+ // no more updates after calling final.
+ QCA::SecureArray resultArray = hashObject.final();
+ // convert the result into printable hexadecimal.
+ QString result = QCA::arrayToHex(resultArray.toByteArray());
+ printf("md5(\"%s\") = [%s]\n", arg.data(), qPrintable(result));
+ }
- return 0;
+ return 0;
}
diff --git a/examples/hextest/hextest.cpp b/examples/hextest/hextest.cpp
index aa41704f..dabf1659 100644
--- a/examples/hextest/hextest.cpp
+++ b/examples/hextest/hextest.cpp
@@ -1,70 +1,70 @@
/*
Copyright (C) 2005 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <iostream>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
- // the Initializer object sets things up, and
- // also does cleanup when it goes out of scope
- QCA::Initializer init;
+ // the Initializer object sets things up, and
+ // also does cleanup when it goes out of scope
+ QCA::Initializer init;
- QCoreApplication app(argc, argv);
+ QCoreApplication app(argc, argv);
- // we use the first argument as the data to encode / decode
- // if an argument is provided. Use "hello" if no argument
- QByteArray arg; // empty array
- arg.append((argc >= 2) ? argv[1] : "hello");
+ // we use the first argument as the data to encode / decode
+ // if an argument is provided. Use "hello" if no argument
+ QByteArray arg; // empty array
+ arg.append((argc >= 2) ? argv[1] : "hello");
- // create our object, which does encoding by default
- // QCA::Hex encoder(QCA::Encode); is equivalent
- QCA::Hex encoder;
+ // create our object, which does encoding by default
+ // QCA::Hex encoder(QCA::Encode); is equivalent
+ QCA::Hex encoder;
- // You might prefer to use encoder.encode(); and have
- // it return a QCA::SecureArray, depending on your needs
- QString encoded = encoder.arrayToString(arg);
+ // You might prefer to use encoder.encode(); and have
+ // it return a QCA::SecureArray, depending on your needs
+ QString encoded = encoder.arrayToString(arg);
- std::cout << arg.data() << " in hex encoding is ";
- std::cout << encoded.toLatin1().data() << std::endl;
+ std::cout << arg.data() << " in hex encoding is ";
+ std::cout << encoded.toLatin1().data() << std::endl;
- // This time, we'll create an object to decode hexadecimal.
- // We could also have reused the existing object, calling
- // clear(); and setup(QCA::Decode); on it.
- QCA::Hex decoder(QCA::Decode);
+ // This time, we'll create an object to decode hexadecimal.
+ // We could also have reused the existing object, calling
+ // clear(); and setup(QCA::Decode); on it.
+ QCA::Hex decoder(QCA::Decode);
- // This time, we convert a QString into a QString
- QString decoded = decoder.decodeString(encoded);
+ // This time, we convert a QString into a QString
+ QString decoded = decoder.decodeString(encoded);
- std::cout << encoded.toLatin1().data() << " decoded from hex is ";
- std::cout << decoded.toLatin1().data() << std::endl;
+ std::cout << encoded.toLatin1().data() << " decoded from hex is ";
+ std::cout << decoded.toLatin1().data() << std::endl;
- return 0;
+ return 0;
}
diff --git a/examples/keyloader/keyloader.cpp b/examples/keyloader/keyloader.cpp
index b9f90dc0..93619056 100644
--- a/examples/keyloader/keyloader.cpp
+++ b/examples/keyloader/keyloader.cpp
@@ -1,120 +1,117 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <QTimer>
#include <stdio.h>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class PassphraseHandler: public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- QCA::EventHandler handler;
+ QCA::EventHandler handler;
- PassphraseHandler(QObject *parent = 0) : QObject(parent)
- {
- connect(&handler, SIGNAL(eventReady(int, const QCA::Event &)),
- SLOT(eh_eventReady(int, const QCA::Event &)));
- handler.start();
- }
+ PassphraseHandler(QObject *parent = 0) : QObject(parent)
+ {
+ connect(&handler, SIGNAL(eventReady(int,QCA::Event)),
+ SLOT(eh_eventReady(int,QCA::Event)));
+ handler.start();
+ }
private slots:
- void eh_eventReady(int id, const QCA::Event &event)
- {
- if(event.type() == QCA::Event::Password)
- {
- QCA::SecureArray pass;
- QCA::ConsolePrompt prompt;
- prompt.getHidden("Passphrase");
- prompt.waitForFinished();
- pass = prompt.result();
- handler.submitPassword(id, pass);
- }
- else
- handler.reject(id);
- }
+ void eh_eventReady(int id, const QCA::Event &event)
+ {
+ if (event.type() == QCA::Event::Password) {
+ QCA::SecureArray pass;
+ QCA::ConsolePrompt prompt;
+ prompt.getHidden("Passphrase");
+ prompt.waitForFinished();
+ pass = prompt.result();
+ handler.submitPassword(id, pass);
+ } else {
+ handler.reject(id);
+ }
+ }
};
class App : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- QCA::KeyLoader keyLoader;
- QString str;
+ QCA::KeyLoader keyLoader;
+ QString str;
- App()
- {
- connect(&keyLoader, SIGNAL(finished()), SLOT(kl_finished()));
- }
+ App()
+ {
+ connect(&keyLoader, SIGNAL(finished()), SLOT(kl_finished()));
+ }
public slots:
- void start()
- {
- keyLoader.loadPrivateKeyFromPEMFile(str);
- }
+ void start()
+ {
+ keyLoader.loadPrivateKeyFromPEMFile(str);
+ }
signals:
- void quit();
+ void quit();
private slots:
- void kl_finished()
- {
- if(keyLoader.convertResult() == QCA::ConvertGood)
- {
- QCA::PrivateKey key = keyLoader.privateKey();
- printf("Loaded successfully. Bits: %d\n", key.bitSize());
- }
- else
- printf("Unable to load.\n");
-
- emit quit();
- }
+ void kl_finished()
+ {
+ if (keyLoader.convertResult() == QCA::ConvertGood) {
+ QCA::PrivateKey key = keyLoader.privateKey();
+ printf("Loaded successfully. Bits: %d\n", key.bitSize());
+ } else {
+ printf("Unable to load.\n");
+ }
+
+ emit quit();
+ }
};
int main(int argc, char **argv)
{
- QCA::Initializer init;
- QCoreApplication qapp(argc, argv);
-
- if(argc < 2)
- {
- printf("usage: keyloader [privatekey.pem]\n");
- return 0;
- }
-
- PassphraseHandler passphraseHandler;
- App app;
- app.str = argv[1];
- QObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit()));
- QTimer::singleShot(0, &app, SLOT(start()));
- qapp.exec();
- return 0;
+ QCA::Initializer init;
+ QCoreApplication qapp(argc, argv);
+
+ if (argc < 2) {
+ printf("usage: keyloader [privatekey.pem]\n");
+ return 0;
+ }
+
+ PassphraseHandler passphraseHandler;
+ App app;
+ app.str = argv[1];
+ QObject::connect(&app, SIGNAL(quit()), &qapp, SLOT(quit()));
+ QTimer::singleShot(0, &app, SLOT(start()));
+ qapp.exec();
+ return 0;
}
#include "keyloader.moc"
diff --git a/examples/mactest/mactest.cpp b/examples/mactest/mactest.cpp
index b3dc160b..afd0e699 100644
--- a/examples/mactest/mactest.cpp
+++ b/examples/mactest/mactest.cpp
@@ -1,86 +1,86 @@
/*
Copyright (C) 2004, 2006 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <QDebug>
// needed for printf
#include<stdio.h>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
- // the Initializer object sets things up, and
- // also does cleanup when it goes out of scope
- QCA::Initializer init;
-
- QCoreApplication app(argc, argv);
-
- qDebug() << "This example shows hashed MAC";
-
- // we use the first argument as the data to authenticate
- // if an argument is provided. Use "hello" if no argument
- QByteArray arg = (argc >= 2) ? argv[1] : "hello";
-
- // we use the second argument as the key to authenticate
- // with, if two arguments are provided. Use "secret" as
- // the key if less than two arguments.
- QCA::SecureArray key((argc >= 3) ? argv[2] : "secret");
-
- // must always check that an algorithm is supported before using it
- if( !QCA::isSupported("hmac(sha1)") ) {
- printf("HMAC(SHA1) not supported!\n");
- } else {
- // create the required object using HMAC with SHA-1, and an
- // empty key.
- QCA::MessageAuthenticationCode hmacObject( "hmac(sha1)", QCA::SecureArray() );
-
- // create the key
- QCA::SymmetricKey keyObject(key);
-
- // set the HMAC object to use the key
- hmacObject.setup(key);
- // that could also have been done in the
- // QCA::MessageAuthenticationCode constructor
-
- // we split it into two parts to show incremental update
- QCA::SecureArray part1(arg.left(3)); // three chars - "hel"
- QCA::SecureArray part2(arg.mid(3)); // the rest - "lo"
- hmacObject.update(part1);
- hmacObject.update(part2);
-
- // no more updates after calling final.
- QCA::SecureArray resultArray = hmacObject.final();
-
- // convert the result into printable hexadecimal.
- QString result = QCA::arrayToHex(resultArray.toByteArray());
- printf("HMAC(SHA1) of \"%s\" with \"%s\" = [%s]\n", arg.data(), key.data(), result.toLatin1().data());
- }
-
- return 0;
+ // the Initializer object sets things up, and
+ // also does cleanup when it goes out of scope
+ QCA::Initializer init;
+
+ QCoreApplication app(argc, argv);
+
+ qDebug() << "This example shows hashed MAC";
+
+ // we use the first argument as the data to authenticate
+ // if an argument is provided. Use "hello" if no argument
+ QByteArray arg = (argc >= 2) ? argv[1] : "hello";
+
+ // we use the second argument as the key to authenticate
+ // with, if two arguments are provided. Use "secret" as
+ // the key if less than two arguments.
+ QCA::SecureArray key((argc >= 3) ? argv[2] : "secret");
+
+ // must always check that an algorithm is supported before using it
+ if (!QCA::isSupported("hmac(sha1)")) {
+ printf("HMAC(SHA1) not supported!\n");
+ } else {
+ // create the required object using HMAC with SHA-1, and an
+ // empty key.
+ QCA::MessageAuthenticationCode hmacObject("hmac(sha1)", QCA::SecureArray());
+
+ // create the key
+ QCA::SymmetricKey keyObject(key);
+
+ // set the HMAC object to use the key
+ hmacObject.setup(key);
+ // that could also have been done in the
+ // QCA::MessageAuthenticationCode constructor
+
+ // we split it into two parts to show incremental update
+ QCA::SecureArray part1(arg.left(3)); // three chars - "hel"
+ QCA::SecureArray part2(arg.mid(3)); // the rest - "lo"
+ hmacObject.update(part1);
+ hmacObject.update(part2);
+
+ // no more updates after calling final.
+ QCA::SecureArray resultArray = hmacObject.final();
+
+ // convert the result into printable hexadecimal.
+ QString result = QCA::arrayToHex(resultArray.toByteArray());
+ printf("HMAC(SHA1) of \"%s\" with \"%s\" = [%s]\n", arg.data(), key.data(), result.toLatin1().data());
+ }
+
+ return 0;
}
diff --git a/examples/md5crypt/md5crypt.cpp b/examples/md5crypt/md5crypt.cpp
index 80d3f60f..ab6bcec5 100644
--- a/examples/md5crypt/md5crypt.cpp
+++ b/examples/md5crypt/md5crypt.cpp
@@ -1,225 +1,204 @@
/*
Copyright (C) 2007 Carlo Todeschini - Metarete s.r.l. <info@metarete.it>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
Algorithm inspired by Vladimir Silva's "Secure Java apps on Linux using
MD5 crypt" article
(http://www-128.ibm.com/developerworks/linux/library/l-md5crypt/)
*/
#include <QtCrypto>
#include <QCoreApplication>
#include <QtDebug>
#include <stdio.h>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
-QString to64 ( long v , int size )
+QString to64(long v, int size)
{
// Character set of the encrypted password: A-Za-z0-9./
QString itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
QString result;
- while ( --size >= 0 )
- {
- result.append ( itoa64.at ( ( int )( v & 0x3f ) ) );
+ while (--size >= 0) {
+ result.append(itoa64.at((int)(v & 0x3f)));
v = v >> 6;
}
return result;
}
-
-int byte2unsigned ( int byteValue )
+int byte2unsigned(int byteValue)
{
int integerToReturn;
integerToReturn = (int) byteValue & 0xff;
return integerToReturn;
}
-QString qca_md5crypt( const QCA::SecureArray &password, const QCA::SecureArray &salt )
+QString qca_md5crypt(const QCA::SecureArray &password, const QCA::SecureArray &salt)
{
QCA::SecureArray finalState, magic_string = "$1$";
// The md5crypt algorithm uses two separate hashes
- QCA::Hash hash1( "md5" );
- QCA::Hash hash2( "md5" );
+ QCA::Hash hash1("md5");
+ QCA::Hash hash2("md5");
// MD5 Hash #1: pwd, magic string and salt
- hash1.update ( password );
- hash1.update ( magic_string );
- hash1.update ( salt );
+ hash1.update(password);
+ hash1.update(magic_string);
+ hash1.update(salt);
// MD5 Hash #2: password, salt, password
- hash2.update ( password );
- hash2.update ( salt );
- hash2.update ( password );
+ hash2.update(password);
+ hash2.update(salt);
+ hash2.update(password);
finalState = hash2.final();
// Two sets of transformations based on the length of the password
- for ( int i = password.size() ; i > 0 ; i -= 16 )
- {
+ for (int i = password.size() ; i > 0 ; i -= 16) {
// Update hash1 from offset value (i > 16 ? 16 : i)
- hash1.update( finalState.toByteArray().left(i > 16 ? 16 : i));
+ hash1.update(finalState.toByteArray().left(i > 16 ? 16 : i));
}
// Clear array bits
- finalState.fill( 0 );
+ finalState.fill(0);
- for ( int i = password.size() ; i != 0 ; i = i >> 1 )
- {
- if ( ( i & 1 ) != 0 )
- {
- hash1.update( finalState.toByteArray().left ( 1 ) );
- }
- else
- {
- hash1.update( password.toByteArray().left ( 1 ) );
+ for (int i = password.size() ; i != 0 ; i = i >> 1) {
+ if ((i & 1) != 0) {
+ hash1.update(finalState.toByteArray().left(1));
+ } else {
+ hash1.update(password.toByteArray().left(1));
}
}
finalState = hash1.final();
// Now build a 1000 entry dictionary...
- for ( int i = 0 ; i < 1000 ; i++ )
- {
+ for (int i = 0 ; i < 1000 ; i++) {
hash2.clear();
- if ((i & 1) != 0)
- {
- hash2.update ( password );
- }
- else
- {
- hash2.update ( finalState.toByteArray().left( 16 ));
+ if ((i & 1) != 0) {
+ hash2.update(password);
+ } else {
+ hash2.update(finalState.toByteArray().left(16));
}
- if ((i % 3) != 0)
- {
- hash2.update ( salt );
+ if ((i % 3) != 0) {
+ hash2.update(salt);
}
- if ((i % 7) != 0)
- {
- hash2.update ( password );
+ if ((i % 7) != 0) {
+ hash2.update(password);
}
- if ((i & 1) != 0)
- {
- hash2.update ( finalState.toByteArray().left( 16 ) );
- }
- else
- {
- hash2.update ( password );
+ if ((i & 1) != 0) {
+ hash2.update(finalState.toByteArray().left(16));
+ } else {
+ hash2.update(password);
}
finalState = hash2.final();
}
// Create an output string
// Salt is part of the encoded password ($1$<string>$)
QString encodedString;
- encodedString.append ( magic_string.toByteArray() );
- encodedString.append ( salt.toByteArray() );
- encodedString.append ( "$" );
+ encodedString.append(magic_string.toByteArray());
+ encodedString.append(salt.toByteArray());
+ encodedString.append("$");
long l;
- l = ( byte2unsigned (finalState.toByteArray().at(0) ) << 16 |
- ( byte2unsigned (finalState.toByteArray().at(6)) ) << 8 |
- byte2unsigned (finalState.toByteArray().at(12)) );
- encodedString.append ( to64 (l, 4) );
+ l = (byte2unsigned(finalState.toByteArray().at(0)) << 16 |
+ (byte2unsigned(finalState.toByteArray().at(6))) << 8 |
+ byte2unsigned(finalState.toByteArray().at(12)));
+ encodedString.append(to64(l, 4));
- l = ( byte2unsigned (finalState.toByteArray().at(1)) << 16 |
- ( byte2unsigned (finalState.toByteArray().at(7))) << 8 |
- byte2unsigned (finalState.toByteArray().at(13)) );
- encodedString.append ( to64 (l, 4) );
+ l = (byte2unsigned(finalState.toByteArray().at(1)) << 16 |
+ (byte2unsigned(finalState.toByteArray().at(7))) << 8 |
+ byte2unsigned(finalState.toByteArray().at(13)));
+ encodedString.append(to64(l, 4));
- l = ( byte2unsigned (finalState.toByteArray().at(2)) << 16 |
- ( byte2unsigned (finalState.toByteArray().at(8))) << 8 |
- byte2unsigned (finalState.toByteArray().at(14)) );
- encodedString.append ( to64 (l, 4) );
+ l = (byte2unsigned(finalState.toByteArray().at(2)) << 16 |
+ (byte2unsigned(finalState.toByteArray().at(8))) << 8 |
+ byte2unsigned(finalState.toByteArray().at(14)));
+ encodedString.append(to64(l, 4));
- l = ( byte2unsigned (finalState.toByteArray().at(3)) << 16 |
- ( byte2unsigned (finalState.toByteArray().at(9))) << 8 |
- byte2unsigned (finalState.toByteArray().at(15)) );
- encodedString.append ( to64 (l, 4) );
+ l = (byte2unsigned(finalState.toByteArray().at(3)) << 16 |
+ (byte2unsigned(finalState.toByteArray().at(9))) << 8 |
+ byte2unsigned(finalState.toByteArray().at(15)));
+ encodedString.append(to64(l, 4));
- l = ( byte2unsigned (finalState.toByteArray().at(4)) << 16 |
- ( byte2unsigned (finalState.toByteArray().at(10))) << 8 |
- byte2unsigned (finalState.toByteArray().at(5)) );
- encodedString.append ( to64 (l, 4) );
+ l = (byte2unsigned(finalState.toByteArray().at(4)) << 16 |
+ (byte2unsigned(finalState.toByteArray().at(10))) << 8 |
+ byte2unsigned(finalState.toByteArray().at(5)));
+ encodedString.append(to64(l, 4));
- l = byte2unsigned (finalState.toByteArray().at(11));
- encodedString.append ( to64 (l, 2) );
+ l = byte2unsigned(finalState.toByteArray().at(11));
+ encodedString.append(to64(l, 2));
return encodedString;
}
int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
- QCoreApplication app ( argc, argv );
+ QCoreApplication app(argc, argv);
QCA::SecureArray password, salt;
- if ( argc < 3 )
- {
- printf ( "Usage: %s password salt (salt without $1$)\n" , argv[0] );
+ if (argc < 3) {
+ printf("Usage: %s password salt (salt without $1$)\n", argv[0]);
return 1;
}
- password.append( argv[1] );
+ password.append(argv[1]);
- salt.append( argv[2] );
+ salt.append(argv[2]);
// must always check that an algorithm is supported before using it
- if( !QCA::isSupported( "md5" ) )
- printf ("MD5 hash not supported!\n");
- else
- {
- QString result = qca_md5crypt( password, salt );
+ if (!QCA::isSupported("md5")) {
+ printf("MD5 hash not supported!\n");
+ } else {
+ QString result = qca_md5crypt(password, salt);
- printf ("md5crypt [ %s , %s ] = '%s'\n" , password.data(), salt.data() , qPrintable(result) );
+ printf("md5crypt [ %s , %s ] = '%s'\n", password.data(), salt.data(), qPrintable(result));
// this is equivalent if you have GNU libc 2.0
// printf( "GNU md5crypt [ %s , %s ] = '%s'\n", password.data(), salt.data(), crypt( password.data(), ( "$1$"+salt ).data() ) );
}
return 0;
}
-
-
-
diff --git a/examples/providertest/providertest.cpp b/examples/providertest/providertest.cpp
index 9d5def3d..4d7b02bb 100644
--- a/examples/providertest/providertest.cpp
+++ b/examples/providertest/providertest.cpp
@@ -1,67 +1,67 @@
/*
Copyright (C) 2004 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <iostream>
#include <qstringlist.h>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication app(argc, argv);
// get all the available providers loaded.
// you don't normally need this (because you test using isSupported())
// but this is a special case.
QCA::scanForPlugins();
// this gives us all the plugin providers as a list
QCA::ProviderList qcaProviders = QCA::providers();
for (int i = 0; i < qcaProviders.size(); ++i) {
- // each provider has a name, which we can display
+ // each provider has a name, which we can display
std::cout << qcaProviders[i]->name().toLatin1().data() << ": ";
- // ... and also a list of features
- QStringList capabilities = qcaProviders[i]->features();
- // we turn the string list back into a single string,
- // and display it as well
- std::cout << capabilities.join(", ").toLatin1().data() << std::endl;
+ // ... and also a list of features
+ QStringList capabilities = qcaProviders[i]->features();
+ // we turn the string list back into a single string,
+ // and display it as well
+ std::cout << capabilities.join(", ").toLatin1().data() << std::endl;
}
// Note that the default provider isn't included in
// the result of QCA::providers()
std::cout << "default: ";
// However it is still possible to get the features
// supported by the default provider
QStringList capabilities = QCA::defaultFeatures();
std::cout << capabilities.join(", ").toLatin1().data() << std::endl;
return 0;
}
diff --git a/examples/publickeyexample/publickeyexample.cpp b/examples/publickeyexample/publickeyexample.cpp
index 7a58db2f..fb508487 100644
--- a/examples/publickeyexample/publickeyexample.cpp
+++ b/examples/publickeyexample/publickeyexample.cpp
@@ -1,117 +1,115 @@
/*
Copyright (C) 2003 Justin Karneges <justin@affinix.com>
Copyright (C) 2005 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
-
#include <QtCrypto>
#include <QCoreApplication>
#include <iostream>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
-int main(int argc, char** argv)
+int main(int argc, char **argv)
{
// the Initializer object sets things up, and
// also does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication app(argc, argv);
// We need to ensure that we have certificate handling support
- if ( !QCA::isSupported( "cert" ) ) {
- std::cout << "Sorry, no PKI certificate support" << std::endl;
- return 1;
+ if (!QCA::isSupported("cert")) {
+ std::cout << "Sorry, no PKI certificate support" << std::endl;
+ return 1;
}
// Read in a private key
QCA::PrivateKey privKey;
QCA::ConvertResult convRes;
QCA::SecureArray passPhrase = "start";
- privKey = QCA::PrivateKey::fromPEMFile( "Userkey.pem", passPhrase, &convRes );
- if ( convRes != QCA::ConvertGood ) {
- std::cout << "Sorry, could not import Private Key" << std::endl;
- return 1;
+ privKey = QCA::PrivateKey::fromPEMFile("Userkey.pem", passPhrase, &convRes);
+ if (convRes != QCA::ConvertGood) {
+ std::cout << "Sorry, could not import Private Key" << std::endl;
+ return 1;
}
// Read in a matching public key cert
// you could also build this using the fromPEMFile() method
- QCA::Certificate pubCert( "User.pem" );
- if ( pubCert.isNull() ) {
- std::cout << "Sorry, could not import public key certificate" << std::endl;
- return 1;
+ QCA::Certificate pubCert("User.pem");
+ if (pubCert.isNull()) {
+ std::cout << "Sorry, could not import public key certificate" << std::endl;
+ return 1;
}
// We are building the certificate into a SecureMessageKey object, via a
// CertificateChain
QCA::SecureMessageKey secMsgKey;
QCA::CertificateChain chain;
chain += pubCert;
- secMsgKey.setX509CertificateChain( chain );
+ secMsgKey.setX509CertificateChain(chain);
// build up a SecureMessage object, based on our public key certificate
QCA::CMS cms;
QCA::SecureMessage msg(&cms);
msg.setRecipient(secMsgKey);
// Some plain text - we use the first command line argument if provided
QByteArray plainText = (argc >= 2) ? argv[1] : "What do ya want for nuthin'";
// Now use the SecureMessage object to encrypt the plain text.
msg.startEncrypt();
msg.update(plainText);
msg.end();
// I think it is reasonable to wait for 1 second for this
msg.waitForFinished(1000);
// check to see if it worked
- if(!msg.success())
- {
- std::cout << "Error encrypting: " << msg.errorCode() << std::endl;
- return 1;
+ if (!msg.success()) {
+ std::cout << "Error encrypting: " << msg.errorCode() << std::endl;
+ return 1;
}
// get the result
QCA::SecureArray cipherText = msg.read();
QCA::Base64 enc;
std::cout << plainText.data() << " encrypts to (in base 64): ";
- std::cout << qPrintable( enc.arrayToString( cipherText ) ) << std::endl;
+ std::cout << qPrintable(enc.arrayToString(cipherText)) << std::endl;
// Show we can decrypt it with the private key
- if ( !privKey.canDecrypt() ) {
- std::cout << "Private key cannot be used to decrypt" << std::endl;
- return 1;
+ if (!privKey.canDecrypt()) {
+ std::cout << "Private key cannot be used to decrypt" << std::endl;
+ return 1;
}
QCA::SecureArray plainTextResult;
- if ( 0 == privKey.decrypt(cipherText, &plainTextResult, QCA::EME_PKCS1_OAEP ) ) {
- std::cout << "Decryption process failed" << std::endl;
- return 1;
+ if (0 == privKey.decrypt(cipherText, &plainTextResult, QCA::EME_PKCS1_OAEP)) {
+ std::cout << "Decryption process failed" << std::endl;
+ return 1;
}
- std::cout << qPrintable( enc.arrayToString( cipherText ) );
+ std::cout << qPrintable(enc.arrayToString(cipherText));
std::cout << " (in base 64) decrypts to: ";
std::cout << plainTextResult.data() << std::endl;
return 0;
}
diff --git a/examples/randomtest/randomtest.cpp b/examples/randomtest/randomtest.cpp
index c9dbed5d..aa79ae32 100644
--- a/examples/randomtest/randomtest.cpp
+++ b/examples/randomtest/randomtest.cpp
@@ -1,73 +1,73 @@
/*
Copyright (C) 2004, 2006 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#include <QCoreApplication>
#include <QDebug>
#include <iostream>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
- // the Initializer object sets things up, and
- // also does cleanup when it goes out of scope
- QCA::Initializer init;
-
- QCoreApplication app(argc, argv);
-
- qDebug() << "This example generates random numbers";
-
- int randInt;
- // This is the standard way to generate a random integer.
- randInt = QCA::Random::randomInt();
- qDebug() << "A random number: " << randInt;
-
- // If you wanted a random character (octet), you could
- // use something like:
- unsigned char randChar;
- randChar = QCA::Random::randomChar();
- // It might not be printable, so this may not produce output
- std::cout << "A random character: " << randChar << std::endl;
-
- QCA::SecureArray tenBytes(10);
- // If you need more random values, you may want to
- // get an array, as shown below.
- tenBytes = QCA::Random::randomArray(10);
-
- // To make this viewable, we convert to hexadecimal.
- std::cout << "A random 10 byte array (in hex): ";
- std::cout << qPrintable(QCA::Hex().arrayToString(tenBytes)) << std::endl;
-
- // Under some circumstances, you may want to create a
- // Random object, rather than a static public member function.
- // This isn't normally the easiest way, but it does work
- QCA::Random myRandomObject;
- randChar = myRandomObject.nextByte();
- tenBytes = myRandomObject.nextBytes(10);
- return 0;
+ // the Initializer object sets things up, and
+ // also does cleanup when it goes out of scope
+ QCA::Initializer init;
+
+ QCoreApplication app(argc, argv);
+
+ qDebug() << "This example generates random numbers";
+
+ int randInt;
+ // This is the standard way to generate a random integer.
+ randInt = QCA::Random::randomInt();
+ qDebug() << "A random number: " << randInt;
+
+ // If you wanted a random character (octet), you could
+ // use something like:
+ unsigned char randChar;
+ randChar = QCA::Random::randomChar();
+ // It might not be printable, so this may not produce output
+ std::cout << "A random character: " << randChar << std::endl;
+
+ QCA::SecureArray tenBytes(10);
+ // If you need more random values, you may want to
+ // get an array, as shown below.
+ tenBytes = QCA::Random::randomArray(10);
+
+ // To make this viewable, we convert to hexadecimal.
+ std::cout << "A random 10 byte array (in hex): ";
+ std::cout << qPrintable(QCA::Hex().arrayToString(tenBytes)) << std::endl;
+
+ // Under some circumstances, you may want to create a
+ // Random object, rather than a static public member function.
+ // This isn't normally the easiest way, but it does work
+ QCA::Random myRandomObject;
+ randChar = myRandomObject.nextByte();
+ tenBytes = myRandomObject.nextBytes(10);
+ return 0;
}
diff --git a/examples/rsatest/rsatest.cpp b/examples/rsatest/rsatest.cpp
index b47f2921..ca9e050e 100644
--- a/examples/rsatest/rsatest.cpp
+++ b/examples/rsatest/rsatest.cpp
@@ -1,157 +1,156 @@
/*
Copyright (C) 2003 Justin Karneges <justin@affinix.com>
Copyright (C) 2005 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <QtCrypto>
#include <QCoreApplication>
#include <iostream>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
int main(int argc, char **argv)
{
// The Initializer object sets things up, and also
// does cleanup when it goes out of scope
QCA::Initializer init;
QCoreApplication app(argc, argv);
// we use the first argument if provided, or
// use "hello" if no arguments
QCA::SecureArray arg = (argc >= 2) ? argv[1] : "hello";
// We demonstrate PEM usage here, so we need to test for
// supportedIOTypes, not just supportedTypes
- if(!QCA::isSupported("pkey") ||
- !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA))
- std::cout << "RSA not supported!\n";
- else {
- // When creating a public / private key pair, you make the
- // private key, and then extract the public key component from it
- // Using RSA is very common, however DSA can provide equivalent
- // signature/verification. This example applies to DSA to the
- // extent that the operations work on that key type.
-
- // QCA provides KeyGenerator as a convenient source of new keys,
- // however you could also import an existing key instead.
- QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024);
- if(seckey.isNull()) {
- std::cout << "Failed to make private RSA key" << std::endl;
- return 1;
- }
-
- QCA::PublicKey pubkey = seckey.toPublicKey();
-
- // check if the key can encrypt
- if(!pubkey.canEncrypt()) {
- std::cout << "Error: this kind of key cannot encrypt" << std::endl;
- return 1;
- }
-
- // encrypt some data - note that only the public key is required
- // you must also choose the algorithm to be used
- QCA::SecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP);
- if(result.isEmpty()) {
- std::cout << "Error encrypting" << std::endl;
- return 1;
- }
-
- // output the encrypted data
- QString rstr = QCA::arrayToHex(result.toByteArray());
- std::cout << "\"" << arg.data() << "\" encrypted with RSA is \"";
- std::cout << qPrintable(rstr) << "\"" << std::endl;
-
- // save the private key - in a real example, make sure this goes
- // somewhere secure and has a good pass phrase
- // You can use the same technique with the public key too.
- QCA::SecureArray passPhrase = "pass phrase";
- seckey.toPEMFile("keyprivate.pem", passPhrase);
-
- // Read that key back in, checking if the read succeeded
- QCA::ConvertResult conversionResult;
- QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile( "keyprivate.pem",
- passPhrase,
- &conversionResult);
- if (! (QCA::ConvertGood == conversionResult) ) {
- std::cout << "Private key read failed" << std::endl;
- }
-
- // now decrypt that encrypted data using the private key that
- // we read in. The algorithm is the same.
- QCA::SecureArray decrypt;
- if(0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) {
- std::cout << "Error decrypting.\n";
- return 1;
- }
-
- // output the resulting decrypted string
- std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \"";
- std::cout << decrypt.data() << "\"" << std::endl;
-
-
- // Some private keys can also be used for producing signatures
- if(!privateKey.canSign()) {
- std::cout << "Error: this kind of key cannot sign" << std::endl;
- return 1;
- }
- privateKey.startSign( QCA::EMSA3_MD5 );
- privateKey.update( arg ); // just reuse the same message
- QByteArray argSig = privateKey.signature();
-
- // instead of using the startSign(), update(), signature() calls,
- // you may be better doing the whole thing in one go, using the
- // signMessage call. Of course you need the whole message in one
- // hit, which may or may not be a problem
-
- // output the resulting signature
- rstr = QCA::arrayToHex(argSig);
- std::cout << "Signature for \"" << arg.data() << "\" using RSA, is ";
- std::cout << "\"" << qPrintable( rstr ) << "\"" << std::endl;
-
- // to check a signature, we must check that the key is
- // appropriate
- if(pubkey.canVerify()) {
- pubkey.startVerify( QCA::EMSA3_MD5 );
- pubkey.update( arg );
- if ( pubkey.validSignature( argSig ) ) {
- std::cout << "Signature is valid" << std::endl;
- } else {
- std::cout << "Bad signature" << std::endl;
- }
- }
-
- // We can also do the verification in a single step if we
- // have all the message
- if ( pubkey.canVerify() &&
- pubkey.verifyMessage( arg, argSig, QCA::EMSA3_MD5 ) ) {
- std::cout << "Signature is valid" << std::endl;
- } else {
- std::cout << "Signature could not be verified" << std::endl;
- }
+ if (!QCA::isSupported("pkey") ||
+ !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA)) {
+ std::cout << "RSA not supported!\n";
+ } else {
+ // When creating a public / private key pair, you make the
+ // private key, and then extract the public key component from it
+ // Using RSA is very common, however DSA can provide equivalent
+ // signature/verification. This example applies to DSA to the
+ // extent that the operations work on that key type.
+
+ // QCA provides KeyGenerator as a convenient source of new keys,
+ // however you could also import an existing key instead.
+ QCA::PrivateKey seckey = QCA::KeyGenerator().createRSA(1024);
+ if (seckey.isNull()) {
+ std::cout << "Failed to make private RSA key" << std::endl;
+ return 1;
+ }
+
+ QCA::PublicKey pubkey = seckey.toPublicKey();
+
+ // check if the key can encrypt
+ if (!pubkey.canEncrypt()) {
+ std::cout << "Error: this kind of key cannot encrypt" << std::endl;
+ return 1;
+ }
+
+ // encrypt some data - note that only the public key is required
+ // you must also choose the algorithm to be used
+ QCA::SecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP);
+ if (result.isEmpty()) {
+ std::cout << "Error encrypting" << std::endl;
+ return 1;
+ }
+
+ // output the encrypted data
+ QString rstr = QCA::arrayToHex(result.toByteArray());
+ std::cout << "\"" << arg.data() << "\" encrypted with RSA is \"";
+ std::cout << qPrintable(rstr) << "\"" << std::endl;
+
+ // save the private key - in a real example, make sure this goes
+ // somewhere secure and has a good pass phrase
+ // You can use the same technique with the public key too.
+ QCA::SecureArray passPhrase = "pass phrase";
+ seckey.toPEMFile("keyprivate.pem", passPhrase);
+
+ // Read that key back in, checking if the read succeeded
+ QCA::ConvertResult conversionResult;
+ QCA::PrivateKey privateKey = QCA::PrivateKey::fromPEMFile("keyprivate.pem",
+ passPhrase,
+ &conversionResult);
+ if (!(QCA::ConvertGood == conversionResult)) {
+ std::cout << "Private key read failed" << std::endl;
+ }
+
+ // now decrypt that encrypted data using the private key that
+ // we read in. The algorithm is the same.
+ QCA::SecureArray decrypt;
+ if (0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) {
+ std::cout << "Error decrypting.\n";
+ return 1;
+ }
+
+ // output the resulting decrypted string
+ std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \"";
+ std::cout << decrypt.data() << "\"" << std::endl;
+
+ // Some private keys can also be used for producing signatures
+ if (!privateKey.canSign()) {
+ std::cout << "Error: this kind of key cannot sign" << std::endl;
+ return 1;
+ }
+ privateKey.startSign(QCA::EMSA3_MD5);
+ privateKey.update(arg); // just reuse the same message
+ QByteArray argSig = privateKey.signature();
+
+ // instead of using the startSign(), update(), signature() calls,
+ // you may be better doing the whole thing in one go, using the
+ // signMessage call. Of course you need the whole message in one
+ // hit, which may or may not be a problem
+
+ // output the resulting signature
+ rstr = QCA::arrayToHex(argSig);
+ std::cout << "Signature for \"" << arg.data() << "\" using RSA, is ";
+ std::cout << "\"" << qPrintable(rstr) << "\"" << std::endl;
+
+ // to check a signature, we must check that the key is
+ // appropriate
+ if (pubkey.canVerify()) {
+ pubkey.startVerify(QCA::EMSA3_MD5);
+ pubkey.update(arg);
+ if (pubkey.validSignature(argSig)) {
+ std::cout << "Signature is valid" << std::endl;
+ } else {
+ std::cout << "Bad signature" << std::endl;
+ }
+ }
+
+ // We can also do the verification in a single step if we
+ // have all the message
+ if (pubkey.canVerify() &&
+ pubkey.verifyMessage(arg, argSig, QCA::EMSA3_MD5)) {
+ std::cout << "Signature is valid" << std::endl;
+ } else {
+ std::cout << "Signature could not be verified" << std::endl;
+ }
}
return 0;
}
diff --git a/examples/saslclient/saslclient.cpp b/examples/saslclient/saslclient.cpp
index 85f69ed1..42906870 100644
--- a/examples/saslclient/saslclient.cpp
+++ b/examples/saslclient/saslclient.cpp
@@ -1,569 +1,546 @@
/*
Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
Copyright (C) 2006 Michail Pishchagin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <QCoreApplication>
#include <QTimer>
#include <QTcpSocket>
#include <QTcpServer>
#include <stdio.h>
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
static QString prompt(const QString &s)
{
- printf("* %s ", qPrintable(s));
- fflush(stdout);
- char line[256];
- fgets(line, 255, stdin);
- QString result = line;
- if(result[result.length()-1] == '\n')
- result.truncate(result.length()-1);
- return result;
+ printf("* %s ", qPrintable(s));
+ fflush(stdout);
+ char line[256];
+ fgets(line, 255, stdin);
+ QString result = line;
+ if (result[result.length() - 1] == '\n') {
+ result.truncate(result.length() - 1);
+ }
+ return result;
}
static QString socketErrorToString(QAbstractSocket::SocketError x)
{
- QString s;
- switch(x)
- {
- case QAbstractSocket::ConnectionRefusedError:
- s = "connection refused or timed out"; break;
- case QAbstractSocket::RemoteHostClosedError:
- s = "remote host closed the connection"; break;
- case QAbstractSocket::HostNotFoundError:
- s = "host not found"; break;
- case QAbstractSocket::SocketAccessError:
- s = "access error"; break;
- case QAbstractSocket::SocketResourceError:
- s = "too many sockets"; break;
- case QAbstractSocket::SocketTimeoutError:
- s = "operation timed out"; break;
- case QAbstractSocket::DatagramTooLargeError:
- s = "datagram was larger than system limit"; break;
- case QAbstractSocket::NetworkError:
- s = "network error"; break;
- case QAbstractSocket::AddressInUseError:
- s = "address is already in use"; break;
- case QAbstractSocket::SocketAddressNotAvailableError:
- s = "address does not belong to the host"; break;
- case QAbstractSocket::UnsupportedSocketOperationError:
- s = "operation is not supported by the local operating system"; break;
- default:
- s = "unknown socket error"; break;
- }
- return s;
+ QString s;
+ switch (x) {
+ case QAbstractSocket::ConnectionRefusedError:
+ s = "connection refused or timed out"; break;
+ case QAbstractSocket::RemoteHostClosedError:
+ s = "remote host closed the connection"; break;
+ case QAbstractSocket::HostNotFoundError:
+ s = "host not found"; break;
+ case QAbstractSocket::SocketAccessError:
+ s = "access error"; break;
+ case QAbstractSocket::SocketResourceError:
+ s = "too many sockets"; break;
+ case QAbstractSocket::SocketTimeoutError:
+ s = "operation timed out"; break;
+ case QAbstractSocket::DatagramTooLargeError:
+ s = "datagram was larger than system limit"; break;
+ case QAbstractSocket::NetworkError:
+ s = "network error"; break;
+ case QAbstractSocket::AddressInUseError:
+ s = "address is already in use"; break;
+ case QAbstractSocket::SocketAddressNotAvailableError:
+ s = "address does not belong to the host"; break;
+ case QAbstractSocket::UnsupportedSocketOperationError:
+ s = "operation is not supported by the local operating system"; break;
+ default:
+ s = "unknown socket error"; break;
+ }
+ return s;
}
static QString saslAuthConditionToString(QCA::SASL::AuthCondition x)
{
- QString s;
- switch(x)
- {
- case QCA::SASL::NoMechanism:
- s = "no appropriate mechanism could be negotiated"; break;
- case QCA::SASL::BadProtocol:
- s = "bad SASL protocol"; break;
- case QCA::SASL::BadServer:
- s = "server failed mutual authentication"; break;
- // AuthFail or unknown (including those defined for server only)
- default:
- s = "generic authentication failure"; break;
- };
- return s;
+ QString s;
+ switch (x) {
+ case QCA::SASL::NoMechanism:
+ s = "no appropriate mechanism could be negotiated"; break;
+ case QCA::SASL::BadProtocol:
+ s = "bad SASL protocol"; break;
+ case QCA::SASL::BadServer:
+ s = "server failed mutual authentication"; break;
+ // AuthFail or unknown (including those defined for server only)
+ default:
+ s = "generic authentication failure"; break;
+ };
+ return s;
}
class ClientTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private:
- QString host, proto, authzid, realm, user, pass;
- int port;
- bool no_authzid, no_realm;
- int mode; // 0 = receive mechanism list, 1 = sasl negotiation, 2 = app
- QTcpSocket *sock;
- QCA::SASL *sasl;
- QByteArray inbuf;
- bool sock_done;
- int waitCycles;
+ QString host, proto, authzid, realm, user, pass;
+ int port;
+ bool no_authzid, no_realm;
+ int mode; // 0 = receive mechanism list, 1 = sasl negotiation, 2 = app
+ QTcpSocket *sock;
+ QCA::SASL *sasl;
+ QByteArray inbuf;
+ bool sock_done;
+ int waitCycles;
public:
- ClientTest(const QString &_host, int _port, const QString &_proto, const QString &_authzid, const QString &_realm, const QString &_user, const QString &_pass, bool _no_authzid, bool _no_realm) :
- host(_host),
- proto(_proto),
- authzid(_authzid),
- realm(_realm),
- user(_user),
- pass(_pass),
- port(_port),
- no_authzid(_no_authzid),
- no_realm(_no_realm),
- sock_done(false),
- waitCycles(0)
- {
- sock = new QTcpSocket(this);
- connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
- connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
- connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));
-
- sasl = new QCA::SASL(this);
- connect(sasl, SIGNAL(clientStarted(bool, const QByteArray &)), SLOT(sasl_clientFirstStep(bool, const QByteArray &)));
- connect(sasl, SIGNAL(nextStep(const QByteArray &)), SLOT(sasl_nextStep(const QByteArray &)));
- connect(sasl, SIGNAL(needParams(const QCA::SASL::Params &)), SLOT(sasl_needParams(const QCA::SASL::Params &)));
- connect(sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
- connect(sasl, SIGNAL(readyRead()), SLOT(sasl_readyRead()));
- connect(sasl, SIGNAL(readyReadOutgoing()), SLOT(sasl_readyReadOutgoing()));
- connect(sasl, SIGNAL(error()), SLOT(sasl_error()));
- }
+ ClientTest(const QString &_host, int _port, const QString &_proto, const QString &_authzid, const QString &_realm, const QString &_user, const QString &_pass, bool _no_authzid, bool _no_realm) :
+ host(_host),
+ proto(_proto),
+ authzid(_authzid),
+ realm(_realm),
+ user(_user),
+ pass(_pass),
+ port(_port),
+ no_authzid(_no_authzid),
+ no_realm(_no_realm),
+ sock_done(false),
+ waitCycles(0)
+ {
+ sock = new QTcpSocket(this);
+ connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
+ connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
+ connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));
+
+ sasl = new QCA::SASL(this);
+ connect(sasl, SIGNAL(clientStarted(bool,QByteArray)), SLOT(sasl_clientFirstStep(bool,QByteArray)));
+ connect(sasl, SIGNAL(nextStep(QByteArray)), SLOT(sasl_nextStep(QByteArray)));
+ connect(sasl, SIGNAL(needParams(QCA::SASL::Params)), SLOT(sasl_needParams(QCA::SASL::Params)));
+ connect(sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
+ connect(sasl, SIGNAL(readyRead()), SLOT(sasl_readyRead()));
+ connect(sasl, SIGNAL(readyReadOutgoing()), SLOT(sasl_readyReadOutgoing()));
+ connect(sasl, SIGNAL(error()), SLOT(sasl_error()));
+ }
public slots:
- void start()
- {
- mode = 0; // mech list mode
-
- int flags = 0;
- flags |= QCA::SASL::AllowPlain;
- flags |= QCA::SASL::AllowAnonymous;
- sasl->setConstraints((QCA::SASL::AuthFlags)flags, 0, 256);
-
- if(!user.isEmpty())
- sasl->setUsername(user);
- if(!authzid.isEmpty())
- sasl->setAuthzid(authzid);
- if(!pass.isEmpty())
- sasl->setPassword(pass.toUtf8());
- if(!realm.isEmpty())
- sasl->setRealm(realm);
-
- printf("Connecting to %s:%d, for protocol %s\n", qPrintable(host), port, qPrintable(proto));
- sock->connectToHost(host, port);
- }
+ void start()
+ {
+ mode = 0; // mech list mode
+
+ int flags = 0;
+ flags |= QCA::SASL::AllowPlain;
+ flags |= QCA::SASL::AllowAnonymous;
+ sasl->setConstraints((QCA::SASL::AuthFlags)flags, 0, 256);
+
+ if (!user.isEmpty()) {
+ sasl->setUsername(user);
+ }
+ if (!authzid.isEmpty()) {
+ sasl->setAuthzid(authzid);
+ }
+ if (!pass.isEmpty()) {
+ sasl->setPassword(pass.toUtf8());
+ }
+ if (!realm.isEmpty()) {
+ sasl->setRealm(realm);
+ }
+
+ printf("Connecting to %s:%d, for protocol %s\n", qPrintable(host), port, qPrintable(proto));
+ sock->connectToHost(host, port);
+ }
signals:
- void quit();
+ void quit();
private slots:
- void sock_connected()
- {
- printf("Connected to server. Awaiting mechanism list...\n");
- }
-
- void sock_error(QAbstractSocket::SocketError x)
- {
- if(x == QAbstractSocket::RemoteHostClosedError)
- {
- if(mode == 2) // app mode, where disconnect means completion
- {
- sock_done = true;
- tryFinished();
- return;
- }
- else // any other mode, where disconnect is an error
- {
- printf("Error: server closed connection unexpectedly.\n");
- emit quit();
- return;
- }
- }
-
- printf("Error: socket: %s\n", qPrintable(socketErrorToString(x)));
- emit quit();
- }
-
- void sock_readyRead()
- {
- if(mode == 2) // app mode
- {
- QByteArray a = sock->readAll();
- printf("Read %d bytes\n", a.size());
-
- // there is a possible flaw in the qca 2.0 api, in
- // that if sasl data is received from the peer
- // followed by a disconnect from the peer, there is
- // no clear approach to salvaging the bytes. tls is
- // not affected because tls has the concept of
- // closing a session. with sasl, there is no
- // closing, and since the qca api is asynchronous,
- // we could potentially wait forever for decoded
- // data, if the last write was a partial packet.
- //
- // for now, we can perform a simple workaround of
- // waiting at least three event loop cycles for
- // decoded data before giving up and assuming the
- // last write was partial. the fact is, all current
- // qca sasl providers respond within this time
- // frame, so this fix should work fine for now. in
- // qca 2.1, we should revise the api to handle this
- // situation better.
- //
- // further note: i guess this only affects application
- // protocols that have no close message of their
- // own, and rely on the tcp-level close. examples
- // are http, and of course this qcatest protocol.
- if(waitCycles == 0)
- {
- waitCycles = 3;
- QMetaObject::invokeMethod(this, "waitWriteIncoming", Qt::QueuedConnection);
- }
-
- sasl->writeIncoming(a);
- }
- else // mech list or sasl negotiation mode
- {
- if(sock->canReadLine())
- {
- QString line = sock->readLine();
- line.truncate(line.length() - 1); // chop the newline
- handleLine(line);
- }
- }
- }
-
- void sasl_clientFirstStep(bool clientInit, const QByteArray &clientInitData)
- {
- printf("Choosing mech: %s\n", qPrintable(sasl->mechanism()));
- QString line = sasl->mechanism();
- if(clientInit)
- {
- line += ' ';
- line += arrayToString(clientInitData);
- }
- sendLine(line);
- }
-
- void sasl_nextStep(const QByteArray &stepData)
- {
- QString line = "C";
- if(!stepData.isEmpty())
- {
- line += ',';
- line += arrayToString(stepData);
- }
- sendLine(line);
- }
-
- void sasl_needParams(const QCA::SASL::Params &params)
- {
- if(params.needUsername())
- {
- user = prompt("Username:");
- sasl->setUsername(user);
- }
-
- if(params.canSendAuthzid() && !no_authzid)
- {
- authzid = prompt("Authorize As (enter to skip):");
- if(!authzid.isEmpty())
- sasl->setAuthzid(authzid);
- }
-
- if(params.needPassword())
- {
- QCA::ConsolePrompt prompt;
- prompt.getHidden("* Password");
- prompt.waitForFinished();
- QCA::SecureArray pass = prompt.result();
- sasl->setPassword(pass);
- }
-
- if(params.canSendRealm() && !no_realm)
- {
- QStringList realms = sasl->realmList();
- printf("Available realms:\n");
- if(realms.isEmpty())
- printf(" (none specified)\n");
- foreach(const QString &s, realms)
- printf(" %s\n", qPrintable(s));
- realm = prompt("Realm (enter to skip):");
- if(!realm.isEmpty())
- sasl->setRealm(realm);
- }
-
- sasl->continueAfterParams();
- }
-
- void sasl_authenticated()
- {
- printf("SASL success!\n");
- printf("SSF: %d\n", sasl->ssf());
- }
-
- void sasl_readyRead()
- {
- QByteArray a = sasl->read();
- inbuf += a;
- processInbuf();
- }
-
- void sasl_readyReadOutgoing()
- {
- QByteArray a = sasl->readOutgoing();
- sock->write(a);
- }
-
- void sasl_error()
- {
- int e = sasl->errorCode();
- if(e == QCA::SASL::ErrorInit)
- printf("Error: sasl: initialization failed.\n");
- else if(e == QCA::SASL::ErrorHandshake)
- printf("Error: sasl: %s.\n", qPrintable(saslAuthConditionToString(sasl->authCondition())));
- else if(e == QCA::SASL::ErrorCrypt)
- printf("Error: sasl: broken security layer.\n");
- else
- printf("Error: sasl: unknown error.\n");
-
- emit quit();
- }
-
- void waitWriteIncoming()
- {
- --waitCycles;
- if(waitCycles > 0)
- {
- QMetaObject::invokeMethod(this, "waitWriteIncoming", Qt::QueuedConnection);
- return;
- }
-
- tryFinished();
- }
+ void sock_connected()
+ {
+ printf("Connected to server. Awaiting mechanism list...\n");
+ }
+
+ void sock_error(QAbstractSocket::SocketError x)
+ {
+ if (x == QAbstractSocket::RemoteHostClosedError) {
+ if (mode == 2) { // app mode, where disconnect means completion
+ sock_done = true;
+ tryFinished();
+ return;
+ } else { // any other mode, where disconnect is an error
+ printf("Error: server closed connection unexpectedly.\n");
+ emit quit();
+ return;
+ }
+ }
+
+ printf("Error: socket: %s\n", qPrintable(socketErrorToString(x)));
+ emit quit();
+ }
+
+ void sock_readyRead()
+ {
+ if (mode == 2) { // app mode
+ QByteArray a = sock->readAll();
+ printf("Read %d bytes\n", a.size());
+
+ // there is a possible flaw in the qca 2.0 api, in
+ // that if sasl data is received from the peer
+ // followed by a disconnect from the peer, there is
+ // no clear approach to salvaging the bytes. tls is
+ // not affected because tls has the concept of
+ // closing a session. with sasl, there is no
+ // closing, and since the qca api is asynchronous,
+ // we could potentially wait forever for decoded
+ // data, if the last write was a partial packet.
+ //
+ // for now, we can perform a simple workaround of
+ // waiting at least three event loop cycles for
+ // decoded data before giving up and assuming the
+ // last write was partial. the fact is, all current
+ // qca sasl providers respond within this time
+ // frame, so this fix should work fine for now. in
+ // qca 2.1, we should revise the api to handle this
+ // situation better.
+ //
+ // further note: i guess this only affects application
+ // protocols that have no close message of their
+ // own, and rely on the tcp-level close. examples
+ // are http, and of course this qcatest protocol.
+ if (waitCycles == 0) {
+ waitCycles = 3;
+ QMetaObject::invokeMethod(this, "waitWriteIncoming", Qt::QueuedConnection);
+ }
+
+ sasl->writeIncoming(a);
+ } else { // mech list or sasl negotiation mode
+ if (sock->canReadLine()) {
+ QString line = sock->readLine();
+ line.truncate(line.length() - 1); // chop the newline
+ handleLine(line);
+ }
+ }
+ }
+
+ void sasl_clientFirstStep(bool clientInit, const QByteArray &clientInitData)
+ {
+ printf("Choosing mech: %s\n", qPrintable(sasl->mechanism()));
+ QString line = sasl->mechanism();
+ if (clientInit) {
+ line += ' ';
+ line += arrayToString(clientInitData);
+ }
+ sendLine(line);
+ }
+
+ void sasl_nextStep(const QByteArray &stepData)
+ {
+ QString line = "C";
+ if (!stepData.isEmpty()) {
+ line += ',';
+ line += arrayToString(stepData);
+ }
+ sendLine(line);
+ }
+
+ void sasl_needParams(const QCA::SASL::Params &params)
+ {
+ if (params.needUsername()) {
+ user = prompt("Username:");
+ sasl->setUsername(user);
+ }
+
+ if (params.canSendAuthzid() && !no_authzid) {
+ authzid = prompt("Authorize As (enter to skip):");
+ if (!authzid.isEmpty()) {
+ sasl->setAuthzid(authzid);
+ }
+ }
+
+ if (params.needPassword()) {
+ QCA::ConsolePrompt prompt;
+ prompt.getHidden("* Password");
+ prompt.waitForFinished();
+ QCA::SecureArray pass = prompt.result();
+ sasl->setPassword(pass);
+ }
+
+ if (params.canSendRealm() && !no_realm) {
+ QStringList realms = sasl->realmList();
+ printf("Available realms:\n");
+ if (realms.isEmpty()) {
+ printf(" (none specified)\n");
+ }
+ foreach (const QString &s, realms) {
+ printf(" %s\n", qPrintable(s));
+ }
+ realm = prompt("Realm (enter to skip):");
+ if (!realm.isEmpty()) {
+ sasl->setRealm(realm);
+ }
+ }
+
+ sasl->continueAfterParams();
+ }
+
+ void sasl_authenticated()
+ {
+ printf("SASL success!\n");
+ printf("SSF: %d\n", sasl->ssf());
+ }
+
+ void sasl_readyRead()
+ {
+ QByteArray a = sasl->read();
+ inbuf += a;
+ processInbuf();
+ }
+
+ void sasl_readyReadOutgoing()
+ {
+ QByteArray a = sasl->readOutgoing();
+ sock->write(a);
+ }
+
+ void sasl_error()
+ {
+ int e = sasl->errorCode();
+ if (e == QCA::SASL::ErrorInit) {
+ printf("Error: sasl: initialization failed.\n");
+ } else if (e == QCA::SASL::ErrorHandshake) {
+ printf("Error: sasl: %s.\n", qPrintable(saslAuthConditionToString(sasl->authCondition())));
+ } else if (e == QCA::SASL::ErrorCrypt) {
+ printf("Error: sasl: broken security layer.\n");
+ } else {
+ printf("Error: sasl: unknown error.\n");
+ }
+
+ emit quit();
+ }
+
+ void waitWriteIncoming()
+ {
+ --waitCycles;
+ if (waitCycles > 0) {
+ QMetaObject::invokeMethod(this, "waitWriteIncoming", Qt::QueuedConnection);
+ return;
+ }
+
+ tryFinished();
+ }
private:
- void tryFinished()
- {
- if(sock_done && waitCycles == 0)
- {
- printf("Finished, server closed connection.\n");
-
- // if we give up on waiting for a response to
- // writeIncoming, then it might come late. in
- // theory this shouldn't happen if we wait enough
- // cycles, but if one were to arrive then it could
- // occur between the request to quit the app and
- // the actual quit of the app. to assist with
- // debugging, then, we'll explicitly stop listening
- // for signals here. otherwise the response may
- // still be received and displayed, giving a false
- // sense of correctness.
- sasl->disconnect(this);
-
- emit quit();
- }
- }
-
- QString arrayToString(const QByteArray &ba)
- {
- return QCA::Base64().arrayToString(ba);
- }
-
- QByteArray stringToArray(const QString &s)
- {
- return QCA::Base64().stringToArray(s).toByteArray();
- }
-
- void sendLine(const QString &line)
- {
- printf("Writing: {%s}\n", qPrintable(line));
- QString s = line + '\n';
- QByteArray a = s.toUtf8();
- if(mode == 2) // app mode
- sasl->write(a); // write to sasl
- else // mech list or sasl negotiation
- sock->write(a); // write to socket
- }
-
- void processInbuf()
- {
- // collect completed lines from inbuf
- QStringList list;
- int at;
- while((at = inbuf.indexOf('\n')) != -1)
- {
- list += QString::fromUtf8(inbuf.mid(0, at));
- inbuf = inbuf.mid(at + 1);
- }
-
- // process the lines
- foreach(const QString &line, list)
- handleLine(line);
- }
-
- void handleLine(const QString &line)
- {
- printf("Reading: [%s]\n", qPrintable(line));
- if(mode == 0)
- {
- // first line is the method list
- QStringList mechlist = line.split(' ');
- mode = 1; // switch to sasl negotiation mode
- sasl->startClient(proto, host, mechlist);
- }
- else if(mode == 1)
- {
- QString type, rest;
- int n = line.indexOf(',');
- if(n != -1)
- {
- type = line.mid(0, n);
- rest = line.mid(n + 1);
- }
- else
- type = line;
-
- if(type == "C")
- {
- sasl->putStep(stringToArray(rest));
- }
- else if(type == "E")
- {
- if(!rest.isEmpty())
- printf("Error: server says: %s.\n", qPrintable(rest));
- else
- printf("Error: server error, unspecified.\n");
- emit quit();
- return;
- }
- else if(type == "A")
- {
- printf("Authentication success.\n");
- mode = 2; // switch to app mode
-
- // at this point, the server may send us text
- // lines for us to display and then close.
-
- sock_readyRead(); // any extra data?
- return;
- }
- else
- {
- printf("Error: Bad format from peer, closing.\n");
- emit quit();
- return;
- }
- }
- }
+ void tryFinished()
+ {
+ if (sock_done && waitCycles == 0) {
+ printf("Finished, server closed connection.\n");
+
+ // if we give up on waiting for a response to
+ // writeIncoming, then it might come late. in
+ // theory this shouldn't happen if we wait enough
+ // cycles, but if one were to arrive then it could
+ // occur between the request to quit the app and
+ // the actual quit of the app. to assist with
+ // debugging, then, we'll explicitly stop listening
+ // for signals here. otherwise the response may
+ // still be received and displayed, giving a false
+ // sense of correctness.
+ sasl->disconnect(this);
+
+ emit quit();
+ }
+ }
+
+ QString arrayToString(const QByteArray &ba)
+ {
+ return QCA::Base64().arrayToString(ba);
+ }
+
+ QByteArray stringToArray(const QString &s)
+ {
+ return QCA::Base64().stringToArray(s).toByteArray();
+ }
+
+ void sendLine(const QString &line)
+ {
+ printf("Writing: {%s}\n", qPrintable(line));
+ QString s = line + '\n';
+ QByteArray a = s.toUtf8();
+ if (mode == 2) { // app mode
+ sasl->write(a); // write to sasl
+ } else { // mech list or sasl negotiation
+ sock->write(a); // write to socket
+ }
+ }
+
+ void processInbuf()
+ {
+ // collect completed lines from inbuf
+ QStringList list;
+ int at;
+ while ((at = inbuf.indexOf('\n')) != -1) {
+ list += QString::fromUtf8(inbuf.mid(0, at));
+ inbuf = inbuf.mid(at + 1);
+ }
+
+ // process the lines
+ foreach (const QString &line, list) {
+ handleLine(line);
+ }
+ }
+
+ void handleLine(const QString &line)
+ {
+ printf("Reading: [%s]\n", qPrintable(line));
+ if (mode == 0) {
+ // first line is the method list
+ QStringList mechlist = line.split(' ');
+ mode = 1; // switch to sasl negotiation mode
+ sasl->startClient(proto, host, mechlist);
+ } else if (mode == 1) {
+ QString type, rest;
+ int n = line.indexOf(',');
+ if (n != -1) {
+ type = line.mid(0, n);
+ rest = line.mid(n + 1);
+ } else {
+ type = line;
+ }
+
+ if (type == "C") {
+ sasl->putStep(stringToArray(rest));
+ } else if (type == "E") {
+ if (!rest.isEmpty()) {
+ printf("Error: server says: %s.\n", qPrintable(rest));
+ } else {
+ printf("Error: server error, unspecified.\n");
+ }
+ emit quit();
+ return;
+ } else if (type == "A") {
+ printf("Authentication success.\n");
+ mode = 2; // switch to app mode
+
+ // at this point, the server may send us text
+ // lines for us to display and then close.
+
+ sock_readyRead(); // any extra data?
+ return;
+ } else {
+ printf("Error: Bad format from peer, closing.\n");
+ emit quit();
+ return;
+ }
+ }
+ }
};
void usage()
{
- printf("usage: saslclient (options) host(:port) (user) (pass)\n");
- printf("options: --proto=x, --authzid=x, --realm=x\n");
+ printf("usage: saslclient (options) host(:port) (user) (pass)\n");
+ printf("options: --proto=x, --authzid=x, --realm=x\n");
}
int main(int argc, char **argv)
{
- QCA::Initializer init;
- QCoreApplication qapp(argc, argv);
-
- QStringList args = qapp.arguments();
- args.removeFirst();
-
- // options
- QString proto = "qcatest"; // default protocol
- QString authzid, realm;
- bool no_authzid = false;
- bool no_realm = false;
- for(int n = 0; n < args.count(); ++n)
- {
- if(!args[n].startsWith("--"))
- continue;
-
- QString opt = args[n].mid(2);
- QString var, val;
- int at = opt.indexOf('=');
- if(at != -1)
- {
- var = opt.mid(0, at);
- val = opt.mid(at + 1);
- }
- else
- var = opt;
-
- if(var == "proto")
- {
- proto = val;
- }
- else if(var == "authzid")
- {
- // specifying empty authzid means force unspecified
- if(val.isEmpty())
- no_authzid = true;
- else
- authzid = val;
- }
- else if(var == "realm")
- {
- // specifying empty realm means force unspecified
- if(val.isEmpty())
- no_realm = true;
- else
- realm = val;
- }
-
- args.removeAt(n);
- --n; // adjust position
- }
-
- if(args.count() < 1)
- {
- usage();
- return 0;
- }
-
- QString host, user, pass;
- int port = 8001; // default port
-
- QString hostinput = args[0];
- if(args.count() >= 2)
- user = args[1];
- if(args.count() >= 3)
- pass = args[2];
-
- int at = hostinput.indexOf(':');
- if(at != -1)
- {
- host = hostinput.mid(0, at);
- port = hostinput.mid(at + 1).toInt();
- }
- else
- host = hostinput;
-
- if(!QCA::isSupported("sasl"))
- {
- printf("Error: SASL support not found.\n");
- return 1;
- }
-
- ClientTest client(host, port, proto, authzid, realm, user, pass, no_authzid, no_realm);
- QObject::connect(&client, SIGNAL(quit()), &qapp, SLOT(quit()));
- QTimer::singleShot(0, &client, SLOT(start()));
- qapp.exec();
-
- return 0;
+ QCA::Initializer init;
+ QCoreApplication qapp(argc, argv);
+
+ QStringList args = qapp.arguments();
+ args.removeFirst();
+
+ // options
+ QString proto = "qcatest"; // default protocol
+ QString authzid, realm;
+ bool no_authzid = false;
+ bool no_realm = false;
+ for (int n = 0; n < args.count(); ++n) {
+ if (!args[n].startsWith("--")) {
+ continue;
+ }
+
+ QString opt = args[n].mid(2);
+ QString var, val;
+ int at = opt.indexOf('=');
+ if (at != -1) {
+ var = opt.mid(0, at);
+ val = opt.mid(at + 1);
+ } else {
+ var = opt;
+ }
+
+ if (var == "proto") {
+ proto = val;
+ } else if (var == "authzid") {
+ // specifying empty authzid means force unspecified
+ if (val.isEmpty()) {
+ no_authzid = true;
+ } else {
+ authzid = val;
+ }
+ } else if (var == "realm") {
+ // specifying empty realm means force unspecified
+ if (val.isEmpty()) {
+ no_realm = true;
+ } else {
+ realm = val;
+ }
+ }
+
+ args.removeAt(n);
+ --n; // adjust position
+ }
+
+ if (args.count() < 1) {
+ usage();
+ return 0;
+ }
+
+ QString host, user, pass;
+ int port = 8001; // default port
+
+ QString hostinput = args[0];
+ if (args.count() >= 2) {
+ user = args[1];
+ }
+ if (args.count() >= 3) {
+ pass = args[2];
+ }
+
+ int at = hostinput.indexOf(':');
+ if (at != -1) {
+ host = hostinput.mid(0, at);
+ port = hostinput.mid(at + 1).toInt();
+ } else {
+ host = hostinput;
+ }
+
+ if (!QCA::isSupported("sasl")) {
+ printf("Error: SASL support not found.\n");
+ return 1;
+ }
+
+ ClientTest client(host, port, proto, authzid, realm, user, pass, no_authzid, no_realm);
+ QObject::connect(&client, SIGNAL(quit()), &qapp, SLOT(quit()));
+ QTimer::singleShot(0, &client, SLOT(start()));
+ qapp.exec();
+
+ return 0;
}
#include "saslclient.moc"
diff --git a/examples/saslserver/saslserver.cpp b/examples/saslserver/saslserver.cpp
index 9a69aae5..12dd50bd 100644
--- a/examples/saslserver/saslserver.cpp
+++ b/examples/saslserver/saslserver.cpp
@@ -1,514 +1,487 @@
/*
Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
Copyright (C) 2006 Michail Pishchagin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <QCoreApplication>
#include <QTimer>
#include <QTcpSocket>
#include <QTcpServer>
#include <stdio.h>
// QtCrypto has the declarations for all of QCA
#include <QtCrypto>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
static QString socketErrorToString(QAbstractSocket::SocketError x)
{
- QString s;
- switch(x)
- {
- case QAbstractSocket::ConnectionRefusedError:
- s = "connection refused or timed out"; break;
- case QAbstractSocket::RemoteHostClosedError:
- s = "remote host closed the connection"; break;
- case QAbstractSocket::HostNotFoundError:
- s = "host not found"; break;
- case QAbstractSocket::SocketAccessError:
- s = "access error"; break;
- case QAbstractSocket::SocketResourceError:
- s = "too many sockets"; break;
- case QAbstractSocket::SocketTimeoutError:
- s = "operation timed out"; break;
- case QAbstractSocket::DatagramTooLargeError:
- s = "datagram was larger than system limit"; break;
- case QAbstractSocket::NetworkError:
- s = "network error"; break;
- case QAbstractSocket::AddressInUseError:
- s = "address is already in use"; break;
- case QAbstractSocket::SocketAddressNotAvailableError:
- s = "address does not belong to the host"; break;
- case QAbstractSocket::UnsupportedSocketOperationError:
- s = "operation is not supported by the local operating system"; break;
- default:
- s = "unknown socket error"; break;
- }
- return s;
+ QString s;
+ switch (x) {
+ case QAbstractSocket::ConnectionRefusedError:
+ s = "connection refused or timed out"; break;
+ case QAbstractSocket::RemoteHostClosedError:
+ s = "remote host closed the connection"; break;
+ case QAbstractSocket::HostNotFoundError:
+ s = "host not found"; break;
+ case QAbstractSocket::SocketAccessError:
+ s = "access error"; break;
+ case QAbstractSocket::SocketResourceError:
+ s = "too many sockets"; break;
+ case QAbstractSocket::SocketTimeoutError:
+ s = "operation timed out"; break;
+ case QAbstractSocket::DatagramTooLargeError:
+ s = "datagram was larger than system limit"; break;
+ case QAbstractSocket::NetworkError:
+ s = "network error"; break;
+ case QAbstractSocket::AddressInUseError:
+ s = "address is already in use"; break;
+ case QAbstractSocket::SocketAddressNotAvailableError:
+ s = "address does not belong to the host"; break;
+ case QAbstractSocket::UnsupportedSocketOperationError:
+ s = "operation is not supported by the local operating system"; break;
+ default:
+ s = "unknown socket error"; break;
+ }
+ return s;
}
static QString saslAuthConditionToString(QCA::SASL::AuthCondition x)
{
- QString s;
- switch(x)
- {
- case QCA::SASL::NoMechanism:
- s = "no appropriate mechanism could be negotiated"; break;
- case QCA::SASL::BadProtocol:
- s = "bad SASL protocol"; break;
- case QCA::SASL::BadAuth:
- s = "authentication failed"; break;
- case QCA::SASL::NoAuthzid:
- s = "authorization failed"; break;
- case QCA::SASL::TooWeak:
- s = "mechanism too weak for this user"; break;
- case QCA::SASL::NeedEncrypt:
- s = "encryption is needed to use this mechanism"; break;
- case QCA::SASL::Expired:
- s = "passphrase expired"; break;
- case QCA::SASL::Disabled:
- s = "account is disabled"; break;
- case QCA::SASL::NoUser:
- s = "user not found"; break;
- case QCA::SASL::RemoteUnavailable:
- s = "needed remote service is unavailable"; break;
- // AuthFail or unknown (including those defined for client only)
- default:
- s = "generic authentication failure"; break;
- };
- return s;
+ QString s;
+ switch (x) {
+ case QCA::SASL::NoMechanism:
+ s = "no appropriate mechanism could be negotiated"; break;
+ case QCA::SASL::BadProtocol:
+ s = "bad SASL protocol"; break;
+ case QCA::SASL::BadAuth:
+ s = "authentication failed"; break;
+ case QCA::SASL::NoAuthzid:
+ s = "authorization failed"; break;
+ case QCA::SASL::TooWeak:
+ s = "mechanism too weak for this user"; break;
+ case QCA::SASL::NeedEncrypt:
+ s = "encryption is needed to use this mechanism"; break;
+ case QCA::SASL::Expired:
+ s = "passphrase expired"; break;
+ case QCA::SASL::Disabled:
+ s = "account is disabled"; break;
+ case QCA::SASL::NoUser:
+ s = "user not found"; break;
+ case QCA::SASL::RemoteUnavailable:
+ s = "needed remote service is unavailable"; break;
+ // AuthFail or unknown (including those defined for client only)
+ default:
+ s = "generic authentication failure"; break;
+ };
+ return s;
}
// --- ServerTest declaration
class ServerTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private:
- QString host, proto, realm, str;
- int port;
- QTcpServer *tcpServer;
- QList<int> ids;
+ QString host, proto, realm, str;
+ int port;
+ QTcpServer *tcpServer;
+ QList<int> ids;
public:
- ServerTest(const QString &_host, int _port, const QString &_proto, const QString &_realm, const QString &_str);
+ ServerTest(const QString &_host, int _port, const QString &_proto, const QString &_realm, const QString &_str);
- int reserveId();
- void releaseId(int id);
+ int reserveId();
+ void releaseId(int id);
public slots:
- void start();
+ void start();
signals:
- void quit();
+ void quit();
private slots:
- void server_newConnection();
+ void server_newConnection();
};
// --- ServerTestHandler
class ServerTestHandler : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private:
- ServerTest *serverTest;
- QTcpSocket *sock;
- QCA::SASL *sasl;
- int id;
- QString host, proto, realm, str;
- int mode; // 0 = receive mechanism list, 1 = sasl negotiation, 2 = app
- int toWrite;
+ ServerTest *serverTest;
+ QTcpSocket *sock;
+ QCA::SASL *sasl;
+ int id;
+ QString host, proto, realm, str;
+ int mode; // 0 = receive mechanism list, 1 = sasl negotiation, 2 = app
+ int toWrite;
public:
- ServerTestHandler(ServerTest *_serverTest, QTcpSocket *_sock, const QString &_host, const QString &_proto, const QString &_realm, const QString &_str) :
- serverTest(_serverTest),
- sock(_sock),
- host(_host),
- proto(_proto),
- realm(_realm),
- str(_str)
- {
- id = serverTest->reserveId();
-
- sock->setParent(this);
- connect(sock, SIGNAL(disconnected()), SLOT(sock_disconnected()));
- connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
- connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));
- connect(sock, SIGNAL(bytesWritten(qint64)), SLOT(sock_bytesWritten(qint64)));
-
- sasl = new QCA::SASL(this);
- connect(sasl, SIGNAL(authCheck(const QString &, const QString &)), SLOT(sasl_authCheck(const QString &, const QString &)));
- connect(sasl, SIGNAL(nextStep(const QByteArray &)), SLOT(sasl_nextStep(const QByteArray &)));
- connect(sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
- connect(sasl, SIGNAL(readyRead()), SLOT(sasl_readyRead()));
- connect(sasl, SIGNAL(readyReadOutgoing()), SLOT(sasl_readyReadOutgoing()));
- connect(sasl, SIGNAL(error()), SLOT(sasl_error()));
- connect(sasl, SIGNAL(serverStarted()), SLOT(sasl_serverStarted()));
-
- mode = 0; // mech list mode
- toWrite = 0;
-
- int flags = 0;
- flags |= QCA::SASL::AllowPlain;
- flags |= QCA::SASL::AllowAnonymous;
- sasl->setConstraints((QCA::SASL::AuthFlags)flags, 0, 256);
-
- printf("%d: Connection received! Starting SASL handshake...\n", id);
- sasl->startServer(proto, host, realm);
- }
-
- ~ServerTestHandler()
- {
- serverTest->releaseId(id);
- }
+ ServerTestHandler(ServerTest *_serverTest, QTcpSocket *_sock, const QString &_host, const QString &_proto, const QString &_realm, const QString &_str) :
+ serverTest(_serverTest),
+ sock(_sock),
+ host(_host),
+ proto(_proto),
+ realm(_realm),
+ str(_str)
+ {
+ id = serverTest->reserveId();
+
+ sock->setParent(this);
+ connect(sock, SIGNAL(disconnected()), SLOT(sock_disconnected()));
+ connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
+ connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));
+ connect(sock, SIGNAL(bytesWritten(qint64)), SLOT(sock_bytesWritten(qint64)));
+
+ sasl = new QCA::SASL(this);
+ connect(sasl, SIGNAL(authCheck(QString,QString)), SLOT(sasl_authCheck(QString,QString)));
+ connect(sasl, SIGNAL(nextStep(QByteArray)), SLOT(sasl_nextStep(QByteArray)));
+ connect(sasl, SIGNAL(authenticated()), SLOT(sasl_authenticated()));
+ connect(sasl, SIGNAL(readyRead()), SLOT(sasl_readyRead()));
+ connect(sasl, SIGNAL(readyReadOutgoing()), SLOT(sasl_readyReadOutgoing()));
+ connect(sasl, SIGNAL(error()), SLOT(sasl_error()));
+ connect(sasl, SIGNAL(serverStarted()), SLOT(sasl_serverStarted()));
+
+ mode = 0; // mech list mode
+ toWrite = 0;
+
+ int flags = 0;
+ flags |= QCA::SASL::AllowPlain;
+ flags |= QCA::SASL::AllowAnonymous;
+ sasl->setConstraints((QCA::SASL::AuthFlags)flags, 0, 256);
+
+ printf("%d: Connection received! Starting SASL handshake...\n", id);
+ sasl->startServer(proto, host, realm);
+ }
+
+ ~ServerTestHandler()
+ {
+ serverTest->releaseId(id);
+ }
private slots:
- void sasl_serverStarted()
- {
- sendLine(sasl->mechanismList().join(" "));
- }
-
- void sock_disconnected()
- {
- printf("%d: Connection closed.\n", id);
- discard();
- }
-
- void sock_error(QAbstractSocket::SocketError x)
- {
- if(x == QAbstractSocket::RemoteHostClosedError)
- {
- printf("%d: Error: client closed connection unexpectedly.\n", id);
- discard();
- return;
- }
-
- printf("%d: Error: socket: %s\n", id, qPrintable(socketErrorToString(x)));
- discard();
- }
-
- void sock_readyRead()
- {
- if(sock->canReadLine())
- {
- QString line = sock->readLine();
- line.truncate(line.length() - 1); // chop the newline
- handleLine(line);
- }
- }
-
- void sock_bytesWritten(qint64 x)
- {
- if(mode == 2) // app mode
- {
- toWrite -= sasl->convertBytesWritten(x);
- if(toWrite == 0)
- {
- printf("%d: Sent, closing.\n", id);
- sock->close();
- }
- }
- }
-
- void sasl_nextStep(const QByteArray &stepData)
- {
- QString line = "C";
- if(!stepData.isEmpty())
- {
- line += ',';
- line += arrayToString(stepData);
- }
- sendLine(line);
- }
-
- void sasl_authCheck(const QString &user, const QString &authzid)
- {
- printf("%d: AuthCheck: User: [%s], Authzid: [%s]\n", id, qPrintable(user), qPrintable(authzid));
-
- // user - who has logged in, confirmed by sasl
- // authzid - the identity the user wishes to act as, which
- // could be another user or just any arbitrary string (in
- // XMPP, this field holds a Jabber ID, for example). this
- // field is not necessarily confirmed by sasl, and the
- // decision about whether the user can act as the authzid
- // must be made by the app.
-
- // for this simple example program, we allow anyone to use
- // the service, and simply continue onward with the
- // negotiation.
- sasl->continueAfterAuthCheck();
- }
-
- void sasl_authenticated()
- {
- sendLine("A");
- printf("%d: Authentication success.\n", id);
- mode = 2; // switch to app mode
- printf("%d: SSF: %d\n", id, sasl->ssf());
- sendLine(str);
- }
-
- void sasl_readyRead()
- {
- QByteArray a = sasl->read();
- printf("%d: Warning, client sent %d bytes unexpectedly.\n", id, a.size());
- }
-
- void sasl_readyReadOutgoing()
- {
- sock->write(sasl->readOutgoing());
- }
-
- void sasl_error()
- {
- int e = sasl->errorCode();
- if(e == QCA::SASL::ErrorInit)
- {
- printf("%d: Error: sasl: initialization failed.\n", id);
- }
- else if(e == QCA::SASL::ErrorHandshake)
- {
- QString errstr = saslAuthConditionToString(sasl->authCondition());
- sendLine(QString("E,") + errstr);
- printf("%d: Error: sasl: %s.\n", id, qPrintable(errstr));
- }
- else if(e == QCA::SASL::ErrorCrypt)
- {
- printf("%d: Error: sasl: broken security layer.\n", id);
- }
- else
- {
- printf("%d: Error: sasl: unknown error.\n", id);
- }
-
- sock->close();
- }
+ void sasl_serverStarted()
+ {
+ sendLine(sasl->mechanismList().join(" "));
+ }
+
+ void sock_disconnected()
+ {
+ printf("%d: Connection closed.\n", id);
+ discard();
+ }
+
+ void sock_error(QAbstractSocket::SocketError x)
+ {
+ if (x == QAbstractSocket::RemoteHostClosedError) {
+ printf("%d: Error: client closed connection unexpectedly.\n", id);
+ discard();
+ return;
+ }
+
+ printf("%d: Error: socket: %s\n", id, qPrintable(socketErrorToString(x)));
+ discard();
+ }
+
+ void sock_readyRead()
+ {
+ if (sock->canReadLine()) {
+ QString line = sock->readLine();
+ line.truncate(line.length() - 1); // chop the newline
+ handleLine(line);
+ }
+ }
+
+ void sock_bytesWritten(qint64 x)
+ {
+ if (mode == 2) { // app mode
+ toWrite -= sasl->convertBytesWritten(x);
+ if (toWrite == 0) {
+ printf("%d: Sent, closing.\n", id);
+ sock->close();
+ }
+ }
+ }
+
+ void sasl_nextStep(const QByteArray &stepData)
+ {
+ QString line = "C";
+ if (!stepData.isEmpty()) {
+ line += ',';
+ line += arrayToString(stepData);
+ }
+ sendLine(line);
+ }
+
+ void sasl_authCheck(const QString &user, const QString &authzid)
+ {
+ printf("%d: AuthCheck: User: [%s], Authzid: [%s]\n", id, qPrintable(user), qPrintable(authzid));
+
+ // user - who has logged in, confirmed by sasl
+ // authzid - the identity the user wishes to act as, which
+ // could be another user or just any arbitrary string (in
+ // XMPP, this field holds a Jabber ID, for example). this
+ // field is not necessarily confirmed by sasl, and the
+ // decision about whether the user can act as the authzid
+ // must be made by the app.
+
+ // for this simple example program, we allow anyone to use
+ // the service, and simply continue onward with the
+ // negotiation.
+ sasl->continueAfterAuthCheck();
+ }
+
+ void sasl_authenticated()
+ {
+ sendLine("A");
+ printf("%d: Authentication success.\n", id);
+ mode = 2; // switch to app mode
+ printf("%d: SSF: %d\n", id, sasl->ssf());
+ sendLine(str);
+ }
+
+ void sasl_readyRead()
+ {
+ QByteArray a = sasl->read();
+ printf("%d: Warning, client sent %d bytes unexpectedly.\n", id, a.size());
+ }
+
+ void sasl_readyReadOutgoing()
+ {
+ sock->write(sasl->readOutgoing());
+ }
+
+ void sasl_error()
+ {
+ int e = sasl->errorCode();
+ if (e == QCA::SASL::ErrorInit) {
+ printf("%d: Error: sasl: initialization failed.\n", id);
+ } else if (e == QCA::SASL::ErrorHandshake) {
+ QString errstr = saslAuthConditionToString(sasl->authCondition());
+ sendLine(QString("E,") + errstr);
+ printf("%d: Error: sasl: %s.\n", id, qPrintable(errstr));
+ } else if (e == QCA::SASL::ErrorCrypt) {
+ printf("%d: Error: sasl: broken security layer.\n", id);
+ } else {
+ printf("%d: Error: sasl: unknown error.\n", id);
+ }
+
+ sock->close();
+ }
private:
- void discard()
- {
- deleteLater();
- }
-
- void handleLine(const QString &line)
- {
- printf("%d: Reading: [%s]\n", id, qPrintable(line));
- if(mode == 0)
- {
- int n = line.indexOf(' ');
- if(n != -1)
- {
- QString mech = line.mid(0, n);
- QString rest = line.mid(n + 1).toUtf8();
- sasl->putServerFirstStep(mech, stringToArray(rest));
- }
- else
- sasl->putServerFirstStep(line);
- ++mode;
- }
- else if(mode == 1)
- {
- QString type, rest;
- int n = line.indexOf(',');
- if(n != -1)
- {
- type = line.mid(0, n);
- rest = line.mid(n + 1);
- }
- else
- {
- type = line;
- rest = "";
- }
-
- if(type == "C")
- {
- sasl->putStep(stringToArray(rest));
- }
- else
- {
- printf("%d: Bad format from peer, closing.\n", id);
- sock->close();
- return;
- }
- }
- }
-
- QString arrayToString(const QByteArray &ba)
- {
- QCA::Base64 encoder;
- return encoder.arrayToString(ba);
- }
-
- QByteArray stringToArray(const QString &s)
- {
- QCA::Base64 decoder(QCA::Decode);
- return decoder.stringToArray(s).toByteArray();
- }
-
- void sendLine(const QString &line)
- {
- printf("%d: Writing: {%s}\n", id, qPrintable(line));
- QString s = line + '\n';
- QByteArray a = s.toUtf8();
- if(mode == 2) // app mode
- {
- toWrite += a.size();
- sasl->write(a); // write to sasl
- }
- else // mech list or sasl negotiation
- sock->write(a); // write to socket
- }
+ void discard()
+ {
+ deleteLater();
+ }
+
+ void handleLine(const QString &line)
+ {
+ printf("%d: Reading: [%s]\n", id, qPrintable(line));
+ if (mode == 0) {
+ int n = line.indexOf(' ');
+ if (n != -1) {
+ QString mech = line.mid(0, n);
+ QString rest = line.mid(n + 1).toUtf8();
+ sasl->putServerFirstStep(mech, stringToArray(rest));
+ } else {
+ sasl->putServerFirstStep(line);
+ }
+ ++mode;
+ } else if (mode == 1) {
+ QString type, rest;
+ int n = line.indexOf(',');
+ if (n != -1) {
+ type = line.mid(0, n);
+ rest = line.mid(n + 1);
+ } else {
+ type = line;
+ rest = "";
+ }
+
+ if (type == "C") {
+ sasl->putStep(stringToArray(rest));
+ } else {
+ printf("%d: Bad format from peer, closing.\n", id);
+ sock->close();
+ return;
+ }
+ }
+ }
+
+ QString arrayToString(const QByteArray &ba)
+ {
+ QCA::Base64 encoder;
+ return encoder.arrayToString(ba);
+ }
+
+ QByteArray stringToArray(const QString &s)
+ {
+ QCA::Base64 decoder(QCA::Decode);
+ return decoder.stringToArray(s).toByteArray();
+ }
+
+ void sendLine(const QString &line)
+ {
+ printf("%d: Writing: {%s}\n", id, qPrintable(line));
+ QString s = line + '\n';
+ QByteArray a = s.toUtf8();
+ if (mode == 2) { // app mode
+ toWrite += a.size();
+ sasl->write(a); // write to sasl
+ } else { // mech list or sasl negotiation
+ sock->write(a); // write to socket
+ }
+ }
};
// --- ServerTest implementation
ServerTest::ServerTest(const QString &_host, int _port, const QString &_proto, const QString &_realm, const QString &_str) :
- host(_host),
- proto(_proto),
- realm(_realm),
- str(_str),
- port(_port)
+ host(_host),
+ proto(_proto),
+ realm(_realm),
+ str(_str),
+ port(_port)
{
- tcpServer = new QTcpServer(this);
- connect(tcpServer, SIGNAL(newConnection()), SLOT(server_newConnection()));
+ tcpServer = new QTcpServer(this);
+ connect(tcpServer, SIGNAL(newConnection()), SLOT(server_newConnection()));
}
int ServerTest::reserveId()
{
- int n = 0;
- while(ids.contains(n))
- ++n;
- ids += n;
- return n;
+ int n = 0;
+ while (ids.contains(n)) {
+ ++n;
+ }
+ ids += n;
+ return n;
}
void ServerTest::releaseId(int id)
{
- ids.removeAll(id);
+ ids.removeAll(id);
}
void ServerTest::start()
{
- if(!tcpServer->listen(QHostAddress::Any, port))
- {
- printf("Error: unable to bind to port %d.\n", port);
- emit quit();
- return;
- }
-
- printf("Serving on %s:%d, for protocol %s ...\n", qPrintable(host), port, qPrintable(proto));
+ if (!tcpServer->listen(QHostAddress::Any, port)) {
+ printf("Error: unable to bind to port %d.\n", port);
+ emit quit();
+ return;
+ }
+
+ printf("Serving on %s:%d, for protocol %s ...\n", qPrintable(host), port, qPrintable(proto));
}
void ServerTest::server_newConnection()
{
- QTcpSocket *sock = tcpServer->nextPendingConnection();
- new ServerTestHandler(this, sock, host, proto, realm, str);
+ QTcpSocket *sock = tcpServer->nextPendingConnection();
+ new ServerTestHandler(this, sock, host, proto, realm, str);
}
// ---
void usage()
{
- printf("usage: saslserver host (message)\n");
- printf("options: --proto=x, --realm=x\n");
+ printf("usage: saslserver host (message)\n");
+ printf("options: --proto=x, --realm=x\n");
}
int main(int argc, char **argv)
{
- QCA::Initializer init;
- QCoreApplication qapp(argc, argv);
-
- QCA::setAppName("saslserver");
-
- QStringList args = qapp.arguments();
- args.removeFirst();
-
- // options
- QString proto = "qcatest"; // default protocol
- QString realm;
- for(int n = 0; n < args.count(); ++n)
- {
- if(!args[n].startsWith("--"))
- continue;
-
- QString opt = args[n].mid(2);
- QString var, val;
- int at = opt.indexOf('=');
- if(at != -1)
- {
- var = opt.mid(0, at);
- val = opt.mid(at + 1);
- }
- else
- var = opt;
-
- if(var == "proto")
- proto = val;
- else if(var == "realm")
- realm = val;
-
- args.removeAt(n);
- --n; // adjust position
- }
-
- if(args.count() < 1)
- {
- usage();
- return 0;
- }
-
- QString host;
- int port = 8001; // default port
-
- QString hostinput = args[0];
- QString str = "Hello, World";
- if(args.count() >= 2)
- str = args[1];
-
- int at = hostinput.indexOf(':');
- if(at != -1)
- {
- host = hostinput.mid(0, at);
- port = hostinput.mid(at + 1).toInt();
- }
- else
- host = hostinput;
-
- if(!QCA::isSupported("sasl"))
- {
- printf("Error: SASL support not found.\n");
- return 1;
- }
-
- ServerTest server(host, port, proto, realm, str);
- QObject::connect(&server, SIGNAL(quit()), &qapp, SLOT(quit()));
- QTimer::singleShot(0, &server, SLOT(start()));
- qapp.exec();
-
- return 0;
+ QCA::Initializer init;
+ QCoreApplication qapp(argc, argv);
+
+ QCA::setAppName("saslserver");
+
+ QStringList args = qapp.arguments();
+ args.removeFirst();
+
+ // options
+ QString proto = "qcatest"; // default protocol
+ QString realm;
+ for (int n = 0; n < args.count(); ++n) {
+ if (!args[n].startsWith("--")) {
+ continue;
+ }
+
+ QString opt = args[n].mid(2);
+ QString var, val;
+ int at = opt.indexOf('=');
+ if (at != -1) {
+ var = opt.mid(0, at);
+ val = opt.mid(at + 1);
+ } else {
+ var = opt;
+ }
+
+ if (var == "proto") {
+ proto = val;
+ } else if (var == "realm") {
+ realm = val;
+ }
+
+ args.removeAt(n);
+ --n; // adjust position
+ }
+
+ if (args.count() < 1) {
+ usage();
+ return 0;
+ }
+
+ QString host;
+ int port = 8001; // default port
+
+ QString hostinput = args[0];
+ QString str = "Hello, World";
+ if (args.count() >= 2) {
+ str = args[1];
+ }
+
+ int at = hostinput.indexOf(':');
+ if (at != -1) {
+ host = hostinput.mid(0, at);
+ port = hostinput.mid(at + 1).toInt();
+ } else {
+ host = hostinput;
+ }
+
+ if (!QCA::isSupported("sasl")) {
+ printf("Error: SASL support not found.\n");
+ return 1;
+ }
+
+ ServerTest server(host, port, proto, realm, str);
+ QObject::connect(&server, SIGNAL(quit()), &qapp, SLOT(quit()));
+ QTimer::singleShot(0, &server, SLOT(start()));
+ qapp.exec();
+
+ return 0;
}
#include "saslserver.moc"
diff --git a/examples/sslservtest/sslservtest.cpp b/examples/sslservtest/sslservtest.cpp
index bed14acb..a8ce4d60 100644
--- a/examples/sslservtest/sslservtest.cpp
+++ b/examples/sslservtest/sslservtest.cpp
@@ -1,273 +1,274 @@
/*
Copyright (C) 2003 Justin Karneges <justin@affinix.com>
Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <QtCrypto>
#include <QCoreApplication>
#include <QDebug>
#include <QHostAddress>
#include <QTcpServer>
#include <QTcpSocket>
#include <QTimer>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
char pemdata_cert[] =
- "-----BEGIN CERTIFICATE-----\n"
- "MIICeTCCAeKgAwIBAgIRAKKKnOj6Aarmwf0phApitVAwDQYJKoZIhvcNAQEFBQAw\n"
- "ODELMAkGA1UEBhMCVVMxFDASBgNVBAoTC0V4YW1wbGUgT3JnMRMwEQYDVQQDEwpF\n"
- "eGFtcGxlIENBMB4XDTA2MDMxNTA3MDU1MloXDTA3MDMxNTA3MDU1MlowOjEVMBMG\n"
- "A1UEAxMMRXhhbXBsZSBVc2VyMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBs\n"
- "ZSBPcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPkKn0FfHMvRZv+3uFcw\n"
- "VrOadJmANzLVeVW/DHZp4CXokXSksM66ZMqFuQRBk5rnIZZpZmVp1tTRDVt9sEAY\n"
- "YNa8CRM4HXkVlU0lCKdey18CSq2VuSvNtw8dDpoBmQt3nr9tePvKHnpS3nm6YjR2\n"
- "NEvIKt1P4mHzYXLmwoF24C1bAgMBAAGjgYAwfjAdBgNVHQ4EFgQUmQIdzyDaPYWF\n"
- "fPJ8PPOOm1eSsucwHwYDVR0jBBgwFoAUkCglAizTO7iqwLeaO6r/8kJuqhMwDAYD\n"
- "VR0TAQH/BAIwADAeBgNVHREEFzAVgRNleGFtcGxlQGV4YW1wbGUuY29tMA4GA1Ud\n"
- "DwEB/wQEAwIF4DANBgkqhkiG9w0BAQUFAAOBgQAuhbiUgy2a++EUccaonID7eTJZ\n"
- "F3D5qXMqUpQxlYxU8du+9AxDD7nFxTMkQC2pzfmEc1znRNmJ1ZeLRL72VYsVndcT\n"
- "psyM8ABkvPp1d2jWIyccVjGpt+/RN5IPKm/YIbtIZcywvWuXrOp1lanVmppLfPnO\n"
- "6yneBkC9iqjOv/+Q+A==\n"
- "-----END CERTIFICATE-----\n";
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIICeTCCAeKgAwIBAgIRAKKKnOj6Aarmwf0phApitVAwDQYJKoZIhvcNAQEFBQAw\n"
+ "ODELMAkGA1UEBhMCVVMxFDASBgNVBAoTC0V4YW1wbGUgT3JnMRMwEQYDVQQDEwpF\n"
+ "eGFtcGxlIENBMB4XDTA2MDMxNTA3MDU1MloXDTA3MDMxNTA3MDU1MlowOjEVMBMG\n"
+ "A1UEAxMMRXhhbXBsZSBVc2VyMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBs\n"
+ "ZSBPcmcwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPkKn0FfHMvRZv+3uFcw\n"
+ "VrOadJmANzLVeVW/DHZp4CXokXSksM66ZMqFuQRBk5rnIZZpZmVp1tTRDVt9sEAY\n"
+ "YNa8CRM4HXkVlU0lCKdey18CSq2VuSvNtw8dDpoBmQt3nr9tePvKHnpS3nm6YjR2\n"
+ "NEvIKt1P4mHzYXLmwoF24C1bAgMBAAGjgYAwfjAdBgNVHQ4EFgQUmQIdzyDaPYWF\n"
+ "fPJ8PPOOm1eSsucwHwYDVR0jBBgwFoAUkCglAizTO7iqwLeaO6r/8kJuqhMwDAYD\n"
+ "VR0TAQH/BAIwADAeBgNVHREEFzAVgRNleGFtcGxlQGV4YW1wbGUuY29tMA4GA1Ud\n"
+ "DwEB/wQEAwIF4DANBgkqhkiG9w0BAQUFAAOBgQAuhbiUgy2a++EUccaonID7eTJZ\n"
+ "F3D5qXMqUpQxlYxU8du+9AxDD7nFxTMkQC2pzfmEc1znRNmJ1ZeLRL72VYsVndcT\n"
+ "psyM8ABkvPp1d2jWIyccVjGpt+/RN5IPKm/YIbtIZcywvWuXrOp1lanVmppLfPnO\n"
+ "6yneBkC9iqjOv/+Q+A==\n"
+ "-----END CERTIFICATE-----\n";
char pemdata_privkey[] =
- "-----BEGIN PRIVATE KEY-----\n"
- "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAPkKn0FfHMvRZv+3\n"
- "uFcwVrOadJmANzLVeVW/DHZp4CXokXSksM66ZMqFuQRBk5rnIZZpZmVp1tTRDVt9\n"
- "sEAYYNa8CRM4HXkVlU0lCKdey18CSq2VuSvNtw8dDpoBmQt3nr9tePvKHnpS3nm6\n"
- "YjR2NEvIKt1P4mHzYXLmwoF24C1bAgMBAAECgYEAyIjJHDaeVXDU42zovyxpZE4n\n"
- "PcOEryY+gdFJE8DFgUD4f1huFsj4iCuNg+PaG42p+hf9IARNvSho/RcEaVg4AJrV\n"
- "jRP8r7fSqcIGr6lGuvDFFv3SU5ddy84g5oqLYGKvuPSHMGfVsZSxAwOrzD4bH19L\n"
- "SNqtNcpdBsBd7ZiEE4ECQQD/oJGui9D5Dx3QVcS+QV4F8wuyN9jYIANmX/17o0fl\n"
- "BL0bwRU4RICwadrcybi5N0JQLIYSUm2HGqNvAJbtnuQxAkEA+WeYLLYPeawcy+WU\n"
- "kGcOR7BUjHiG71+6cvU4XIDW2bezA04fqWXkZRFAwHTMpQb785/XalFftgS21kql\n"
- "8yLDSwJAHkeT2hwftdDPlEUEmBDAJW5DvWmWGwu3u2G1cfbGZl9oUyhM7ixXHg57\n"
- "6VlPs0jTZxHPE86FwNIr99MXDbCbkQJBAMDFOJK+ecGirXNP1P+0GA6DFSap9inJ\n"
- "BRTbwx+EmgwX966DUOefEOSpbDIVVSPs/Qr2LgtIMEFA7Y0+j3wZD3cCQBsTwccd\n"
- "ASQx59xakpq11eOlTYz14rjwodr4QMyj26WxEPJtz7hKokx/+EH6fWuPIUSrROM5\n"
- "07y2gaVbYxtis0s=\n"
- "-----END PRIVATE KEY-----\n";
+ "-----BEGIN PRIVATE KEY-----\n"
+ "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAPkKn0FfHMvRZv+3\n"
+ "uFcwVrOadJmANzLVeVW/DHZp4CXokXSksM66ZMqFuQRBk5rnIZZpZmVp1tTRDVt9\n"
+ "sEAYYNa8CRM4HXkVlU0lCKdey18CSq2VuSvNtw8dDpoBmQt3nr9tePvKHnpS3nm6\n"
+ "YjR2NEvIKt1P4mHzYXLmwoF24C1bAgMBAAECgYEAyIjJHDaeVXDU42zovyxpZE4n\n"
+ "PcOEryY+gdFJE8DFgUD4f1huFsj4iCuNg+PaG42p+hf9IARNvSho/RcEaVg4AJrV\n"
+ "jRP8r7fSqcIGr6lGuvDFFv3SU5ddy84g5oqLYGKvuPSHMGfVsZSxAwOrzD4bH19L\n"
+ "SNqtNcpdBsBd7ZiEE4ECQQD/oJGui9D5Dx3QVcS+QV4F8wuyN9jYIANmX/17o0fl\n"
+ "BL0bwRU4RICwadrcybi5N0JQLIYSUm2HGqNvAJbtnuQxAkEA+WeYLLYPeawcy+WU\n"
+ "kGcOR7BUjHiG71+6cvU4XIDW2bezA04fqWXkZRFAwHTMpQb785/XalFftgS21kql\n"
+ "8yLDSwJAHkeT2hwftdDPlEUEmBDAJW5DvWmWGwu3u2G1cfbGZl9oUyhM7ixXHg57\n"
+ "6VlPs0jTZxHPE86FwNIr99MXDbCbkQJBAMDFOJK+ecGirXNP1P+0GA6DFSap9inJ\n"
+ "BRTbwx+EmgwX966DUOefEOSpbDIVVSPs/Qr2LgtIMEFA7Y0+j3wZD3cCQBsTwccd\n"
+ "ASQx59xakpq11eOlTYz14rjwodr4QMyj26WxEPJtz7hKokx/+EH6fWuPIUSrROM5\n"
+ "07y2gaVbYxtis0s=\n"
+ "-----END PRIVATE KEY-----\n";
class SecureServer : public QObject
{
Q_OBJECT
public:
enum { Idle, Handshaking, Active, Closing };
SecureServer(quint16 _port) : port(_port)
{
- server = new QTcpServer;
- connect( server, SIGNAL(newConnection()), SLOT(server_handleConnection()) );
+ server = new QTcpServer;
+ connect(server, SIGNAL(newConnection()), SLOT(server_handleConnection()));
- ssl = new QCA::TLS;
- connect(ssl, SIGNAL(handshaken()), SLOT(ssl_handshaken()));
- connect(ssl, SIGNAL(readyRead()), SLOT(ssl_readyRead()));
- connect(ssl, SIGNAL(readyReadOutgoing()), SLOT(ssl_readyReadOutgoing()));
- connect(ssl, SIGNAL(closed()), SLOT(ssl_closed()));
- connect(ssl, SIGNAL(error()), SLOT(ssl_error()));
+ ssl = new QCA::TLS;
+ connect(ssl, SIGNAL(handshaken()), SLOT(ssl_handshaken()));
+ connect(ssl, SIGNAL(readyRead()), SLOT(ssl_readyRead()));
+ connect(ssl, SIGNAL(readyReadOutgoing()), SLOT(ssl_readyReadOutgoing()));
+ connect(ssl, SIGNAL(closed()), SLOT(ssl_closed()));
+ connect(ssl, SIGNAL(error()), SLOT(ssl_error()));
- cert = QCA::Certificate::fromPEM(pemdata_cert);
- privkey = QCA::PrivateKey::fromPEM(pemdata_privkey);
+ cert = QCA::Certificate::fromPEM(pemdata_cert);
+ privkey = QCA::PrivateKey::fromPEM(pemdata_privkey);
- mode = Idle;
+ mode = Idle;
}
~SecureServer()
{
- delete ssl;
- delete server;
+ delete ssl;
+ delete server;
}
void start()
{
- if(cert.isNull()) {
- qDebug() << "Error loading cert!";
- QTimer::singleShot(0, this, SIGNAL(quit()));
- return;
- }
- if(privkey.isNull()) {
- qDebug() << "Error loading private key!";
- QTimer::singleShot(0, this, SIGNAL(quit()));
- return;
- }
- if(false == server->listen(QHostAddress::Any, port)) {
- qDebug() << "Error binding to port " << port;
- QTimer::singleShot(0, this, SIGNAL(quit()));
- return;
- }
- qDebug() << "Listening on port" << port;
+ if (cert.isNull()) {
+ qDebug() << "Error loading cert!";
+ QTimer::singleShot(0, this, SIGNAL(quit()));
+ return;
+ }
+ if (privkey.isNull()) {
+ qDebug() << "Error loading private key!";
+ QTimer::singleShot(0, this, SIGNAL(quit()));
+ return;
+ }
+ if (false == server->listen(QHostAddress::Any, port)) {
+ qDebug() << "Error binding to port " << port;
+ QTimer::singleShot(0, this, SIGNAL(quit()));
+ return;
+ }
+ qDebug() << "Listening on port" << port;
}
signals:
void quit();
private slots:
void sock_readyRead()
{
- QByteArray buf(sock->bytesAvailable(), 0x00);
+ QByteArray buf(sock->bytesAvailable(), 0x00);
- int num = sock->read(buf.data(), buf.size());
+ int num = sock->read(buf.data(), buf.size());
- if ( -1 == num )
- qDebug() << "Error reading data from socket";
+ if (-1 == num) {
+ qDebug() << "Error reading data from socket";
+ }
- if (num < buf.size() )
- buf.resize(num);
+ if (num < buf.size()) {
+ buf.resize(num);
+ }
- ssl->writeIncoming(buf);
+ ssl->writeIncoming(buf);
}
void server_handleConnection()
{
- // Note: only 1 connection supported at a time in this example!
- if(mode != Idle) {
- QTcpSocket* tmp = server->nextPendingConnection();
- tmp->close();
- connect(tmp, SIGNAL(disconnected()), tmp, SLOT(deleteLater()));
- qDebug() << "throwing away extra connection";
- return;
- }
- mode = Handshaking;
- sock = server->nextPendingConnection();
- connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
- connect(sock, SIGNAL(disconnected()), SLOT(sock_disconnected()));
- connect(sock, SIGNAL(error(QAbstractSocket::SocketError)),
- SLOT(sock_error(QAbstractSocket::SocketError)));
- connect(sock, SIGNAL(bytesWritten(qint64)), SLOT(sock_bytesWritten(qint64)));
-
- qDebug() << "Connection received! Starting TLS handshake.";
- ssl->setCertificate(cert, privkey);
- ssl->startServer();
+ // Note: only 1 connection supported at a time in this example!
+ if (mode != Idle) {
+ QTcpSocket *tmp = server->nextPendingConnection();
+ tmp->close();
+ connect(tmp, SIGNAL(disconnected()), tmp, SLOT(deleteLater()));
+ qDebug() << "throwing away extra connection";
+ return;
+ }
+ mode = Handshaking;
+ sock = server->nextPendingConnection();
+ connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
+ connect(sock, SIGNAL(disconnected()), SLOT(sock_disconnected()));
+ connect(sock, SIGNAL(error(QAbstractSocket::SocketError)),
+ SLOT(sock_error(QAbstractSocket::SocketError)));
+ connect(sock, SIGNAL(bytesWritten(qint64)), SLOT(sock_bytesWritten(qint64)));
+
+ qDebug() << "Connection received! Starting TLS handshake.";
+ ssl->setCertificate(cert, privkey);
+ ssl->startServer();
}
void sock_disconnected()
{
- qDebug() << "Connection closed.";
+ qDebug() << "Connection closed.";
}
void sock_bytesWritten(qint64 x)
{
- if(mode == Active && sent) {
- qint64 bytes = ssl->convertBytesWritten(x);
- bytesLeft -= bytes;
-
- if(bytesLeft == 0) {
- mode = Closing;
- qDebug() << "Data transfer complete - SSL shutting down";
- ssl->close();
- }
- }
+ if (mode == Active && sent) {
+ qint64 bytes = ssl->convertBytesWritten(x);
+ bytesLeft -= bytes;
+
+ if (bytesLeft == 0) {
+ mode = Closing;
+ qDebug() << "Data transfer complete - SSL shutting down";
+ ssl->close();
+ }
+ }
}
void sock_error(QAbstractSocket::SocketError error)
{
- qDebug() << "Socket error: " << (unsigned) error;
+ qDebug() << "Socket error: " << (unsigned) error;
}
void ssl_handshaken()
{
- qDebug() << "Successful SSL handshake. Waiting for newline.";
- bytesLeft = 0;
- sent = false;
- mode = Active;
- ssl->continueAfterStep();
+ qDebug() << "Successful SSL handshake. Waiting for newline.";
+ bytesLeft = 0;
+ sent = false;
+ mode = Active;
+ ssl->continueAfterStep();
}
void ssl_readyRead()
{
- QByteArray a = ssl->read();
- QByteArray b =
- "<html>\n"
- "<head><title>Test</title></head>\n"
- "<body>this is only a test</body>\n"
- "</html>\n";
-
- qDebug() << "Sending test response.";
- sent = true;
- ssl->write(b);
+ QByteArray a = ssl->read();
+ QByteArray b =
+ "<html>\n"
+ "<head><title>Test</title></head>\n"
+ "<body>this is only a test</body>\n"
+ "</html>\n";
+
+ qDebug() << "Sending test response.";
+ sent = true;
+ ssl->write(b);
}
void ssl_readyReadOutgoing()
{
- int plainBytes;
- QByteArray outgoingData = ssl->readOutgoing(&plainBytes);
- sock->write( outgoingData );
+ int plainBytes;
+ QByteArray outgoingData = ssl->readOutgoing(&plainBytes);
+ sock->write(outgoingData);
}
void ssl_closed()
{
- qDebug() << "Closing socket.";
- sock->close();
- mode = Idle;
+ qDebug() << "Closing socket.";
+ sock->close();
+ mode = Idle;
}
void ssl_error()
{
- if(ssl->errorCode() == QCA::TLS::ErrorHandshake) {
- qDebug() << "SSL Handshake Error! Closing.";
- sock->close();
- }
- else {
- qDebug() << "SSL Error! Closing.";
- sock->close();
- }
- mode = Idle;
+ if (ssl->errorCode() == QCA::TLS::ErrorHandshake) {
+ qDebug() << "SSL Handshake Error! Closing.";
+ sock->close();
+ } else {
+ qDebug() << "SSL Error! Closing.";
+ sock->close();
+ }
+ mode = Idle;
}
private:
quint16 port;
QTcpServer *server;
QTcpSocket *sock;
QCA::TLS *ssl;
QCA::Certificate cert;
QCA::PrivateKey privkey;
bool sent;
int mode;
qint64 bytesLeft;
};
#include "sslservtest.moc"
int main(int argc, char **argv)
{
QCA::Initializer init;
QCoreApplication app(argc, argv);
int port = argc > 1 ? QString(argv[1]).toInt() : 8000;
- if(!QCA::isSupported("tls")) {
- qDebug() << "TLS not supported!";
- return 1;
+ if (!QCA::isSupported("tls")) {
+ qDebug() << "TLS not supported!";
+ return 1;
}
SecureServer *server = new SecureServer(port);
QObject::connect(server, SIGNAL(quit()), &app, SLOT(quit()));
server->start();
app.exec();
delete server;
return 0;
}
diff --git a/examples/ssltest/ssltest.cpp b/examples/ssltest/ssltest.cpp
index de3a7c0e..cd07b7f5 100644
--- a/examples/ssltest/ssltest.cpp
+++ b/examples/ssltest/ssltest.cpp
@@ -1,336 +1,331 @@
/*
Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <QtCrypto>
#include <QCoreApplication>
#include <QTcpSocket>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
char exampleCA_cert[] =
- "-----BEGIN CERTIFICATE-----\n"
- "MIICSzCCAbSgAwIBAgIBADANBgkqhkiG9w0BAQUFADA4MRMwEQYDVQQDEwpFeGFt\n"
- "cGxlIENBMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBsZSBPcmcwHhcNMDYw\n"
- "MzE1MDY1ODMyWhcNMDYwNDE1MDY1ODMyWjA4MRMwEQYDVQQDEwpFeGFtcGxlIENB\n"
- "MQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBsZSBPcmcwgZ8wDQYJKoZIhvcN\n"
- "AQEBBQADgY0AMIGJAoGBAL6ULdOxmpeZ+G/ypV12eNO4qnHSVIPTrYPkQuweXqPy\n"
- "atwGFheG+hLVsNIh9GGOS0tCe7a3hBBKN0BJg1ppfk2x39cDx7hefYqjBuZvp/0O\n"
- "8Ja3qlQiJLezITZKLxMBrsibcvcuH8zpfUdys2yaN+YGeqNfjQuoNN3Byl1TwuGJ\n"
- "AgMBAAGjZTBjMB0GA1UdDgQWBBSQKCUCLNM7uKrAt5o7qv/yQm6qEzASBgNVHRMB\n"
- "Af8ECDAGAQEBAgEIMB4GA1UdEQQXMBWBE2V4YW1wbGVAZXhhbXBsZS5jb20wDgYD\n"
- "VR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4GBAAh+SIeT1Ao5qInw8oMSoTdO\n"
- "lQ6h67ec/Jk5KmK4OoskuimmHI0Sp0C5kOCLehXbsVWW8pXsNC2fv0d2HkdaSUcX\n"
- "hwLzqgyZXd4mupIYlaOTZhuHDwWPCAOZS4LVsi2tndTRHKCP12441JjNKhmZRhkR\n"
- "u5zzD60nWgM9dKTaxuZM\n"
- "-----END CERTIFICATE-----\n";
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIICSzCCAbSgAwIBAgIBADANBgkqhkiG9w0BAQUFADA4MRMwEQYDVQQDEwpFeGFt\n"
+ "cGxlIENBMQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBsZSBPcmcwHhcNMDYw\n"
+ "MzE1MDY1ODMyWhcNMDYwNDE1MDY1ODMyWjA4MRMwEQYDVQQDEwpFeGFtcGxlIENB\n"
+ "MQswCQYDVQQGEwJVUzEUMBIGA1UEChMLRXhhbXBsZSBPcmcwgZ8wDQYJKoZIhvcN\n"
+ "AQEBBQADgY0AMIGJAoGBAL6ULdOxmpeZ+G/ypV12eNO4qnHSVIPTrYPkQuweXqPy\n"
+ "atwGFheG+hLVsNIh9GGOS0tCe7a3hBBKN0BJg1ppfk2x39cDx7hefYqjBuZvp/0O\n"
+ "8Ja3qlQiJLezITZKLxMBrsibcvcuH8zpfUdys2yaN+YGeqNfjQuoNN3Byl1TwuGJ\n"
+ "AgMBAAGjZTBjMB0GA1UdDgQWBBSQKCUCLNM7uKrAt5o7qv/yQm6qEzASBgNVHRMB\n"
+ "Af8ECDAGAQEBAgEIMB4GA1UdEQQXMBWBE2V4YW1wbGVAZXhhbXBsZS5jb20wDgYD\n"
+ "VR0PAQH/BAQDAgEGMA0GCSqGSIb3DQEBBQUAA4GBAAh+SIeT1Ao5qInw8oMSoTdO\n"
+ "lQ6h67ec/Jk5KmK4OoskuimmHI0Sp0C5kOCLehXbsVWW8pXsNC2fv0d2HkdaSUcX\n"
+ "hwLzqgyZXd4mupIYlaOTZhuHDwWPCAOZS4LVsi2tndTRHKCP12441JjNKhmZRhkR\n"
+ "u5zzD60nWgM9dKTaxuZM\n"
+ "-----END CERTIFICATE-----\n";
void showCertInfo(const QCA::Certificate &cert)
{
- printf("-- Cert --\n");
- printf(" CN: %s\n", qPrintable(cert.commonName()));
- printf(" Valid from: %s, until %s\n",
- qPrintable(cert.notValidBefore().toString()),
- qPrintable(cert.notValidAfter().toString()));
- printf(" PEM:\n%s\n", qPrintable(cert.toPEM()));
+ printf("-- Cert --\n");
+ printf(" CN: %s\n", qPrintable(cert.commonName()));
+ printf(" Valid from: %s, until %s\n",
+ qPrintable(cert.notValidBefore().toString()),
+ qPrintable(cert.notValidAfter().toString()));
+ printf(" PEM:\n%s\n", qPrintable(cert.toPEM()));
}
static QString validityToString(QCA::Validity v)
{
- QString s;
- switch(v)
- {
- case QCA::ValidityGood:
- s = "Validated";
- break;
- case QCA::ErrorRejected:
- s = "Root CA is marked to reject the specified purpose";
- break;
- case QCA::ErrorUntrusted:
- s = "Certificate not trusted for the required purpose";
- break;
- case QCA::ErrorSignatureFailed:
- s = "Invalid signature";
- break;
- case QCA::ErrorInvalidCA:
- s = "Invalid CA certificate";
- break;
- case QCA::ErrorInvalidPurpose:
- s = "Invalid certificate purpose";
- break;
- case QCA::ErrorSelfSigned:
- s = "Certificate is self-signed";
- break;
- case QCA::ErrorRevoked:
- s = "Certificate has been revoked";
- break;
- case QCA::ErrorPathLengthExceeded:
- s = "Maximum certificate chain length exceeded";
- break;
- case QCA::ErrorExpired:
- s = "Certificate has expired";
- break;
- case QCA::ErrorExpiredCA:
- s = "CA has expired";
- break;
- case QCA::ErrorValidityUnknown:
- default:
- s = "General certificate validation error";
- break;
- }
- return s;
+ QString s;
+ switch (v) {
+ case QCA::ValidityGood:
+ s = "Validated";
+ break;
+ case QCA::ErrorRejected:
+ s = "Root CA is marked to reject the specified purpose";
+ break;
+ case QCA::ErrorUntrusted:
+ s = "Certificate not trusted for the required purpose";
+ break;
+ case QCA::ErrorSignatureFailed:
+ s = "Invalid signature";
+ break;
+ case QCA::ErrorInvalidCA:
+ s = "Invalid CA certificate";
+ break;
+ case QCA::ErrorInvalidPurpose:
+ s = "Invalid certificate purpose";
+ break;
+ case QCA::ErrorSelfSigned:
+ s = "Certificate is self-signed";
+ break;
+ case QCA::ErrorRevoked:
+ s = "Certificate has been revoked";
+ break;
+ case QCA::ErrorPathLengthExceeded:
+ s = "Maximum certificate chain length exceeded";
+ break;
+ case QCA::ErrorExpired:
+ s = "Certificate has expired";
+ break;
+ case QCA::ErrorExpiredCA:
+ s = "CA has expired";
+ break;
+ case QCA::ErrorValidityUnknown:
+ default:
+ s = "General certificate validation error";
+ break;
+ }
+ return s;
}
class SecureTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SecureTest()
- {
- sock_done = false;
- ssl_done = false;
-
- sock = new QTcpSocket;
- connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
- connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
- connect(sock, SIGNAL(error(QAbstractSocket::SocketError)),
- SLOT(sock_error(QAbstractSocket::SocketError)));
-
- ssl = new QCA::TLS;
- connect(ssl, SIGNAL(certificateRequested()), SLOT(ssl_certificateRequested()));
- connect(ssl, SIGNAL(handshaken()), SLOT(ssl_handshaken()));
- connect(ssl, SIGNAL(readyRead()), SLOT(ssl_readyRead()));
- connect(ssl, SIGNAL(readyReadOutgoing()),
- SLOT(ssl_readyReadOutgoing()));
- connect(ssl, SIGNAL(closed()), SLOT(ssl_closed()));
- connect(ssl, SIGNAL(error()), SLOT(ssl_error()));
- }
-
- ~SecureTest()
- {
- delete ssl;
- delete sock;
- }
-
- void start(const QString &_host)
- {
- int n = _host.indexOf(':');
- int port;
- if(n != -1)
- {
- host = _host.mid(0, n);
- port = _host.mid(n+1).toInt();
- }
- else
- {
- host = _host;
- port = 443;
- }
-
- printf("Trying %s:%d...\n", qPrintable(host), port);
- sock->connectToHost(host, port);
- }
+ SecureTest()
+ {
+ sock_done = false;
+ ssl_done = false;
+
+ sock = new QTcpSocket;
+ connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
+ connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
+ connect(sock, SIGNAL(error(QAbstractSocket::SocketError)),
+ SLOT(sock_error(QAbstractSocket::SocketError)));
+
+ ssl = new QCA::TLS;
+ connect(ssl, SIGNAL(certificateRequested()), SLOT(ssl_certificateRequested()));
+ connect(ssl, SIGNAL(handshaken()), SLOT(ssl_handshaken()));
+ connect(ssl, SIGNAL(readyRead()), SLOT(ssl_readyRead()));
+ connect(ssl, SIGNAL(readyReadOutgoing()),
+ SLOT(ssl_readyReadOutgoing()));
+ connect(ssl, SIGNAL(closed()), SLOT(ssl_closed()));
+ connect(ssl, SIGNAL(error()), SLOT(ssl_error()));
+ }
+
+ ~SecureTest()
+ {
+ delete ssl;
+ delete sock;
+ }
+
+ void start(const QString &_host)
+ {
+ int n = _host.indexOf(':');
+ int port;
+ if (n != -1) {
+ host = _host.mid(0, n);
+ port = _host.mid(n + 1).toInt();
+ } else {
+ host = _host;
+ port = 443;
+ }
+
+ printf("Trying %s:%d...\n", qPrintable(host), port);
+ sock->connectToHost(host, port);
+ }
signals:
- void quit();
+ void quit();
private slots:
- void sock_connected()
- {
- // We just do this to help doxygen...
- QCA::TLS *ssl = SecureTest::ssl;
-
- printf("Connected, starting TLS handshake...\n");
-
- QCA::CertificateCollection rootCerts = QCA::systemStore();
-
- // We add this one to show how, and to make it work with
- // the server example.
- rootCerts.addCertificate(QCA::Certificate::fromPEM(exampleCA_cert));
-
- if(!QCA::haveSystemStore())
- printf("Warning: no root certs\n");
- else
- ssl->setTrustedCertificates(rootCerts);
-
- ssl->startClient(host);
- }
-
- void sock_readyRead()
- {
- // We just do this to help doxygen...
- QCA::TLS *ssl = SecureTest::ssl;
-
- ssl->writeIncoming(sock->readAll());
- }
-
- void sock_connectionClosed()
- {
- printf("\nConnection closed.\n");
- sock_done = true;
-
- if(ssl_done && sock_done)
- emit quit();
- }
-
- void sock_error(QAbstractSocket::SocketError x)
- {
- if(x == QAbstractSocket::RemoteHostClosedError)
- {
- sock_connectionClosed();
- return;
- }
-
- printf("\nSocket error.\n");
- emit quit();
- }
-
- void ssl_handshaken()
- {
- // We just do this to help doxygen...
- QCA::TLS *ssl = SecureTest::ssl;
-
- QCA::TLS::IdentityResult r = ssl->peerIdentityResult();
-
- printf("Successful SSL handshake using %s (%i of %i bits)\n",
- qPrintable(ssl->cipherSuite()),
- ssl->cipherBits(),
- ssl->cipherMaxBits() );
- if(r != QCA::TLS::NoCertificate)
- {
- cert = ssl->peerCertificateChain().primary();
- if(!cert.isNull())
- showCertInfo(cert);
- }
-
- QString str = "Peer Identity: ";
- if(r == QCA::TLS::Valid)
- str += "Valid";
- else if(r == QCA::TLS::HostMismatch)
- str += "Error: Wrong certificate";
- else if(r == QCA::TLS::InvalidCertificate)
- str += "Error: Invalid certificate.\n -> Reason: " +
- validityToString(ssl->peerCertificateValidity());
- else
- str += "Error: No certificate";
- printf("%s\n", qPrintable(str));
-
- ssl->continueAfterStep();
-
- printf("Let's try a GET request now.\n");
- QString req = "GET / HTTP/1.0\nHost: " + host + "\n\n";
- ssl->write(req.toLatin1());
- }
-
- void ssl_certificateRequested()
- {
- // We just do this to help doxygen...
- QCA::TLS *ssl = SecureTest::ssl;
-
- printf("Server requested client certificate.\n");
- QList<QCA::CertificateInfoOrdered> issuerList = ssl->issuerList();
- if(!issuerList.isEmpty())
- {
- printf("Allowed issuers:\n");
- foreach(QCA::CertificateInfoOrdered i, issuerList)
- printf(" %s\n", qPrintable(i.toString()));
- }
-
- ssl->continueAfterStep();
- }
-
- void ssl_readyRead()
- {
- // We just do this to help doxygen...
- QCA::TLS *ssl = SecureTest::ssl;
-
- QByteArray a = ssl->read();
- printf("%s", a.data());
- }
-
- void ssl_readyReadOutgoing()
- {
- // We just do this to help doxygen...
- QCA::TLS *ssl = SecureTest::ssl;
-
- sock->write(ssl->readOutgoing());
- }
-
- void ssl_closed()
- {
- printf("SSL session closed.\n");
- ssl_done = true;
-
- if(ssl_done && sock_done)
- emit quit();
- }
-
- void ssl_error()
- {
- // We just do this to help doxygen...
- QCA::TLS *ssl = SecureTest::ssl;
-
- int x = ssl->errorCode();
- if(x == QCA::TLS::ErrorHandshake)
- {
- printf("SSL Handshake Error!\n");
- emit quit();
- }
- else
- {
- printf("SSL Error!\n");
- emit quit();
- }
- }
+ void sock_connected()
+ {
+ // We just do this to help doxygen...
+ QCA::TLS *ssl = SecureTest::ssl;
+
+ printf("Connected, starting TLS handshake...\n");
+
+ QCA::CertificateCollection rootCerts = QCA::systemStore();
+
+ // We add this one to show how, and to make it work with
+ // the server example.
+ rootCerts.addCertificate(QCA::Certificate::fromPEM(exampleCA_cert));
+
+ if (!QCA::haveSystemStore()) {
+ printf("Warning: no root certs\n");
+ } else {
+ ssl->setTrustedCertificates(rootCerts);
+ }
+
+ ssl->startClient(host);
+ }
+
+ void sock_readyRead()
+ {
+ // We just do this to help doxygen...
+ QCA::TLS *ssl = SecureTest::ssl;
+
+ ssl->writeIncoming(sock->readAll());
+ }
+
+ void sock_connectionClosed()
+ {
+ printf("\nConnection closed.\n");
+ sock_done = true;
+
+ if (ssl_done && sock_done) {
+ emit quit();
+ }
+ }
+
+ void sock_error(QAbstractSocket::SocketError x)
+ {
+ if (x == QAbstractSocket::RemoteHostClosedError) {
+ sock_connectionClosed();
+ return;
+ }
+
+ printf("\nSocket error.\n");
+ emit quit();
+ }
+
+ void ssl_handshaken()
+ {
+ // We just do this to help doxygen...
+ QCA::TLS *ssl = SecureTest::ssl;
+
+ QCA::TLS::IdentityResult r = ssl->peerIdentityResult();
+
+ printf("Successful SSL handshake using %s (%i of %i bits)\n",
+ qPrintable(ssl->cipherSuite()),
+ ssl->cipherBits(),
+ ssl->cipherMaxBits());
+ if (r != QCA::TLS::NoCertificate) {
+ cert = ssl->peerCertificateChain().primary();
+ if (!cert.isNull()) {
+ showCertInfo(cert);
+ }
+ }
+
+ QString str = "Peer Identity: ";
+ if (r == QCA::TLS::Valid) {
+ str += "Valid";
+ } else if (r == QCA::TLS::HostMismatch) {
+ str += "Error: Wrong certificate";
+ } else if (r == QCA::TLS::InvalidCertificate)
+ str += "Error: Invalid certificate.\n -> Reason: " +
+ validityToString(ssl->peerCertificateValidity());
+ else {
+ str += "Error: No certificate";
+ }
+ printf("%s\n", qPrintable(str));
+
+ ssl->continueAfterStep();
+
+ printf("Let's try a GET request now.\n");
+ QString req = "GET / HTTP/1.0\nHost: " + host + "\n\n";
+ ssl->write(req.toLatin1());
+ }
+
+ void ssl_certificateRequested()
+ {
+ // We just do this to help doxygen...
+ QCA::TLS *ssl = SecureTest::ssl;
+
+ printf("Server requested client certificate.\n");
+ QList<QCA::CertificateInfoOrdered> issuerList = ssl->issuerList();
+ if (!issuerList.isEmpty()) {
+ printf("Allowed issuers:\n");
+ foreach (QCA::CertificateInfoOrdered i, issuerList) {
+ printf(" %s\n", qPrintable(i.toString()));
+ }
+ }
+
+ ssl->continueAfterStep();
+ }
+
+ void ssl_readyRead()
+ {
+ // We just do this to help doxygen...
+ QCA::TLS *ssl = SecureTest::ssl;
+
+ QByteArray a = ssl->read();
+ printf("%s", a.data());
+ }
+
+ void ssl_readyReadOutgoing()
+ {
+ // We just do this to help doxygen...
+ QCA::TLS *ssl = SecureTest::ssl;
+
+ sock->write(ssl->readOutgoing());
+ }
+
+ void ssl_closed()
+ {
+ printf("SSL session closed.\n");
+ ssl_done = true;
+
+ if (ssl_done && sock_done) {
+ emit quit();
+ }
+ }
+
+ void ssl_error()
+ {
+ // We just do this to help doxygen...
+ QCA::TLS *ssl = SecureTest::ssl;
+
+ int x = ssl->errorCode();
+ if (x == QCA::TLS::ErrorHandshake) {
+ printf("SSL Handshake Error!\n");
+ emit quit();
+ } else {
+ printf("SSL Error!\n");
+ emit quit();
+ }
+ }
private:
- QString host;
- QTcpSocket *sock;
- QCA::TLS *ssl;
- QCA::Certificate cert;
- bool sock_done, ssl_done;
+ QString host;
+ QTcpSocket *sock;
+ QCA::TLS *ssl;
+ QCA::Certificate cert;
+ bool sock_done, ssl_done;
};
#include "ssltest.moc"
int main(int argc, char **argv)
{
- QCA::Initializer init;
+ QCA::Initializer init;
- QCoreApplication app(argc, argv);
- QString host = argc > 1 ? argv[1] : "andbit.net";
+ QCoreApplication app(argc, argv);
+ QString host = argc > 1 ? argv[1] : "andbit.net";
- if(!QCA::isSupported("tls"))
- {
- printf("TLS not supported!\n");
- return 1;
- }
+ if (!QCA::isSupported("tls")) {
+ printf("TLS not supported!\n");
+ return 1;
+ }
- SecureTest *s = new SecureTest;
- QObject::connect(s, SIGNAL(quit()), &app, SLOT(quit()));
- s->start(host);
- app.exec();
- delete s;
+ SecureTest *s = new SecureTest;
+ QObject::connect(s, SIGNAL(quit()), &app, SLOT(quit()));
+ s->start(host);
+ app.exec();
+ delete s;
- return 0;
+ return 0;
}
diff --git a/examples/tlssocket/main.cpp b/examples/tlssocket/main.cpp
index 37bda41d..6d3b6ae8 100644
--- a/examples/tlssocket/main.cpp
+++ b/examples/tlssocket/main.cpp
@@ -1,38 +1,39 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "tlssocket.h"
#include <QCoreApplication>
int main(int argc, char **argv)
{
- QCA::Initializer init;
- QCoreApplication qapp(argc, argv);
+ QCA::Initializer init;
+ QCoreApplication qapp(argc, argv);
- TLSSocket socket;
- socket.connectToHostEncrypted("www.paypal.com", 443);
- socket.write("GET / HTTP/1.0\r\n\r\n");
- while(socket.waitForReadyRead())
- printf("%s", socket.readAll().data());
+ TLSSocket socket;
+ socket.connectToHostEncrypted("www.paypal.com", 443);
+ socket.write("GET / HTTP/1.0\r\n\r\n");
+ while (socket.waitForReadyRead()) {
+ printf("%s", socket.readAll().data());
+ }
- return 0;
+ return 0;
}
diff --git a/examples/tlssocket/tlssocket.cpp b/examples/tlssocket/tlssocket.cpp
index 40564d36..bb745304 100644
--- a/examples/tlssocket/tlssocket.cpp
+++ b/examples/tlssocket/tlssocket.cpp
@@ -1,217 +1,219 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "tlssocket.h"
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class TLSSocket::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- TLSSocket *q;
- QTcpSocket *sock;
- QCA::TLS *tls;
- QString host;
- bool encrypted;
- bool error, done;
- QByteArray readbuf, writebuf;
- QCA::Synchronizer sync;
- bool waiting;
-
- Private(TLSSocket *_q) : QObject(_q), q(_q), sync(_q)
- {
- sock = new QTcpSocket(this);
- connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
- connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
- connect(sock, SIGNAL(bytesWritten(qint64)), SLOT(sock_bytesWritten(qint64)));
- connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));
-
- tls = new QCA::TLS(this);
- connect(tls, SIGNAL(handshaken()), SLOT(tls_handshaken()));
- connect(tls, SIGNAL(readyRead()), SLOT(tls_readyRead()));
- connect(tls, SIGNAL(readyReadOutgoing()), SLOT(tls_readyReadOutgoing()));
- connect(tls, SIGNAL(closed()), SLOT(tls_closed()));
- connect(tls, SIGNAL(error()), SLOT(tls_error()));
- tls->setTrustedCertificates(QCA::systemStore());
- encrypted = false;
- error = false;
- waiting = false;
- done = false;
- }
-
- bool waitForReadyRead(int msecs)
- {
- waiting = true;
- bool ok = sync.waitForCondition(msecs);
- //while(1)
- // QCoreApplication::instance()->processEvents();
- waiting = false;
- if(error || done)
- return false;
- return ok;
- }
+ TLSSocket *q;
+ QTcpSocket *sock;
+ QCA::TLS *tls;
+ QString host;
+ bool encrypted;
+ bool error, done;
+ QByteArray readbuf, writebuf;
+ QCA::Synchronizer sync;
+ bool waiting;
+
+ Private(TLSSocket *_q) : QObject(_q), q(_q), sync(_q)
+ {
+ sock = new QTcpSocket(this);
+ connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
+ connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
+ connect(sock, SIGNAL(bytesWritten(qint64)), SLOT(sock_bytesWritten(qint64)));
+ connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(sock_error(QAbstractSocket::SocketError)));
+
+ tls = new QCA::TLS(this);
+ connect(tls, SIGNAL(handshaken()), SLOT(tls_handshaken()));
+ connect(tls, SIGNAL(readyRead()), SLOT(tls_readyRead()));
+ connect(tls, SIGNAL(readyReadOutgoing()), SLOT(tls_readyReadOutgoing()));
+ connect(tls, SIGNAL(closed()), SLOT(tls_closed()));
+ connect(tls, SIGNAL(error()), SLOT(tls_error()));
+ tls->setTrustedCertificates(QCA::systemStore());
+ encrypted = false;
+ error = false;
+ waiting = false;
+ done = false;
+ }
+
+ bool waitForReadyRead(int msecs)
+ {
+ waiting = true;
+ bool ok = sync.waitForCondition(msecs);
+ //while(1)
+ // QCoreApplication::instance()->processEvents();
+ waiting = false;
+ if (error || done) {
+ return false;
+ }
+ return ok;
+ }
private slots:
- void sock_connected()
- {
- //printf("sock connected\n");
- tls->startClient(host);
- }
-
- void sock_readyRead()
- {
- //printf("sock ready read\n");
- QByteArray buf = sock->readAll();
- //printf("%d bytes\n", buf.size());
- tls->writeIncoming(buf);
- }
-
- void sock_bytesWritten(qint64 x)
- {
- Q_UNUSED(x);
- //printf("sock bytes written: %d\n", (int)x);
- }
-
- void sock_error(QAbstractSocket::SocketError x)
- {
- //printf("sock error: %d\n", x);
- Q_UNUSED(x);
- done = true;
- if(waiting)
- sync.conditionMet();
- }
-
- void tls_handshaken()
- {
- //printf("tls handshaken\n");
- if(tls->peerIdentityResult() != QCA::TLS::Valid)
- {
- printf("not valid\n");
- sock->abort();
- tls->reset();
- error = true;
- }
- else
- {
- //printf("valid\n");
- encrypted = true;
- //printf("%d bytes in writebuf\n", writebuf.size());
- if(!writebuf.isEmpty())
- {
- //printf("[%s]\n", writebuf.data());
- tls->write(writebuf);
- writebuf.clear();
- }
- }
- if(waiting)
- sync.conditionMet();
- }
-
- void tls_readyRead()
- {
- //printf("tls ready read\n");
- if(waiting)
- sync.conditionMet();
- }
-
- void tls_readyReadOutgoing()
- {
- //printf("tls ready read outgoing\n");
- QByteArray buf = tls->readOutgoing();
- //printf("%d bytes\n", buf.size());
- sock->write(buf);
- }
-
- void tls_closed()
- {
- //printf("tls closed\n");
- }
-
- void tls_error()
- {
- //printf("tls error\n");
- }
+ void sock_connected()
+ {
+ //printf("sock connected\n");
+ tls->startClient(host);
+ }
+
+ void sock_readyRead()
+ {
+ //printf("sock ready read\n");
+ QByteArray buf = sock->readAll();
+ //printf("%d bytes\n", buf.size());
+ tls->writeIncoming(buf);
+ }
+
+ void sock_bytesWritten(qint64 x)
+ {
+ Q_UNUSED(x);
+ //printf("sock bytes written: %d\n", (int)x);
+ }
+
+ void sock_error(QAbstractSocket::SocketError x)
+ {
+ //printf("sock error: %d\n", x);
+ Q_UNUSED(x);
+ done = true;
+ if (waiting) {
+ sync.conditionMet();
+ }
+ }
+
+ void tls_handshaken()
+ {
+ //printf("tls handshaken\n");
+ if (tls->peerIdentityResult() != QCA::TLS::Valid) {
+ printf("not valid\n");
+ sock->abort();
+ tls->reset();
+ error = true;
+ } else {
+ //printf("valid\n");
+ encrypted = true;
+ //printf("%d bytes in writebuf\n", writebuf.size());
+ if (!writebuf.isEmpty()) {
+ //printf("[%s]\n", writebuf.data());
+ tls->write(writebuf);
+ writebuf.clear();
+ }
+ }
+ if (waiting) {
+ sync.conditionMet();
+ }
+ }
+
+ void tls_readyRead()
+ {
+ //printf("tls ready read\n");
+ if (waiting) {
+ sync.conditionMet();
+ }
+ }
+
+ void tls_readyReadOutgoing()
+ {
+ //printf("tls ready read outgoing\n");
+ QByteArray buf = tls->readOutgoing();
+ //printf("%d bytes\n", buf.size());
+ sock->write(buf);
+ }
+
+ void tls_closed()
+ {
+ //printf("tls closed\n");
+ }
+
+ void tls_error()
+ {
+ //printf("tls error\n");
+ }
};
TLSSocket::TLSSocket(QObject *parent)
-:QTcpSocket(parent)
+ : QTcpSocket(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
TLSSocket::~TLSSocket()
{
- delete d;
+ delete d;
}
void TLSSocket::connectToHostEncrypted(const QString &host, quint16 port)
{
- d->host = host;
- setOpenMode(QIODevice::ReadWrite);
- d->sock->connectToHost(host, port);
+ d->host = host;
+ setOpenMode(QIODevice::ReadWrite);
+ d->sock->connectToHost(host, port);
}
QCA::TLS *TLSSocket::tls()
{
- return d->tls;
+ return d->tls;
}
bool TLSSocket::waitForReadyRead(int msecs)
{
- /*if(d->readbuf.isEmpty())
- return false;
+ /*if(d->readbuf.isEmpty())
+ return false;
- if(d->tls->bytesAvailable() == 0)
- return false;*/
+ if(d->tls->bytesAvailable() == 0)
+ return false;*/
- return d->waitForReadyRead(msecs);
+ return d->waitForReadyRead(msecs);
}
qint64 TLSSocket::readData(char *data, qint64 maxlen)
{
- if(!d->error)
- d->readbuf += d->tls->read();
- unsigned char *p = (unsigned char *)d->readbuf.data();
- int size = d->readbuf.size();
- int readsize = qMin(size, (int)maxlen);
- int newsize = size - readsize;
- memcpy(data, p, readsize);
- memmove(p, p + readsize, newsize);
- d->readbuf.resize(newsize);
- return readsize;
+ if (!d->error) {
+ d->readbuf += d->tls->read();
+ }
+ unsigned char *p = (unsigned char *)d->readbuf.data();
+ int size = d->readbuf.size();
+ int readsize = qMin(size, (int)maxlen);
+ int newsize = size - readsize;
+ memcpy(data, p, readsize);
+ memmove(p, p + readsize, newsize);
+ d->readbuf.resize(newsize);
+ return readsize;
}
qint64 TLSSocket::writeData(const char *data, qint64 len)
{
- //printf("write %d bytes\n", (int)len);
- QByteArray buf(data, len);
- if(d->encrypted)
- d->tls->write(buf);
- else
- d->writebuf += buf;
- return len;
+ //printf("write %d bytes\n", (int)len);
+ QByteArray buf(data, len);
+ if (d->encrypted) {
+ d->tls->write(buf);
+ } else {
+ d->writebuf += buf;
+ }
+ return len;
}
#include "tlssocket.moc"
diff --git a/examples/tlssocket/tlssocket.h b/examples/tlssocket/tlssocket.h
index 70f79d43..6f597f07 100644
--- a/examples/tlssocket/tlssocket.h
+++ b/examples/tlssocket/tlssocket.h
@@ -1,49 +1,49 @@
/*
Copyright (C) 2007 Justin Karneges <justin@affinix.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef TLSSOCKET_H
#include <QtCrypto>
#include <QTcpSocket>
class TLSSocket : public QTcpSocket
{
public:
- TLSSocket(QObject *parent = 0);
- ~TLSSocket();
+ TLSSocket(QObject *parent = 0);
+ ~TLSSocket();
- void connectToHostEncrypted(const QString &host, quint16 port);
- QCA::TLS *tls();
+ void connectToHostEncrypted(const QString &host, quint16 port);
+ QCA::TLS *tls();
- bool waitForReadyRead(int msecs = -1);
+ bool waitForReadyRead(int msecs = -1);
protected:
- // from qiodevice
- virtual qint64 readData(char *data, qint64 maxlen);
- virtual qint64 writeData(const char *data, qint64 len);
+ // from qiodevice
+ virtual qint64 readData(char *data, qint64 maxlen);
+ virtual qint64 writeData(const char *data, qint64 len);
private:
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
#endif
diff --git a/include/QtCrypto/qca_basic.h b/include/QtCrypto/qca_basic.h
index 4e1b0da5..2894ef10 100644
--- a/include/QtCrypto/qca_basic.h
+++ b/include/QtCrypto/qca_basic.h
@@ -1,1140 +1,1139 @@
/*
* qca_basic.h - Qt Cryptographic Architecture
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004-2007 Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2013-2016 Ivan Romanov <drizt@land.ru>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_basic.h
Header file for classes for cryptographic primitives (basic operations).
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_BASIC_H
#define QCA_BASIC_H
#include "qca_core.h"
#include <QIODevice>
// Qt5 comes with QStringLiteral for wrapping string literals, which Qt4 does
// not have. It is needed if the headers are built with QT_NO_CAST_FROM_ASCII.
// Defining it here as QString::fromUtf8 for convenience.
#ifndef QStringLiteral
#define QStringLiteral(str) QString::fromUtf8(str)
#endif
-namespace QCA {
+namespace QCA
+{
/**
\defgroup UserAPI QCA user API
This is the main set of QCA classes, intended for use
in standard applications.
*/
/**
\class Random qca_basic.h QtCrypto
Source of random numbers.
QCA provides a built in source of random numbers, which
can be accessed through this class. You can also use
an alternative random number source, by implementing
another provider.
The normal use of this class is expected to be through the
static members - randomChar(), randomInt() and randomArray().
\ingroup UserAPI
*/
class QCA_EXPORT Random : public Algorithm
{
public:
- /**
- Standard Constructor
+ /**
+ Standard Constructor
- \param provider the name of the provider library for the random
+ \param provider the name of the provider library for the random
number generation
- */
- Random(const QString &provider = QString());
+ */
+ Random(const QString &provider = QString());
- /**
- Copy constructor
+ /**
+ Copy constructor
- \param from the %Random object to copy from
+ \param from the %Random object to copy from
*/
- Random(const Random &from);
+ Random(const Random &from);
- ~Random();
+ ~Random();
- /**
- Assignment operator
+ /**
+ Assignment operator
- \param from the %Random object to copy state from
- */
- Random & operator=(const Random &from);
+ \param from the %Random object to copy state from
+ */
+ Random &operator=(const Random &from);
- /**
- Provide a random byte.
+ /**
+ Provide a random byte.
- This method isn't normally required - you should use
- the static randomChar() method instead.
+ This method isn't normally required - you should use
+ the static randomChar() method instead.
- \sa randomChar
- */
- uchar nextByte();
+ \sa randomChar
+ */
+ uchar nextByte();
- /**
- Provide a specified number of random bytes.
+ /**
+ Provide a specified number of random bytes.
- This method isn't normally required - you should use
- the static randomArray() method instead.
+ This method isn't normally required - you should use
+ the static randomArray() method instead.
- \param size the number of bytes to provide
+ \param size the number of bytes to provide
- \sa randomArray
- */
- SecureArray nextBytes(int size);
+ \sa randomArray
+ */
+ SecureArray nextBytes(int size);
- /**
- Provide a random character (byte)
+ /**
+ Provide a random character (byte)
- This is the normal way of obtaining a single random char
- (ie. 8 bit byte), as shown below:
- \code
-myRandomChar = QCA::Random::randomChar();
- \endcode
+ This is the normal way of obtaining a single random char
+ (ie. 8 bit byte), as shown below:
+ \code
+ myRandomChar = QCA::Random::randomChar();
+ \endcode
- If you need a number of bytes, perhaps randomArray() may be of use.
- */
- static uchar randomChar();
+ If you need a number of bytes, perhaps randomArray() may be of use.
+ */
+ static uchar randomChar();
- /**
- Provide a random integer.
+ /**
+ Provide a random integer.
- This is the normal way of obtaining a single random integer,
- as shown below:
- \code
-myRandomInt = QCA::Random::randomInt();
- \endcode
- */
- static int randomInt();
+ This is the normal way of obtaining a single random integer,
+ as shown below:
+ \code
+ myRandomInt = QCA::Random::randomInt();
+ \endcode
+ */
+ static int randomInt();
- /**
- Provide a specified number of random bytes.
+ /**
+ Provide a specified number of random bytes.
- \code
-// build a 30 byte secure array.
-SecureArray arry = QCA::Random::randomArray(30);
- \endcode
+ \code
+ // build a 30 byte secure array.
+ SecureArray arry = QCA::Random::randomArray(30);
+ \endcode
- \param size the number of bytes to provide
- */
- static SecureArray randomArray(int size);
+ \param size the number of bytes to provide
+ */
+ static SecureArray randomArray(int size);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class Hash qca_basic.h QtCrypto
General class for hashing algorithms.
Hash is the class for the various hashing algorithms
within %QCA. SHA256, SHA1 or RIPEMD160 are recommended for
new applications, although MD2, MD4, MD5 or SHA0 may be
applicable (for interoperability reasons) for some
applications.
To perform a hash, you create a Hash object, call update()
with the data that needs to be hashed, and then call
final(), which returns a QByteArray of the hash result. An
example (using the SHA1 hash, with 1000 updates of a 1000
byte string) is shown below:
\code
if(!QCA::isSupported("sha1"))
- printf("SHA1 not supported!\n");
+ printf("SHA1 not supported!\n");
else
{
- QByteArray fillerString;
- fillerString.fill('a', 1000);
-
- QCA::Hash shaHash("sha1");
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QByteArray hashResult = shaHash.final();
- if ( "34aa973cd4c4daa4f61eeb2bdbad27316534016f" == QCA::arrayToHex(hashResult) )
- {
- printf("big SHA1 is OK\n");
- }
- else
- {
- printf("big SHA1 failed\n");
- }
+ QByteArray fillerString;
+ fillerString.fill('a', 1000);
+
+ QCA::Hash shaHash("sha1");
+ for (int i=0; i<1000; i++)
+ shaHash.update(fillerString);
+ QByteArray hashResult = shaHash.final();
+ if ( "34aa973cd4c4daa4f61eeb2bdbad27316534016f" == QCA::arrayToHex(hashResult) )
+ {
+ printf("big SHA1 is OK\n");
+ }
+ else
+ {
+ printf("big SHA1 failed\n");
+ }
}
\endcode
If you only have a simple hash requirement - a single
string that is fully available in memory at one time - then
you may be better off with one of the convenience
methods. So, for example, instead of creating a QCA::Hash
object, then doing a single update() and the final() call;
you could simply call QCA::Hash("algoName").hash() with the
data that you would otherwise have provided to the update()
call.
For more information on hashing algorithms, see \ref hashing.
\ingroup UserAPI
*/
class QCA_EXPORT Hash : public Algorithm, public BufferedComputation
{
public:
- /**
- Constructor
+ /**
+ Constructor
- \param type label for the type of hash to be
- created (for example, "sha1" or "md2")
- \param provider the name of the provider plugin
- for the subclass (eg "qca-ossl")
- */
- explicit Hash(const QString &type, const QString &provider = QString());
+ \param type label for the type of hash to be
+ created (for example, "sha1" or "md2")
+ \param provider the name of the provider plugin
+ for the subclass (eg "qca-ossl")
+ */
+ explicit Hash(const QString &type, const QString &provider = QString());
- /**
- Copy constructor
+ /**
+ Copy constructor
- \param from the Hash object to copy from
+ \param from the Hash object to copy from
*/
- Hash(const Hash &from);
+ Hash(const Hash &from);
- ~Hash();
+ ~Hash();
- /**
- Assignment operator
+ /**
+ Assignment operator
- \param from the Hash object to copy state from
+ \param from the Hash object to copy state from
*/
- Hash & operator=(const Hash &from);
-
- /**
- Returns a list of all of the hash types available
-
- \param provider the name of the provider to get a list from, if one
- provider is required. If not specified, available hash types from all
- providers will be returned.
- */
- static QStringList supportedTypes(const QString &provider = QString());
-
- /**
- Return the hash type
- */
- QString type() const;
-
- /**
- Reset a hash, dumping all previous parts of the
- message.
-
- This method clears (or resets) the hash algorithm,
- effectively undoing any previous update()
- calls. You should use this call if you are re-using
- a Hash sub-class object to calculate additional
- hashes.
- */
- virtual void clear();
-
- /**
- Update a hash, adding more of the message contents
- to the digest. The whole message needs to be added
- using this method before you call final().
-
- If you find yourself only calling update() once,
- you may be better off using a convenience method
- such as hash() or hashToString() instead.
-
- \param a the byte array to add to the hash
- */
- virtual void update(const MemoryRegion &a);
-
- /**
- \overload
-
- \param a the QByteArray to add to the hash
- */
- void update(const QByteArray &a);
-
- /**
- \overload
-
- This method is provided to assist with code that
- already exists, and is being ported to %QCA. You are
- better off passing a SecureArray (as shown above)
- if you are writing new code.
-
- \param data pointer to a char array
- \param len the length of the array. If not specified
- (or specified as a negative number), the length will be
- determined with strlen(), which may not be what you want
- if the array contains a null (0x00) character.
- */
- void update(const char *data, int len = -1);
-
- /**
- \overload
-
- This allows you to read from a file or other
- I/O device. Note that the device must be already
- open for reading
-
- \param file an I/O device
-
- If you are trying to calculate the hash of
- a whole file (and it isn't already open), you
- might want to use code like this:
- \code
-QFile f( "file.dat" );
-if ( f.open( QIODevice::ReadOnly ) )
-{
- QCA::Hash hashObj("sha1");
- hashObj.update( &f );
- QByteArray output = hashObj.final().toByteArray();
-}
- \endcode
- */
- void update(QIODevice *file);
-
- /**
- Finalises input and returns the hash result
-
- After calling update() with the required data, the
- hash results are finalised and produced.
-
- Note that it is not possible to add further data (with
- update()) after calling final(), because of the way
- the hashing works - null bytes are inserted to pad
- the results up to a fixed size. If you want to
- reuse the Hash object, you should call clear() and
- start to update() again.
- */
- virtual MemoryRegion final();
-
- /**
- %Hash a byte array, returning it as another
- byte array
-
- This is a convenience method that returns the
- hash of a SecureArray.
-
- \code
-SecureArray sampleArray(3);
-sampleArray.fill('a');
-SecureArray outputArray = QCA::Hash("md2")::hash(sampleArray);
- \endcode
-
- \param array the QByteArray to hash
-
- If you need more flexibility (e.g. you are constructing
- a large byte array object just to pass it to hash(), then
- consider creating an Hash object, and then calling
- update() and final().
- */
- MemoryRegion hash(const MemoryRegion &array);
-
- /**
- %Hash a byte array, returning it as a printable
- string
-
- This is a convenience method that returns the
- hash of a SecureArray as a hexadecimal
- representation encoded in a QString.
-
- \param array the QByteArray to hash
-
- If you need more flexibility, you can create a Hash
- object, call Hash::update() as required, then call
- Hash::final(), before using the static arrayToHex() method.
- */
- QString hashToString(const MemoryRegion &array);
+ Hash &operator=(const Hash &from);
+
+ /**
+ Returns a list of all of the hash types available
+
+ \param provider the name of the provider to get a list from, if one
+ provider is required. If not specified, available hash types from all
+ providers will be returned.
+ */
+ static QStringList supportedTypes(const QString &provider = QString());
+
+ /**
+ Return the hash type
+ */
+ QString type() const;
+
+ /**
+ Reset a hash, dumping all previous parts of the
+ message.
+
+ This method clears (or resets) the hash algorithm,
+ effectively undoing any previous update()
+ calls. You should use this call if you are re-using
+ a Hash sub-class object to calculate additional
+ hashes.
+ */
+ virtual void clear();
+
+ /**
+ Update a hash, adding more of the message contents
+ to the digest. The whole message needs to be added
+ using this method before you call final().
+
+ If you find yourself only calling update() once,
+ you may be better off using a convenience method
+ such as hash() or hashToString() instead.
+
+ \param a the byte array to add to the hash
+ */
+ virtual void update(const MemoryRegion &a);
+
+ /**
+ \overload
+
+ \param a the QByteArray to add to the hash
+ */
+ void update(const QByteArray &a);
+
+ /**
+ \overload
+
+ This method is provided to assist with code that
+ already exists, and is being ported to %QCA. You are
+ better off passing a SecureArray (as shown above)
+ if you are writing new code.
+
+ \param data pointer to a char array
+ \param len the length of the array. If not specified
+ (or specified as a negative number), the length will be
+ determined with strlen(), which may not be what you want
+ if the array contains a null (0x00) character.
+ */
+ void update(const char *data, int len = -1);
+
+ /**
+ \overload
+
+ This allows you to read from a file or other
+ I/O device. Note that the device must be already
+ open for reading
+
+ \param file an I/O device
+
+ If you are trying to calculate the hash of
+ a whole file (and it isn't already open), you
+ might want to use code like this:
+ \code
+ QFile f( "file.dat" );
+ if ( f.open( QIODevice::ReadOnly ) )
+ {
+ QCA::Hash hashObj("sha1");
+ hashObj.update( &f );
+ QByteArray output = hashObj.final().toByteArray();
+ }
+ \endcode
+ */
+ void update(QIODevice *file);
+
+ /**
+ Finalises input and returns the hash result
+
+ After calling update() with the required data, the
+ hash results are finalised and produced.
+
+ Note that it is not possible to add further data (with
+ update()) after calling final(), because of the way
+ the hashing works - null bytes are inserted to pad
+ the results up to a fixed size. If you want to
+ reuse the Hash object, you should call clear() and
+ start to update() again.
+ */
+ virtual MemoryRegion final();
+
+ /**
+ %Hash a byte array, returning it as another
+ byte array
+
+ This is a convenience method that returns the
+ hash of a SecureArray.
+
+ \code
+ SecureArray sampleArray(3);
+ sampleArray.fill('a');
+ SecureArray outputArray = QCA::Hash("md2")::hash(sampleArray);
+ \endcode
+
+ \param array the QByteArray to hash
+
+ If you need more flexibility (e.g. you are constructing
+ a large byte array object just to pass it to hash(), then
+ consider creating an Hash object, and then calling
+ update() and final().
+ */
+ MemoryRegion hash(const MemoryRegion &array);
+
+ /**
+ %Hash a byte array, returning it as a printable
+ string
+
+ This is a convenience method that returns the
+ hash of a SecureArray as a hexadecimal
+ representation encoded in a QString.
+
+ \param array the QByteArray to hash
+
+ If you need more flexibility, you can create a Hash
+ object, call Hash::update() as required, then call
+ Hash::final(), before using the static arrayToHex() method.
+ */
+ QString hashToString(const MemoryRegion &array);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\page hashing Hashing Algorithms
There are a range of hashing algorithms available in
%QCA. Hashing algorithms are used with the Hash and
MessageAuthenticationCode classes.
The MD2 algorithm takes an arbitrary data stream, known as the
message and outputs a condensed 128 bit (16 byte)
representation of that data stream, known as the message
digest. This algorithm is considered slightly more secure than MD5,
but is more expensive to compute. Unless backward
compatibility or interoperability are considerations, you
are better off using the SHA1 or RIPEMD160 hashing algorithms.
For more information on %MD2, see B. Kalinski RFC1319 "The %MD2
Message-Digest Algorithm". The label for MD2 is "md2".
The MD4 algorithm takes an arbitrary data stream, known as the
message and outputs a condensed 128 bit (16 byte)
representation of that data stream, known as the message
digest. MD4 is not considered to be secure, based on
known attacks. It should only be used for applications where
collision attacks are not a consideration (for example, as
used in the rsync algorithm for fingerprinting blocks of
data). If a secure hash is required, you are better off using
the SHA1 or RIPEMD160 hashing algorithms. MD2 and MD5 are both
stronger 128 bit hashes. For more information on MD4, see
R. Rivest RFC1320 "The %MD4 Message-Digest Algorithm". The
label for MD4 is "md4".
The MD5 takes an arbitrary data stream, known as the message
and outputs a condensed 128 bit (16 byte) representation of
that data stream, known as the message digest. MD5 is not
considered to be secure, based on known attacks. It should
only be used for applications where collision attacks are not
a consideration. If a secure hash is required, you are better
off using the SHA1 or RIPEMD160 hashing algorithms. For more
information on MD5, see R. Rivest RFC1321 "The %MD5
Message-Digest Algorithm". The label for MD5 is "md5".
The RIPEMD160 algorithm takes an arbitrary data stream, known
as the message (up to \f$2^{64}\f$ bits in length) and outputs
a condensed 160 bit (20 byte) representation of that data
stream, known as the message digest. The RIPEMD160 algorithm
is considered secure in that it is considered computationally
infeasible to find the message that produced the message
digest. The label for RIPEMD160 is "ripemd160".
The SHA-0 algorithm is a 160 bit hashing function, no longer
recommended for new applications because of known (partial)
attacks against it. The label for SHA-0 is "sha0".
The SHA-1 algorithm takes an arbitrary data stream, known as
the message (up to \f$2^{64}\f$ bits in length) and outputs a
condensed 160 bit (20 byte) representation of that data
stream, known as the message digest. SHA-1 is considered
secure in that it is considered computationally infeasible to
find the message that produced the message digest. For more
information on the SHA-1 algorithm,, see Federal Information
Processing Standard Publication 180-2 "Specifications for the
Secure %Hash Standard", available from
http://csrc.nist.gov/publications/. The label for SHA-1 is
"sha1".
The SHA-224 algorithm takes an arbitrary data stream, known as
the message (up to \f$2^{64}\f$ bits in length) and outputs a
condensed 224 bit (28 byte) representation of that data
stream, known as the message digest. SHA-224 is a "cut down"
version of SHA-256, and you may be better off using SHA-256 in
new designs. The SHA-224 algorithm is considered secure in
that it is considered computationally infeasible to find the
message that produced the message digest. For more information
on SHA-224, see Federal Information Processing Standard
Publication 180-2 "Specifications for the Secure %Hash
Standard", with change notice 1, available from
http://csrc.nist.gov/publications/. The label for SHA-224 is
"sha224".
The SHA-256 algorithm takes an arbitrary data stream, known as
the message (up to \f$2^{64}\f$ bits in length) and outputs a
condensed 256 bit (32 byte) representation of that data
stream, known as the message digest. The SHA-256 algorithm is
considered secure in that it is considered computationally
infeasible to find the message that produced the message
digest. For more information on SHA-256, see Federal
Information Processing Standard Publication 180-2
"Specifications for the Secure %Hash Standard", available from
http://csrc.nist.gov/publications/. The label for SHA-256 is
"sha256".
The SHA-384 algorithm takes an arbitrary data stream, known as
the message (up to \f$2^{128}\f$ bits in length) and outputs a
condensed 384 bit (48 byte) representation of that data
stream, known as the message digest. The SHA-384 algorithm is
a "cut down" version of SHA-512, and you may be better off
using SHA-512 in new designs. The SHA-384 algorithm is
considered secure in that it is considered computationally
infeasible to find the message that produced the message
digest. For more information on SHA-384, see Federal
Information Processing Standard Publication 180-2
"Specifications for the Secure %Hash Standard", available from
http://csrc.nist.gov/publications/. The label for SHA-384 is
"sha384".
The SHA-512 algorithm takes an arbitrary data stream, known as
the message (up to \f$2^{128}\f$ bits in length) and outputs a
condensed 512 bit (64 byte) representation of that data
stream, known as the message digest. The SHA-512 algorithm is
considered secure in that it is considered computationally
infeasible to find the message that produced the message
digest. For more information on SHA-512, see Federal
Information Processing Standard Publication 180-2
"Specifications for the Secure %Hash Standard", available from
http://csrc.nist.gov/publications/. The label for SHA-512 is
"sha512".
The Whirlpool algorithm takes an arbitrary data stream, known as
the message (up to \f$2^{256}\f$ bits in length) and outputs a
condensed 512 bit (64 byte) representation of that data
stream, known as the message digest. The Whirlpool algorithm is
considered secure in that it is considered computationally
infeasible to find the message that produced the message
- digest. For more information on Whirlpool, see
+ digest. For more information on Whirlpool, see
http://paginas.terra.com.br/informatica/paulobarreto/WhirlpoolPage.html
or ISO/IEC 10118-3:2004. The label for Whirlpool is
"whirlpool".
*/
/**
\page paddingDescription Padding
For those Cipher sub-classes that are block based, there are modes
that require a full block on encryption and decryption - %Cipher Block
Chaining mode and Electronic Code Book modes are good examples.
Since real world messages are not always a convenient multiple of a
block size, we have to adding <i>padding</i>. There are a number of
padding modes that %QCA supports, including not doing any padding
at all.
- If you are not going to use padding, then you can pass
+ If you are not going to use padding, then you can pass
QCA::Cipher::NoPadding as the pad argument to the Cipher sub-class,
however it is then your responsibility to pass in appropriate data for
the mode that you are using.
The most common padding scheme is known as PKCS#7 (also PKCS#1), and
- it specifies that the pad bytes are all equal to the length of the
+ it specifies that the pad bytes are all equal to the length of the
padding ( for example, if you need three pad bytes to complete the block,
then the padding is 0x03 0x03 0x03 ). PKCS#5 padding is a subset of
PKCS#7 padding for 8 byte block sizes. For explanation, see
http://crypto.stackexchange.com/questions/9043/what-is-the-difference-between-pkcs5-padding-and-pkcs7-padding/9044#9044.
On encryption, for algorithm / mode combinations that require
padding, you will get a block of ciphertext when the input plain
text block is complete. When you call final(), you will get out the
ciphertext that corresponds to the last part of the plain text,
plus any padding. If you had provided plaintext that matched up
with a block size, then the cipher text block is generated from
pure padding - you always get at least some padding, to ensure that
the padding can be safely removed on decryption.
On decryption, for algorithm / mode combinations that use padding,
you will get back a block of plaintext when the input ciphertext block
is complete. When you call final(), you will get a block that has been
stripped of ciphertext.
*/
/**
\class Cipher qca_basic.h QtCrypto
General class for cipher (encryption / decryption) algorithms.
Cipher is the class for the various algorithms that perform
low level encryption and decryption within %QCA.
AES128, AES192 and AES256 are recommended for new applications.
Standard names for ciphers are:
- Blowfish - "blowfish"
- TripleDES - "tripledes"
- DES - "des"
- AES128 - "aes128"
- AES192 - "aes192"
- AES256 - "aes256"
- CAST5 (CAST-128) - "cast5"
When checking for the availability of a particular kind
of cipher operation (e.g. AES128 in CBC mode with PKCS7
padding), you append the mode and padding type (in that
example "aes128-cbc-pkcs7"). CFB and OFB modes don't use
padding, so they are always just the cipher name followed
by the mode (e.g. "blowfish-cfb" or "aes192-ofb"). If
you are not using padding with CBC mode (i.e. you are
- ensuring block size operations yourself), just use
+ ensuring block size operations yourself), just use
the cipher name followed by "-cbc" (e.g. "blowfish-cbc"
- or "aes256-cbc").
+ or "aes256-cbc").
\ingroup UserAPI
*/
class QCA_EXPORT Cipher : public Algorithm, public Filter
{
public:
- /**
- Mode settings for cipher algorithms.
-
- \note ECB is almost never what you want, unless you
- are trying to implement a %Cipher variation that is not
- supported by %QCA.
- */
- enum Mode
- {
- CBC, ///< operate in %Cipher Block Chaining mode
- CFB, ///< operate in %Cipher FeedBack mode
- ECB, ///< operate in Electronic Code Book mode
- OFB, ///< operate in Output FeedBack Mode
- CTR, ///< operate in CounTer Mode
- GCM, ///< operate in Galois Counter Mode
- CCM ///< operate in Counter with CBC-MAC
- };
-
- /**
- Padding variations for cipher algorithms.
-
- See the \ref paddingDescription description for more details on
- padding schemes.
- */
- enum Padding
- {
- DefaultPadding, ///< Default for cipher-mode
- NoPadding, ///< Do not use padding
- PKCS7 ///< Pad using the scheme in PKCS#7
- };
-
- /**
- Standard constructor
-
- \param type the name of the cipher specialisation to use (e.g.
- "aes128")
- \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
- \param pad the type of Padding to use
- \param dir the Direction that this Cipher should use (Encode for
- encryption, Decode for decryption)
- \param key the SymmetricKey array that is the key
- \param iv the InitializationVector to use (not used for ECB mode)
- \param provider the name of the Provider to use
-
- \note Padding only applies to CBC and ECB modes. CFB and OFB
- ciphertext is always the length of the plaintext.
- */
- Cipher(const QString &type, Mode mode, Padding pad = DefaultPadding,
- Direction dir = Encode, const SymmetricKey &key = SymmetricKey(),
- const InitializationVector &iv = InitializationVector(),
- const QString &provider = QString());
-
- /**
- Standard constructor
-
- \param type the name of the cipher specialisation to use (e.g.
- "aes128")
- \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
- \param pad the type of Padding to use
- \param dir the Direction that this Cipher should use (Encode for
- encryption, Decode for decryption)
- \param key the SymmetricKey array that is the key
- \param iv the InitializationVector to use (not used for ECB mode)
- \param tag the AuthTag to use (only for GCM and CCM modes)
- \param provider the name of the Provider to use
-
- \note Padding only applies to CBC and ECB modes. CFB and OFB
- ciphertext is always the length of the plaintext.
- */
- Cipher(const QString &type, Mode mode, Padding pad,
- Direction dir, const SymmetricKey &key,
- const InitializationVector &iv, const AuthTag &tag,
- const QString &provider = QString());
-
- /**
- Standard copy constructor
-
- \param from the Cipher to copy state from
- */
- Cipher(const Cipher &from);
-
- ~Cipher();
-
- /**
- Assignment operator
-
- \param from the Cipher to copy state from
- */
- Cipher & operator=(const Cipher &from);
-
- /**
- Returns a list of all of the cipher types available
-
- \param provider the name of the provider to get a list from, if one
- provider is required. If not specified, available cipher types from all
- providers will be returned.
- */
- static QStringList supportedTypes(const QString &provider = QString());
-
- /**
- Return the cipher type
- */
- QString type() const;
-
- /**
- Return the cipher mode
- */
- Mode mode() const;
-
- /**
- Return the cipher padding type
- */
- Padding padding() const;
-
- /**
- Return the cipher direction
- */
- Direction direction() const;
-
- /**
- Return acceptable key lengths
- */
- KeyLength keyLength() const;
-
- /**
- Test if a key length is valid for the cipher algorithm
-
- \param n the key length in bytes
- \return true if the key would be valid for the current algorithm
- */
- bool validKeyLength(int n) const;
-
- /**
- return the block size for the cipher object
- */
- int blockSize() const;
-
- /**
- return the authentication tag for the cipher object
- */
- AuthTag tag() const;
-
- /**
- reset the cipher object, to allow re-use
- */
- virtual void clear();
-
- /**
- pass in a byte array of data, which will be encrypted or decrypted
- (according to the Direction that was set in the constructor or in
- setup() ) and returned.
-
- \param a the array of data to encrypt / decrypt
- */
- virtual MemoryRegion update(const MemoryRegion &a);
-
- /**
- complete the block of data, padding as required, and returning
- the completed block
- */
- virtual MemoryRegion final();
-
- /**
- Test if an update() or final() call succeeded.
-
- \return true if the previous call succeeded
- */
- virtual bool ok() const;
-
- /**
- Reset / reconfigure the Cipher
-
- You can use this to re-use an existing Cipher, rather than creating
- a new object with a slightly different configuration.
-
- \param dir the Direction that this Cipher should use (Encode for
- encryption, Decode for decryption)
- \param key the SymmetricKey array that is the key
- \param iv the InitializationVector to use (not used for ECB Mode)
-
- \note You should not leave iv empty for any Mode except ECB.
- */
- void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv = InitializationVector());
-
- /**
- Reset / reconfigure the Cipher
-
- You can use this to re-use an existing Cipher, rather than creating
- a new object with a slightly different configuration.
-
- \param dir the Direction that this Cipher should use (Encode for
- encryption, Decode for decryption)
- \param key the SymmetricKey array that is the key
- \param iv the InitializationVector to use (not used for ECB Mode)
- \param tag the AuthTag to use (only for GCM and CCM modes)
-
- \note You should not leave iv empty for any Mode except ECB.
- */
- void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag);
-
- /**
- Construct a Cipher type string
-
- \param cipherType the name of the algorithm (eg AES128, DES)
- \param modeType the mode to operate the cipher in (eg QCA::CBC,
- QCA::CFB)
- \param paddingType the padding required (eg QCA::NoPadding,
- QCA::PCKS7)
- */
- static QString withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType);
+ /**
+ Mode settings for cipher algorithms.
+
+ \note ECB is almost never what you want, unless you
+ are trying to implement a %Cipher variation that is not
+ supported by %QCA.
+ */
+ enum Mode {
+ CBC, ///< operate in %Cipher Block Chaining mode
+ CFB, ///< operate in %Cipher FeedBack mode
+ ECB, ///< operate in Electronic Code Book mode
+ OFB, ///< operate in Output FeedBack Mode
+ CTR, ///< operate in CounTer Mode
+ GCM, ///< operate in Galois Counter Mode
+ CCM ///< operate in Counter with CBC-MAC
+ };
+
+ /**
+ Padding variations for cipher algorithms.
+
+ See the \ref paddingDescription description for more details on
+ padding schemes.
+ */
+ enum Padding {
+ DefaultPadding, ///< Default for cipher-mode
+ NoPadding, ///< Do not use padding
+ PKCS7 ///< Pad using the scheme in PKCS#7
+ };
+
+ /**
+ Standard constructor
+
+ \param type the name of the cipher specialisation to use (e.g.
+ "aes128")
+ \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
+ \param pad the type of Padding to use
+ \param dir the Direction that this Cipher should use (Encode for
+ encryption, Decode for decryption)
+ \param key the SymmetricKey array that is the key
+ \param iv the InitializationVector to use (not used for ECB mode)
+ \param provider the name of the Provider to use
+
+ \note Padding only applies to CBC and ECB modes. CFB and OFB
+ ciphertext is always the length of the plaintext.
+ */
+ Cipher(const QString &type, Mode mode, Padding pad = DefaultPadding,
+ Direction dir = Encode, const SymmetricKey &key = SymmetricKey(),
+ const InitializationVector &iv = InitializationVector(),
+ const QString &provider = QString());
+
+ /**
+ Standard constructor
+
+ \param type the name of the cipher specialisation to use (e.g.
+ "aes128")
+ \param mode the operating Mode to use (e.g. QCA::Cipher::CBC)
+ \param pad the type of Padding to use
+ \param dir the Direction that this Cipher should use (Encode for
+ encryption, Decode for decryption)
+ \param key the SymmetricKey array that is the key
+ \param iv the InitializationVector to use (not used for ECB mode)
+ \param tag the AuthTag to use (only for GCM and CCM modes)
+ \param provider the name of the Provider to use
+
+ \note Padding only applies to CBC and ECB modes. CFB and OFB
+ ciphertext is always the length of the plaintext.
+ */
+ Cipher(const QString &type, Mode mode, Padding pad,
+ Direction dir, const SymmetricKey &key,
+ const InitializationVector &iv, const AuthTag &tag,
+ const QString &provider = QString());
+
+ /**
+ Standard copy constructor
+
+ \param from the Cipher to copy state from
+ */
+ Cipher(const Cipher &from);
+
+ ~Cipher();
+
+ /**
+ Assignment operator
+
+ \param from the Cipher to copy state from
+ */
+ Cipher &operator=(const Cipher &from);
+
+ /**
+ Returns a list of all of the cipher types available
+
+ \param provider the name of the provider to get a list from, if one
+ provider is required. If not specified, available cipher types from all
+ providers will be returned.
+ */
+ static QStringList supportedTypes(const QString &provider = QString());
+
+ /**
+ Return the cipher type
+ */
+ QString type() const;
+
+ /**
+ Return the cipher mode
+ */
+ Mode mode() const;
+
+ /**
+ Return the cipher padding type
+ */
+ Padding padding() const;
+
+ /**
+ Return the cipher direction
+ */
+ Direction direction() const;
+
+ /**
+ Return acceptable key lengths
+ */
+ KeyLength keyLength() const;
+
+ /**
+ Test if a key length is valid for the cipher algorithm
+
+ \param n the key length in bytes
+ \return true if the key would be valid for the current algorithm
+ */
+ bool validKeyLength(int n) const;
+
+ /**
+ return the block size for the cipher object
+ */
+ int blockSize() const;
+
+ /**
+ return the authentication tag for the cipher object
+ */
+ AuthTag tag() const;
+
+ /**
+ reset the cipher object, to allow re-use
+ */
+ virtual void clear();
+
+ /**
+ pass in a byte array of data, which will be encrypted or decrypted
+ (according to the Direction that was set in the constructor or in
+ setup() ) and returned.
+
+ \param a the array of data to encrypt / decrypt
+ */
+ virtual MemoryRegion update(const MemoryRegion &a);
+
+ /**
+ complete the block of data, padding as required, and returning
+ the completed block
+ */
+ virtual MemoryRegion final();
+
+ /**
+ Test if an update() or final() call succeeded.
+
+ \return true if the previous call succeeded
+ */
+ virtual bool ok() const;
+
+ /**
+ Reset / reconfigure the Cipher
+
+ You can use this to re-use an existing Cipher, rather than creating
+ a new object with a slightly different configuration.
+
+ \param dir the Direction that this Cipher should use (Encode for
+ encryption, Decode for decryption)
+ \param key the SymmetricKey array that is the key
+ \param iv the InitializationVector to use (not used for ECB Mode)
+
+ \note You should not leave iv empty for any Mode except ECB.
+ */
+ void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv = InitializationVector());
+
+ /**
+ Reset / reconfigure the Cipher
+
+ You can use this to re-use an existing Cipher, rather than creating
+ a new object with a slightly different configuration.
+
+ \param dir the Direction that this Cipher should use (Encode for
+ encryption, Decode for decryption)
+ \param key the SymmetricKey array that is the key
+ \param iv the InitializationVector to use (not used for ECB Mode)
+ \param tag the AuthTag to use (only for GCM and CCM modes)
+
+ \note You should not leave iv empty for any Mode except ECB.
+ */
+ void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag);
+
+ /**
+ Construct a Cipher type string
+
+ \param cipherType the name of the algorithm (eg AES128, DES)
+ \param modeType the mode to operate the cipher in (eg QCA::CBC,
+ QCA::CFB)
+ \param paddingType the padding required (eg QCA::NoPadding,
+ QCA::PCKS7)
+ */
+ static QString withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class MessageAuthenticationCode qca_basic.h QtCrypto
General class for message authentication code (MAC) algorithms.
- MessageAuthenticationCode is a class for accessing the various
+ MessageAuthenticationCode is a class for accessing the various
message authentication code algorithms within %QCA.
HMAC using SHA1 ("hmac(sha1)") or HMAC using SHA256 ("hmac(sha256)")
is recommended for new applications.
Note that if your application is potentially susceptable to "replay
attacks" where the message is sent more than once, you should include a
counter in the message that is covered by the MAC, and check that the
counter is always incremented every time you receive a message and MAC.
- For more information on HMAC, see H. Krawczyk et al. RFC2104
+ For more information on HMAC, see H. Krawczyk et al. RFC2104
"HMAC: Keyed-Hashing for Message Authentication"
\ingroup UserAPI
*/
class QCA_EXPORT MessageAuthenticationCode : public Algorithm, public BufferedComputation
{
public:
- /**
- Standard constructor
-
- \param type the name of the MAC (and algorithm, if applicable) to
- use
- \param key the shared key
- \param provider the provider to use, if a particular provider is
- required
- */
- MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider = QString());
-
- /**
- Standard copy constructor
-
- Copies the state (including key) from one MessageAuthenticationCode
- to another
-
- \param from the MessageAuthenticationCode to copy state from
- */
- MessageAuthenticationCode(const MessageAuthenticationCode &from);
-
- ~MessageAuthenticationCode();
-
- /**
- Assignment operator.
-
- Copies the state (including key) from one MessageAuthenticationCode
- to another
-
- \param from the MessageAuthenticationCode to assign from.
- */
- MessageAuthenticationCode & operator=(const MessageAuthenticationCode &from);
-
- /**
- Returns a list of all of the message authentication code types
- available
-
- \param provider the name of the provider to get a list from, if one
- provider is required. If not specified, available message authentication
- codes types from all providers will be returned.
- */
- static QStringList supportedTypes(const QString &provider = QString());
-
- /**
- Return the MAC type
- */
- QString type() const;
-
- /**
- Return acceptable key lengths
- */
- KeyLength keyLength() const;
-
- /**
- Test if a key length is valid for the MAC algorithm
-
- \param n the key length in bytes
- \return true if the key would be valid for the current algorithm
- */
- bool validKeyLength(int n) const;
-
- /**
- Reset a MessageAuthenticationCode, dumping all
- previous parts of the message.
-
- This method clears (or resets) the algorithm,
- effectively undoing any previous update()
- calls. You should use this call if you are re-using
- a %MessageAuthenticationCode sub-class object
- to calculate additional MACs. Note that if the key
- doesn't need to be changed, you don't need to call
- setup() again, since the key can just be reused.
- */
- virtual void clear();
-
- /**
- Update the MAC, adding more of the message contents
- to the digest. The whole message needs to be added
- using this method before you call final().
-
- \param array the message contents
- */
- virtual void update(const MemoryRegion &array);
-
- /**
- Finalises input and returns the MAC result
-
- After calling update() with the required data, the
- hash results are finalised and produced.
-
- Note that it is not possible to add further data (with
- update()) after calling final(). If you want to
- reuse the %MessageAuthenticationCode object, you
- should call clear() and start to update() again.
- */
- virtual MemoryRegion final();
-
- /**
- Initialise the MAC algorithm
-
- \param key the key to use for the algorithm
- */
- void setup(const SymmetricKey &key);
+ /**
+ Standard constructor
+
+ \param type the name of the MAC (and algorithm, if applicable) to
+ use
+ \param key the shared key
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ MessageAuthenticationCode(const QString &type, const SymmetricKey &key, const QString &provider = QString());
+
+ /**
+ Standard copy constructor
+
+ Copies the state (including key) from one MessageAuthenticationCode
+ to another
+
+ \param from the MessageAuthenticationCode to copy state from
+ */
+ MessageAuthenticationCode(const MessageAuthenticationCode &from);
+
+ ~MessageAuthenticationCode();
+
+ /**
+ Assignment operator.
+
+ Copies the state (including key) from one MessageAuthenticationCode
+ to another
+
+ \param from the MessageAuthenticationCode to assign from.
+ */
+ MessageAuthenticationCode &operator=(const MessageAuthenticationCode &from);
+
+ /**
+ Returns a list of all of the message authentication code types
+ available
+
+ \param provider the name of the provider to get a list from, if one
+ provider is required. If not specified, available message authentication
+ codes types from all providers will be returned.
+ */
+ static QStringList supportedTypes(const QString &provider = QString());
+
+ /**
+ Return the MAC type
+ */
+ QString type() const;
+
+ /**
+ Return acceptable key lengths
+ */
+ KeyLength keyLength() const;
+
+ /**
+ Test if a key length is valid for the MAC algorithm
+
+ \param n the key length in bytes
+ \return true if the key would be valid for the current algorithm
+ */
+ bool validKeyLength(int n) const;
+
+ /**
+ Reset a MessageAuthenticationCode, dumping all
+ previous parts of the message.
+
+ This method clears (or resets) the algorithm,
+ effectively undoing any previous update()
+ calls. You should use this call if you are re-using
+ a %MessageAuthenticationCode sub-class object
+ to calculate additional MACs. Note that if the key
+ doesn't need to be changed, you don't need to call
+ setup() again, since the key can just be reused.
+ */
+ virtual void clear();
+
+ /**
+ Update the MAC, adding more of the message contents
+ to the digest. The whole message needs to be added
+ using this method before you call final().
+
+ \param array the message contents
+ */
+ virtual void update(const MemoryRegion &array);
+
+ /**
+ Finalises input and returns the MAC result
+
+ After calling update() with the required data, the
+ hash results are finalised and produced.
+
+ Note that it is not possible to add further data (with
+ update()) after calling final(). If you want to
+ reuse the %MessageAuthenticationCode object, you
+ should call clear() and start to update() again.
+ */
+ virtual MemoryRegion final();
+
+ /**
+ Initialise the MAC algorithm
+
+ \param key the key to use for the algorithm
+ */
+ void setup(const SymmetricKey &key);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class KeyDerivationFunction qca_basic.h QtCrypto
General superclass for key derivation algorithms.
- %KeyDerivationFunction is a superclass for the various
+ %KeyDerivationFunction is a superclass for the various
key derivation function algorithms within %QCA. You should
not need to use it directly unless you are
adding another key derivation capability to %QCA - you should be
using a sub-class. PBKDF2 using SHA1 is recommended for new applications.
\ingroup UserAPI
*/
class QCA_EXPORT KeyDerivationFunction : public Algorithm
{
public:
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the KeyDerivationFunction to copy from
- */
- KeyDerivationFunction(const KeyDerivationFunction &from);
+ \param from the KeyDerivationFunction to copy from
+ */
+ KeyDerivationFunction(const KeyDerivationFunction &from);
- ~KeyDerivationFunction();
+ ~KeyDerivationFunction();
- /**
- Assignment operator
+ /**
+ Assignment operator
- Copies the state (including key) from one KeyDerivationFunction
- to another
+ Copies the state (including key) from one KeyDerivationFunction
+ to another
- \param from the KeyDerivationFunction to assign from
- */
- KeyDerivationFunction & operator=(const KeyDerivationFunction &from);
+ \param from the KeyDerivationFunction to assign from
+ */
+ KeyDerivationFunction &operator=(const KeyDerivationFunction &from);
- /**
- Generate the key from a specified secret and salt value
+ /**
+ Generate the key from a specified secret and salt value
- \note key length is ignored for some functions
+ \note key length is ignored for some functions
- \param secret the secret (password or passphrase)
- \param salt the salt to use
- \param keyLength the length of key to return
- \param iterationCount the number of iterations to perform
+ \param secret the secret (password or passphrase)
+ \param salt the salt to use
+ \param keyLength the length of key to return
+ \param iterationCount the number of iterations to perform
- \return the derived key
- */
- SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount);
+ \return the derived key
+ */
+ SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount);
- /**
- Generate the key from a specified secret and salt value
+ /**
+ Generate the key from a specified secret and salt value
- \note key length is ignored for some functions
+ \note key length is ignored for some functions
- \param secret the secret (password or passphrase)
- \param salt the salt to use
- \param keyLength the length of key to return
- \param msecInterval the maximum time to compute the key, in milliseconds
- \param iterationCount a pointer to store the number of iteration done for the specified time
+ \param secret the secret (password or passphrase)
+ \param salt the salt to use
+ \param keyLength the length of key to return
+ \param msecInterval the maximum time to compute the key, in milliseconds
+ \param iterationCount a pointer to store the number of iteration done for the specified time
- \return the derived key
- */
- SymmetricKey makeKey(const SecureArray &secret,
- const InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount);
+ \return the derived key
+ */
+ SymmetricKey makeKey(const SecureArray &secret,
+ const InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount);
- /**
- Construct the name of the algorithm
+ /**
+ Construct the name of the algorithm
- You can use this to build a standard name string.
- You probably only need this method if you are
- creating a new subclass.
+ You can use this to build a standard name string.
+ You probably only need this method if you are
+ creating a new subclass.
- \param kdfType the type of key derivation function
- \param algType the name of the algorithm to use with the key derivation function
+ \param kdfType the type of key derivation function
+ \param algType the name of the algorithm to use with the key derivation function
- \return the name of the KDF/algorithm pair
- */
- static QString withAlgorithm(const QString &kdfType, const QString &algType);
+ \return the name of the KDF/algorithm pair
+ */
+ static QString withAlgorithm(const QString &kdfType, const QString &algType);
protected:
- /**
- Special constructor for subclass initialisation
+ /**
+ Special constructor for subclass initialisation
- \param type the algorithm to create
- \param provider the name of the provider to create the key derivation function in.
- */
- KeyDerivationFunction(const QString &type, const QString &provider);
+ \param type the algorithm to create
+ \param provider the name of the provider to create the key derivation function in.
+ */
+ KeyDerivationFunction(const QString &type, const QString &provider);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class PBKDF1 qca_basic.h QtCrypto
Password based key derivation function version 1
This class implements Password Based Key Derivation Function version 1,
as specified in RFC2898, and also in PKCS#5.
\ingroup UserAPI
*/
class QCA_EXPORT PBKDF1 : public KeyDerivationFunction
{
public:
- /**
- Standard constructor
-
- \param algorithm the name of the hashing algorithm to use
- \param provider the name of the provider to use, if available
- */
- explicit PBKDF1(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString())
- : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf1"), algorithm), provider) {}
+ /**
+ Standard constructor
+
+ \param algorithm the name of the hashing algorithm to use
+ \param provider the name of the provider to use, if available
+ */
+ explicit PBKDF1(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString())
+ : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf1"), algorithm), provider) {}
};
/**
\class PBKDF2 qca_basic.h QtCrypto
Password based key derivation function version 2
This class implements Password Based Key Derivation Function version 2,
as specified in RFC2898, and also in PKCS#5.
\ingroup UserAPI
*/
class QCA_EXPORT PBKDF2 : public KeyDerivationFunction
{
public:
- /**
- Standard constructor
-
- \param algorithm the name of the hashing algorithm to use
- \param provider the name of the provider to use, if available
- */
- explicit PBKDF2(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString())
- : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf2"), algorithm), provider) {}
+ /**
+ Standard constructor
+
+ \param algorithm the name of the hashing algorithm to use
+ \param provider the name of the provider to use, if available
+ */
+ explicit PBKDF2(const QString &algorithm = QStringLiteral("sha1"), const QString &provider = QString())
+ : KeyDerivationFunction(withAlgorithm(QStringLiteral("pbkdf2"), algorithm), provider) {}
};
/**
\class HKDF qca_basic.h QtCrypto
\since 2.3
HMAC-based extract-and-expand key derivation function
This class implements HMAC-based Extract-and-Expand Key Derivation Function,
as specified in RFC5869.
\ingroup UserAPI
*/
class QCA_EXPORT HKDF : public Algorithm
{
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param algorithm the name of the hashing algorithm to use
- \param provider the name of the provider to use, if available
- */
- explicit HKDF(const QString &algorithm = QStringLiteral("sha256"), const QString &provider = QString());
+ \param algorithm the name of the hashing algorithm to use
+ \param provider the name of the provider to use, if available
+ */
+ explicit HKDF(const QString &algorithm = QStringLiteral("sha256"), const QString &provider = QString());
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the KeyDerivationFunction to copy from
- */
- HKDF(const HKDF &from);
+ \param from the KeyDerivationFunction to copy from
+ */
+ HKDF(const HKDF &from);
- ~HKDF();
+ ~HKDF();
- /**
- Assignment operator
+ /**
+ Assignment operator
- Copies the state (including key) from one HKDF
- to another
+ Copies the state (including key) from one HKDF
+ to another
- \param from the HKDF to assign from
- */
- HKDF & operator=(const HKDF &from);
+ \param from the HKDF to assign from
+ */
+ HKDF &operator=(const HKDF &from);
- /**
- Generate the key from a specified secret, salt value, and an additional info
+ /**
+ Generate the key from a specified secret, salt value, and an additional info
- \note key length is ignored for some functions
+ \note key length is ignored for some functions
- \param secret the secret (password or passphrase)
- \param salt the salt to use
- \param info the info to use
- \param keyLength the length of key to return
+ \param secret the secret (password or passphrase)
+ \param salt the salt to use
+ \param info the info to use
+ \param keyLength the length of key to return
- \return the derived key
- */
- SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
- const InitializationVector &info, unsigned int keyLength);
+ \return the derived key
+ */
+ SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
+ const InitializationVector &info, unsigned int keyLength);
};
}
#endif
diff --git a/include/QtCrypto/qca_cert.h b/include/QtCrypto/qca_cert.h
index 7ae07b1e..fbb93e81 100644
--- a/include/QtCrypto/qca_cert.h
+++ b/include/QtCrypto/qca_cert.h
@@ -1,2675 +1,2673 @@
/*
* qca_cert.h - Qt Cryptographic Architecture
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_cert.h
Header file for PGP key and X.509 certificate related classes
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_CERT_H
#define QCA_CERT_H
#include <QDateTime>
#include "qca_core.h"
#include "qca_publickey.h"
-namespace QCA {
+namespace QCA
+{
class CertContext;
class CSRContext;
class CRLContext;
class Certificate;
class CRL;
class CertificateCollection;
class CertificateChain;
-
/**
Certificate Request Format
*/
-enum CertificateRequestFormat
-{
- PKCS10, ///< standard PKCS#10 format
- SPKAC ///< Signed Public Key and Challenge (Netscape) format
+enum CertificateRequestFormat {
+ PKCS10, ///< standard PKCS#10 format
+ SPKAC ///< Signed Public Key and Challenge (Netscape) format
};
/**
Known types of information stored in certificates
This enumerator offers a convenient way to work with common types.
*/
-enum CertificateInfoTypeKnown
-{
- CommonName, ///< The common name (eg person), id = "2.5.4.3"
- Email, ///< Email address, id = "GeneralName.rfc822Name"
- EmailLegacy, ///< PKCS#9 Email field, id = "1.2.840.113549.1.9.1"
- Organization, ///< An organisation (eg company), id = "2.5.4.10"
- OrganizationalUnit, ///< An part of an organisation (eg a division or branch), id = "2.5.4.11"
- Locality, ///< The locality (eg city, a shire, or part of a state), id = "2.5.4.7"
- IncorporationLocality, ///< The locality of incorporation (EV certificates), id = "1.3.6.1.4.1.311.60.2.1.1"
- State, ///< The state within the country, id = "2.5.4.8"
- IncorporationState, ///< The state of incorporation (EV certificates), id = "1.3.6.1.4.1.311.60.2.1.2"
- Country, ///< The country, id = "2.5.4.6"
- IncorporationCountry, ///< The country of incorporation (EV certificates), id = "1.3.6.1.4.1.311.60.2.1.3"
- URI, ///< Uniform Resource Identifier, id = "GeneralName.uniformResourceIdentifier"
- DNS, ///< DNS name, id = "GeneralName.dNSName"
- IPAddress, ///< IP address, id = "GeneralName.iPAddress"
- XMPP ///< XMPP address (see http://www.ietf.org/rfc/rfc3920.txt), id = "1.3.6.1.5.5.7.8.5"
+enum CertificateInfoTypeKnown {
+ CommonName, ///< The common name (eg person), id = "2.5.4.3"
+ Email, ///< Email address, id = "GeneralName.rfc822Name"
+ EmailLegacy, ///< PKCS#9 Email field, id = "1.2.840.113549.1.9.1"
+ Organization, ///< An organisation (eg company), id = "2.5.4.10"
+ OrganizationalUnit, ///< An part of an organisation (eg a division or branch), id = "2.5.4.11"
+ Locality, ///< The locality (eg city, a shire, or part of a state), id = "2.5.4.7"
+ IncorporationLocality, ///< The locality of incorporation (EV certificates), id = "1.3.6.1.4.1.311.60.2.1.1"
+ State, ///< The state within the country, id = "2.5.4.8"
+ IncorporationState, ///< The state of incorporation (EV certificates), id = "1.3.6.1.4.1.311.60.2.1.2"
+ Country, ///< The country, id = "2.5.4.6"
+ IncorporationCountry, ///< The country of incorporation (EV certificates), id = "1.3.6.1.4.1.311.60.2.1.3"
+ URI, ///< Uniform Resource Identifier, id = "GeneralName.uniformResourceIdentifier"
+ DNS, ///< DNS name, id = "GeneralName.dNSName"
+ IPAddress, ///< IP address, id = "GeneralName.iPAddress"
+ XMPP ///< XMPP address (see http://www.ietf.org/rfc/rfc3920.txt), id = "1.3.6.1.5.5.7.8.5"
};
/**
\class CertificateInfoType qca_cert.h QtCrypto
Certificate information type
This class represents a type of information being stored in
a certificate. It can be created either using a known type
(from the Known enumerator) or an identifier string (usually
an OID). Types created either way are interchangeable.
Types also have the notion of a Section. Some types may
reside in the Distinguished Name field of a certificate, and
some types may reside in the Subject Alternative Name field.
This class is capable of representing a type from either
section.
In the general case, applications will want to use the
CertificateInfoTypeKnown enumerator types. These are from RFC3280
(http://www.ietf.org/rfc/rfc3280.txt) except where shown.
The entries for IncorporationLocality, IncorporationState
and IncorporationCountry are the same as Locality, State
and Country respectively, except that the Extended
Validation (EV) certificate guidelines (published by the
%Certificate Authority / Browser Forum, see
http://www.cabforum.org) distinguish between the place of
where the company does business (which is the Locality /
State / Country combination) and the jurisdiction where the
company is legally incorporated (the IncorporationLocality
/ IncorporationState / IncorporationCountry combination).
\sa Certificate::subjectInfo() and Certificate::issuerInfo()
\sa CRL::issuerInfo()
\ingroup UserAPI
*/
class QCA_EXPORT CertificateInfoType
{
public:
- /**
- Section of the certificate that the information belongs in
- */
- enum Section
- {
- DN, ///< Distinguished name (the primary name)
- AlternativeName ///< Alternative name
- };
-
- /**
- Standard constructor
- */
- CertificateInfoType();
-
- /**
- Construct a new type
-
- The section will be derived by \a known.
-
- \param known the type as part of the CertificateInfoTypeKnown
- enumerator
- */
- CertificateInfoType(CertificateInfoTypeKnown known);
-
- /**
- Construct a new type
-
- \param id the type as an identifier string (OID or internal)
- \param section the section this type belongs in
-
- \sa id
- */
- CertificateInfoType(const QString &id, Section section);
-
- /**
- Standard copy constructor
-
- \param from the certificate information to copy from
- */
- CertificateInfoType(const CertificateInfoType &from);
-
- ~CertificateInfoType();
-
- /**
- Standard assignment operator
-
- \param from the certificate information to assign from
- */
- CertificateInfoType & operator=(const CertificateInfoType &from);
-
- /**
- The section the type is part of
- */
- Section section() const;
-
- /**
- The type as part of the CertificateInfoTypeKnown enumerator
-
- This function may return a value that does not exist in the
- enumerator. In that case, you may use id() to determine the
- type.
- */
- CertificateInfoTypeKnown known() const;
-
- /**
- The type as an identifier string
-
- For types that have OIDs, this function returns an OID in string
- form. For types that do not have OIDs, this function returns an
- internal identifier string whose first character is not a digit
- (this allows you to tell the difference between an OID and an
- internal identifier).
-
- It is hereby stated that General Names (of the X.509 Subject
- Alternative Name) shall use the internal identifier format
- "GeneralName.[rfc field name]". For example, the rfc822Name
- field would have the identifier "GeneralName.rfc822Name".
-
- Applications should not store, use, or compare against internal
- identifiers unless the identifiers are explicitly documented
- (e.g. GeneralName).
- */
- QString id() const;
-
- /**
- Comparison operator
-
- \param other the certificate information to compare with this
- certificate information.
- */
- bool operator<(const CertificateInfoType &other) const;
-
- /**
- Comparison operator
-
- \param other the certificate information to compare with this
- certificate information.
- */
- bool operator==(const CertificateInfoType &other) const;
-
- /**
- Inequality operator
-
- \param other the certificate information to compare with this
- certificate information.
- */
- inline bool operator!=(const CertificateInfoType &other) const
- {
- return !(*this == other);
- }
+ /**
+ Section of the certificate that the information belongs in
+ */
+ enum Section {
+ DN, ///< Distinguished name (the primary name)
+ AlternativeName ///< Alternative name
+ };
+
+ /**
+ Standard constructor
+ */
+ CertificateInfoType();
+
+ /**
+ Construct a new type
+
+ The section will be derived by \a known.
+
+ \param known the type as part of the CertificateInfoTypeKnown
+ enumerator
+ */
+ CertificateInfoType(CertificateInfoTypeKnown known);
+
+ /**
+ Construct a new type
+
+ \param id the type as an identifier string (OID or internal)
+ \param section the section this type belongs in
+
+ \sa id
+ */
+ CertificateInfoType(const QString &id, Section section);
+
+ /**
+ Standard copy constructor
+
+ \param from the certificate information to copy from
+ */
+ CertificateInfoType(const CertificateInfoType &from);
+
+ ~CertificateInfoType();
+
+ /**
+ Standard assignment operator
+
+ \param from the certificate information to assign from
+ */
+ CertificateInfoType &operator=(const CertificateInfoType &from);
+
+ /**
+ The section the type is part of
+ */
+ Section section() const;
+
+ /**
+ The type as part of the CertificateInfoTypeKnown enumerator
+
+ This function may return a value that does not exist in the
+ enumerator. In that case, you may use id() to determine the
+ type.
+ */
+ CertificateInfoTypeKnown known() const;
+
+ /**
+ The type as an identifier string
+
+ For types that have OIDs, this function returns an OID in string
+ form. For types that do not have OIDs, this function returns an
+ internal identifier string whose first character is not a digit
+ (this allows you to tell the difference between an OID and an
+ internal identifier).
+
+ It is hereby stated that General Names (of the X.509 Subject
+ Alternative Name) shall use the internal identifier format
+ "GeneralName.[rfc field name]". For example, the rfc822Name
+ field would have the identifier "GeneralName.rfc822Name".
+
+ Applications should not store, use, or compare against internal
+ identifiers unless the identifiers are explicitly documented
+ (e.g. GeneralName).
+ */
+ QString id() const;
+
+ /**
+ Comparison operator
+
+ \param other the certificate information to compare with this
+ certificate information.
+ */
+ bool operator<(const CertificateInfoType &other) const;
+
+ /**
+ Comparison operator
+
+ \param other the certificate information to compare with this
+ certificate information.
+ */
+ bool operator==(const CertificateInfoType &other) const;
+
+ /**
+ Inequality operator
+
+ \param other the certificate information to compare with this
+ certificate information.
+ */
+ inline bool operator!=(const CertificateInfoType &other) const
+ {
+ return !(*this == other);
+ }
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class CertificateInfoPair qca_cert.h QtCrypto
One entry in a certificate information list
\ingroup UserAPI
*/
class QCA_EXPORT CertificateInfoPair
{
public:
- /**
- Standard constructor
- */
- CertificateInfoPair();
+ /**
+ Standard constructor
+ */
+ CertificateInfoPair();
- /**
- Construct a new pair
+ /**
+ Construct a new pair
- \param type the type of information stored in this pair
- \param value the value of the information to be stored
- */
- CertificateInfoPair(const CertificateInfoType &type, const QString &value);
+ \param type the type of information stored in this pair
+ \param value the value of the information to be stored
+ */
+ CertificateInfoPair(const CertificateInfoType &type, const QString &value);
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the information pair to copy from
- */
- CertificateInfoPair(const CertificateInfoPair &from);
+ \param from the information pair to copy from
+ */
+ CertificateInfoPair(const CertificateInfoPair &from);
- ~CertificateInfoPair();
+ ~CertificateInfoPair();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the information pair to assign from
- */
- CertificateInfoPair & operator=(const CertificateInfoPair &from);
+ \param from the information pair to assign from
+ */
+ CertificateInfoPair &operator=(const CertificateInfoPair &from);
- /**
- The type of information stored in the pair
- */
- CertificateInfoType type() const;
+ /**
+ The type of information stored in the pair
+ */
+ CertificateInfoType type() const;
- /**
- The value of the information stored in the pair
- */
- QString value() const;
+ /**
+ The value of the information stored in the pair
+ */
+ QString value() const;
- /**
- Comparison operator
+ /**
+ Comparison operator
- \param other the certificate information pair to compare with this
- certificate information pair.
- */
- bool operator==(const CertificateInfoPair &other) const;
+ \param other the certificate information pair to compare with this
+ certificate information pair.
+ */
+ bool operator==(const CertificateInfoPair &other) const;
- /**
- Inequality operator
+ /**
+ Inequality operator
- \param other the certificate information pair to compare with this
- certificate information pair.
- */
- inline bool operator!=(const CertificateInfoPair &other) const
- {
- return !(*this == other);
- }
+ \param other the certificate information pair to compare with this
+ certificate information pair.
+ */
+ inline bool operator!=(const CertificateInfoPair &other) const
+ {
+ return !(*this == other);
+ }
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
-
/**
Known types of certificate constraints
This enumerator offers a convenient way to work with common types.
*/
-enum ConstraintTypeKnown
-{
- // KeyUsage
- DigitalSignature, ///< %Certificate can be used to create digital signatures, id = "KeyUsage.digitalSignature"
- NonRepudiation, ///< %Certificate can be used for non-repudiation, id = "KeyUsage.nonRepudiation"
- KeyEncipherment, ///< %Certificate can be used for encrypting / decrypting keys, id = "KeyUsage.keyEncipherment"
- DataEncipherment, ///< %Certificate can be used for encrypting / decrypting data, id = "KeyUsage.dataEncipherment"
- KeyAgreement, ///< %Certificate can be used for key agreement, id = "KeyUsage.keyAgreement"
- KeyCertificateSign, ///< %Certificate can be used for key certificate signing, id = "KeyUsage.keyCertSign"
- CRLSign, ///< %Certificate can be used to sign %Certificate Revocation Lists, id = "KeyUsage.crlSign"
- EncipherOnly, ///< %Certificate can only be used for encryption, id = "KeyUsage.encipherOnly"
- DecipherOnly, ///< %Certificate can only be used for decryption, id = "KeyUsage.decipherOnly"
-
- // ExtKeyUsage
- ServerAuth, ///< %Certificate can be used for server authentication (e.g. web server), id = "1.3.6.1.5.5.7.3.1". This is an extended usage constraint.
- ClientAuth, ///< %Certificate can be used for client authentication (e.g. web browser), id = "1.3.6.1.5.5.7.3.2". This is an extended usage constraint.
- CodeSigning, ///< %Certificate can be used to sign code, id = "1.3.6.1.5.5.7.3.3". This is an extended usage constraint.
- EmailProtection, ///< %Certificate can be used to sign / encrypt email, id = "1.3.6.1.5.5.7.3.4". This is an extended usage constraint.
- IPSecEndSystem, ///< %Certificate can be used to authenticate a endpoint in IPSEC, id = "1.3.6.1.5.5.7.3.5". This is an extended usage constraint.
- IPSecTunnel, ///< %Certificate can be used to authenticate a tunnel in IPSEC, id = "1.3.6.1.5.5.7.3.6". This is an extended usage constraint.
- IPSecUser, ///< %Certificate can be used to authenticate a user in IPSEC, id = "1.3.6.1.5.5.7.3.7". This is an extended usage constraint.
- TimeStamping, ///< %Certificate can be used to create a "time stamp" signature, id = "1.3.6.1.5.5.7.3.8". This is an extended usage constraint.
- OCSPSigning ///< %Certificate can be used to sign an Online %Certificate Status Protocol (OCSP) assertion, id = "1.3.6.1.5.5.7.3.9". This is an extended usage constraint.
+enum ConstraintTypeKnown {
+ // KeyUsage
+ DigitalSignature, ///< %Certificate can be used to create digital signatures, id = "KeyUsage.digitalSignature"
+ NonRepudiation, ///< %Certificate can be used for non-repudiation, id = "KeyUsage.nonRepudiation"
+ KeyEncipherment, ///< %Certificate can be used for encrypting / decrypting keys, id = "KeyUsage.keyEncipherment"
+ DataEncipherment, ///< %Certificate can be used for encrypting / decrypting data, id = "KeyUsage.dataEncipherment"
+ KeyAgreement, ///< %Certificate can be used for key agreement, id = "KeyUsage.keyAgreement"
+ KeyCertificateSign, ///< %Certificate can be used for key certificate signing, id = "KeyUsage.keyCertSign"
+ CRLSign, ///< %Certificate can be used to sign %Certificate Revocation Lists, id = "KeyUsage.crlSign"
+ EncipherOnly, ///< %Certificate can only be used for encryption, id = "KeyUsage.encipherOnly"
+ DecipherOnly, ///< %Certificate can only be used for decryption, id = "KeyUsage.decipherOnly"
+
+ // ExtKeyUsage
+ ServerAuth, ///< %Certificate can be used for server authentication (e.g. web server), id = "1.3.6.1.5.5.7.3.1". This is an extended usage constraint.
+ ClientAuth, ///< %Certificate can be used for client authentication (e.g. web browser), id = "1.3.6.1.5.5.7.3.2". This is an extended usage constraint.
+ CodeSigning, ///< %Certificate can be used to sign code, id = "1.3.6.1.5.5.7.3.3". This is an extended usage constraint.
+ EmailProtection, ///< %Certificate can be used to sign / encrypt email, id = "1.3.6.1.5.5.7.3.4". This is an extended usage constraint.
+ IPSecEndSystem, ///< %Certificate can be used to authenticate a endpoint in IPSEC, id = "1.3.6.1.5.5.7.3.5". This is an extended usage constraint.
+ IPSecTunnel, ///< %Certificate can be used to authenticate a tunnel in IPSEC, id = "1.3.6.1.5.5.7.3.6". This is an extended usage constraint.
+ IPSecUser, ///< %Certificate can be used to authenticate a user in IPSEC, id = "1.3.6.1.5.5.7.3.7". This is an extended usage constraint.
+ TimeStamping, ///< %Certificate can be used to create a "time stamp" signature, id = "1.3.6.1.5.5.7.3.8". This is an extended usage constraint.
+ OCSPSigning ///< %Certificate can be used to sign an Online %Certificate Status Protocol (OCSP) assertion, id = "1.3.6.1.5.5.7.3.9". This is an extended usage constraint.
};
/**
\class ConstraintType qca_cert.h QtCrypto
Certificate constraint
X.509 certificates can be constrained in their application - that is, some
certificates can only be used for certain purposes. This class is used to
identify an approved purpose for a certificate.
\note It is common for a certificate to have more than one purpose.
\ingroup UserAPI
*/
class QCA_EXPORT ConstraintType
{
public:
- /**
- Section of the certificate that the constraint belongs in
- */
- enum Section
- {
- KeyUsage, ///< Stored in the key usage section
- ExtendedKeyUsage ///< Stored in the extended key usage section
- };
-
- /**
- Standard constructor
- */
- ConstraintType();
-
- /**
- Construct a new constraint
-
- The section will be derived by \a known.
-
- \param known the type as part of the ConstraintTypeKnown
- enumerator
- */
- ConstraintType(ConstraintTypeKnown known);
-
- /**
- Construct a new constraint
-
- \param id the type as an identifier string (OID or internal)
- \param section the section this type belongs in
-
- \sa id
- */
- ConstraintType(const QString &id, Section section);
-
- /**
- Standard copy constructor
-
- \param from the constraint type to copy from
- */
- ConstraintType(const ConstraintType &from);
-
- ~ConstraintType();
-
- /**
- Standard assignment operator
-
- \param from the constraint type to assign from
- */
- ConstraintType & operator=(const ConstraintType &from);
-
- /**
- The section the constraint is part of
- */
- Section section() const;
-
- /**
- The type as part of the ConstraintTypeKnown enumerator
-
- This function may return a value that does not exist in the
- enumerator. In that case, you may use id() to determine the
- type.
- */
- ConstraintTypeKnown known() const;
-
- /**
- The type as an identifier string
-
- For types that have OIDs, this function returns an OID in string
- form. For types that do not have OIDs, this function returns an
- internal identifier string whose first character is not a digit
- (this allows you to tell the difference between an OID and an
- internal identifier).
-
- It is hereby stated that the KeyUsage bit fields shall use the
- internal identifier format "KeyUsage.[rfc field name]". For
- example, the keyEncipherment field would have the identifier
- "KeyUsage.keyEncipherment".
-
- Applications should not store, use, or compare against internal
- identifiers unless the identifiers are explicitly documented
- (e.g. KeyUsage).
- */
- QString id() const;
-
- /**
- Comparison operator
-
- \param other the constraint type to compare with this constraint
- */
- bool operator<(const ConstraintType &other) const;
-
- /**
- Comparison operator
-
- \param other the constraint type to compare with this constraint
- */
- bool operator==(const ConstraintType &other) const;
-
- /**
- Inequality operator
-
- \param other the constraint type to compare with this constraint
- */
- inline bool operator!=(const ConstraintType &other) const
- {
- return !(*this == other);
- }
+ /**
+ Section of the certificate that the constraint belongs in
+ */
+ enum Section {
+ KeyUsage, ///< Stored in the key usage section
+ ExtendedKeyUsage ///< Stored in the extended key usage section
+ };
+
+ /**
+ Standard constructor
+ */
+ ConstraintType();
+
+ /**
+ Construct a new constraint
+
+ The section will be derived by \a known.
+
+ \param known the type as part of the ConstraintTypeKnown
+ enumerator
+ */
+ ConstraintType(ConstraintTypeKnown known);
+
+ /**
+ Construct a new constraint
+
+ \param id the type as an identifier string (OID or internal)
+ \param section the section this type belongs in
+
+ \sa id
+ */
+ ConstraintType(const QString &id, Section section);
+
+ /**
+ Standard copy constructor
+
+ \param from the constraint type to copy from
+ */
+ ConstraintType(const ConstraintType &from);
+
+ ~ConstraintType();
+
+ /**
+ Standard assignment operator
+
+ \param from the constraint type to assign from
+ */
+ ConstraintType &operator=(const ConstraintType &from);
+
+ /**
+ The section the constraint is part of
+ */
+ Section section() const;
+
+ /**
+ The type as part of the ConstraintTypeKnown enumerator
+
+ This function may return a value that does not exist in the
+ enumerator. In that case, you may use id() to determine the
+ type.
+ */
+ ConstraintTypeKnown known() const;
+
+ /**
+ The type as an identifier string
+
+ For types that have OIDs, this function returns an OID in string
+ form. For types that do not have OIDs, this function returns an
+ internal identifier string whose first character is not a digit
+ (this allows you to tell the difference between an OID and an
+ internal identifier).
+
+ It is hereby stated that the KeyUsage bit fields shall use the
+ internal identifier format "KeyUsage.[rfc field name]". For
+ example, the keyEncipherment field would have the identifier
+ "KeyUsage.keyEncipherment".
+
+ Applications should not store, use, or compare against internal
+ identifiers unless the identifiers are explicitly documented
+ (e.g. KeyUsage).
+ */
+ QString id() const;
+
+ /**
+ Comparison operator
+
+ \param other the constraint type to compare with this constraint
+ */
+ bool operator<(const ConstraintType &other) const;
+
+ /**
+ Comparison operator
+
+ \param other the constraint type to compare with this constraint
+ */
+ bool operator==(const ConstraintType &other) const;
+
+ /**
+ Inequality operator
+
+ \param other the constraint type to compare with this constraint
+ */
+ inline bool operator!=(const ConstraintType &other) const
+ {
+ return !(*this == other);
+ }
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
Specify the intended usage of a certificate
*/
-enum UsageMode
-{
- UsageAny = 0x00, ///< Any application, or unspecified
- UsageTLSServer = 0x01, ///< server side of a TLS or SSL connection
- UsageTLSClient = 0x02, ///< client side of a TLS or SSL connection
- UsageCodeSigning = 0x04, ///< code signing certificate
- UsageEmailProtection = 0x08, ///< email (S/MIME) certificate
- UsageTimeStamping = 0x10, ///< time stamping certificate
- UsageCRLSigning = 0x20 ///< certificate revocation list signing certificate
+enum UsageMode {
+ UsageAny = 0x00, ///< Any application, or unspecified
+ UsageTLSServer = 0x01, ///< server side of a TLS or SSL connection
+ UsageTLSClient = 0x02, ///< client side of a TLS or SSL connection
+ UsageCodeSigning = 0x04, ///< code signing certificate
+ UsageEmailProtection = 0x08, ///< email (S/MIME) certificate
+ UsageTimeStamping = 0x10, ///< time stamping certificate
+ UsageCRLSigning = 0x20 ///< certificate revocation list signing certificate
};
/**
The validity (or otherwise) of a certificate
*/
-enum Validity
-{
- ValidityGood, ///< The certificate is valid
- ErrorRejected, ///< The root CA rejected the certificate purpose
- ErrorUntrusted, ///< The certificate is not trusted
- ErrorSignatureFailed, ///< The signature does not match
- ErrorInvalidCA, ///< The Certificate Authority is invalid
- ErrorInvalidPurpose, ///< The purpose does not match the intended usage
- ErrorSelfSigned, ///< The certificate is self-signed, and is not found in the list of trusted certificates
- ErrorRevoked, ///< The certificate has been revoked
- ErrorPathLengthExceeded, ///< The path length from the root CA to this certificate is too long
- ErrorExpired, ///< The certificate has expired, or is not yet valid (e.g. current time is earlier than notBefore time)
- ErrorExpiredCA, ///< The Certificate Authority has expired
- ErrorValidityUnknown = 64 ///< Validity is unknown
+enum Validity {
+ ValidityGood, ///< The certificate is valid
+ ErrorRejected, ///< The root CA rejected the certificate purpose
+ ErrorUntrusted, ///< The certificate is not trusted
+ ErrorSignatureFailed, ///< The signature does not match
+ ErrorInvalidCA, ///< The Certificate Authority is invalid
+ ErrorInvalidPurpose, ///< The purpose does not match the intended usage
+ ErrorSelfSigned, ///< The certificate is self-signed, and is not found in the list of trusted certificates
+ ErrorRevoked, ///< The certificate has been revoked
+ ErrorPathLengthExceeded, ///< The path length from the root CA to this certificate is too long
+ ErrorExpired, ///< The certificate has expired, or is not yet valid (e.g. current time is earlier than notBefore time)
+ ErrorExpiredCA, ///< The Certificate Authority has expired
+ ErrorValidityUnknown = 64 ///< Validity is unknown
};
/**
The conditions to validate for a certificate
*/
-enum ValidateFlags
-{
- ValidateAll = 0x00, // Verify all conditions
- ValidateRevoked = 0x01, // Verify the certificate was not revoked
- ValidateExpired = 0x02, // Verify the certificate has not expired
- ValidatePolicy = 0x04 // Verify the certificate can be used for a specified purpose
+enum ValidateFlags {
+ ValidateAll = 0x00, // Verify all conditions
+ ValidateRevoked = 0x01, // Verify the certificate was not revoked
+ ValidateExpired = 0x02, // Verify the certificate has not expired
+ ValidatePolicy = 0x04 // Verify the certificate can be used for a specified purpose
};
/**
Certificate properties type
With this container, the information is not necessarily stored
in the same sequence as the certificate format itself. Use this
container if the order the information is/was stored does not
matter for you (this is the case with most applications).
Additionally, the EmailLegacy type should not be used with this
container. Use Email instead.
*/
typedef QMultiMap<CertificateInfoType, QString> CertificateInfo;
/**
\class CertificateInfoOrdered qca_cert.h QtCrypto
Ordered certificate properties type
This container stores the information in the same sequence as
the certificate format itself.
\ingroup UserAPI
*/
class CertificateInfoOrdered : public QList<CertificateInfoPair>
{
public:
- /**
- Convert to RFC 1779 string format
- */
- inline QString toString() const;
-
- /**
- Return a new CertificateInfoOrdered that only contains
- the Distinguished Name (DN) types found in this object.
- */
- inline CertificateInfoOrdered dnOnly() const;
+ /**
+ Convert to RFC 1779 string format
+ */
+ inline QString toString() const;
+
+ /**
+ Return a new CertificateInfoOrdered that only contains
+ the Distinguished Name (DN) types found in this object.
+ */
+ inline CertificateInfoOrdered dnOnly() const;
};
/**
Convert to RFC 1779 string format
\param in the certificate info to convert
*/
QCA_EXPORT QString orderedToDNString(const CertificateInfoOrdered &in);
/**
Return a new CertificateInfoOrdered that only contains
the Distinguished Name (DN) types found in the input object.
\param in the certificate info to extract from
*/
QCA_EXPORT CertificateInfoOrdered orderedDNOnly(const CertificateInfoOrdered &in);
inline QString CertificateInfoOrdered::toString() const
{
- return orderedToDNString(*this);
+ return orderedToDNString(*this);
}
inline CertificateInfoOrdered CertificateInfoOrdered::dnOnly() const
{
- return orderedDNOnly(*this);
+ return orderedDNOnly(*this);
}
/**
%Certificate constraints type
*/
typedef QList<ConstraintType> Constraints;
/**
Create a list of unique friendly names among a list of certificates
\param list the list of certificates for which a friendly name is required.
*/
QCA_EXPORT QStringList makeFriendlyNames(const QList<Certificate> &list);
/**
\class CertificateOptions qca_cert.h QtCrypto
%Certificate options
\note In SPKAC mode, all options are ignored except for challenge
\ingroup UserAPI
*/
class QCA_EXPORT CertificateOptions
{
public:
- /**
- Create a Certificate options set
+ /**
+ Create a Certificate options set
- \param format the format to create the certificate request in
- */
- CertificateOptions(CertificateRequestFormat format = PKCS10);
+ \param format the format to create the certificate request in
+ */
+ CertificateOptions(CertificateRequestFormat format = PKCS10);
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the Certificate Options to copy into this object
- */
- CertificateOptions(const CertificateOptions &from);
- ~CertificateOptions();
+ \param from the Certificate Options to copy into this object
+ */
+ CertificateOptions(const CertificateOptions &from);
+ ~CertificateOptions();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the Certificate Options to copy into this object
- */
- CertificateOptions & operator=(const CertificateOptions &from);
+ \param from the Certificate Options to copy into this object
+ */
+ CertificateOptions &operator=(const CertificateOptions &from);
- /**
- test the format type for this certificate
- */
- CertificateRequestFormat format() const;
+ /**
+ test the format type for this certificate
+ */
+ CertificateRequestFormat format() const;
- /**
- Specify the format for this certificate
+ /**
+ Specify the format for this certificate
- \param f the format to use
- */
- void setFormat(CertificateRequestFormat f);
+ \param f the format to use
+ */
+ void setFormat(CertificateRequestFormat f);
- /**
- Test if the certificate options object is valid
+ /**
+ Test if the certificate options object is valid
- \return true if the certificate options object is valid
- */
- bool isValid() const;
+ \return true if the certificate options object is valid
+ */
+ bool isValid() const;
- /**
- The challenge part of the certificate
+ /**
+ The challenge part of the certificate
- For CertificateRequest only
+ For CertificateRequest only
- \sa setChallenge
- */
- QString challenge() const;
+ \sa setChallenge
+ */
+ QString challenge() const;
- /**
- Information on the subject of the certificate
+ /**
+ Information on the subject of the certificate
- \sa setInfo
- */
- CertificateInfo info() const;
+ \sa setInfo
+ */
+ CertificateInfo info() const;
- /**
- Information on the subject of the certificate, in the
- exact order the items will be written
+ /**
+ Information on the subject of the certificate, in the
+ exact order the items will be written
- \sa setInfoOrdered
- */
- CertificateInfoOrdered infoOrdered() const;
+ \sa setInfoOrdered
+ */
+ CertificateInfoOrdered infoOrdered() const;
- /**
- List the constraints on this certificate
- */
- Constraints constraints() const;
+ /**
+ List the constraints on this certificate
+ */
+ Constraints constraints() const;
- /**
- list the policies on this certificate
- */
- QStringList policies() const;
+ /**
+ list the policies on this certificate
+ */
+ QStringList policies() const;
- /**
- list of URI locations for CRL files
+ /**
+ list of URI locations for CRL files
- each URI refers to the same CRL file
+ each URI refers to the same CRL file
- For Certificate creation only
- */
- QStringList crlLocations() const;
+ For Certificate creation only
+ */
+ QStringList crlLocations() const;
- /**
- list of URI locations for issuer certificate files
+ /**
+ list of URI locations for issuer certificate files
- each URI refers to the same issuer file
+ each URI refers to the same issuer file
- For Certificate creation only
- */
- QStringList issuerLocations() const;
+ For Certificate creation only
+ */
+ QStringList issuerLocations() const;
- /**
- list of URI locations for OCSP services
+ /**
+ list of URI locations for OCSP services
- For Certificate creation only
- */
- QStringList ocspLocations() const;
+ For Certificate creation only
+ */
+ QStringList ocspLocations() const;
- /**
- test if the certificate is a CA cert
+ /**
+ test if the certificate is a CA cert
- \sa setAsCA
- \sa setAsUser
- */
- bool isCA() const;
+ \sa setAsCA
+ \sa setAsUser
+ */
+ bool isCA() const;
- /**
- return the path limit on this certificate
- */
- int pathLimit() const;
+ /**
+ return the path limit on this certificate
+ */
+ int pathLimit() const;
- /**
- The serial number for the certificate
+ /**
+ The serial number for the certificate
- For Certificate creation only
- */
- BigInteger serialNumber() const;
+ For Certificate creation only
+ */
+ BigInteger serialNumber() const;
- /**
- the first time the certificate will be valid
+ /**
+ the first time the certificate will be valid
- For Certificate creation only
- */
- QDateTime notValidBefore() const;
+ For Certificate creation only
+ */
+ QDateTime notValidBefore() const;
- /**
- the last time the certificate is valid
+ /**
+ the last time the certificate is valid
- For Certificate creation only
- */
- QDateTime notValidAfter() const;
+ For Certificate creation only
+ */
+ QDateTime notValidAfter() const;
- /**
- Specify the challenge associated with this
- certificate
+ /**
+ Specify the challenge associated with this
+ certificate
- \param s the challenge string
+ \param s the challenge string
- \sa challenge()
- */
- void setChallenge(const QString &s);
+ \sa challenge()
+ */
+ void setChallenge(const QString &s);
- /**
- Specify information for the the subject associated with the
- certificate
+ /**
+ Specify information for the the subject associated with the
+ certificate
- \param info the information for the subject
+ \param info the information for the subject
- \sa info()
- */
- void setInfo(const CertificateInfo &info);
+ \sa info()
+ */
+ void setInfo(const CertificateInfo &info);
- /**
- Specify information for the the subject associated with the
- certificate
+ /**
+ Specify information for the the subject associated with the
+ certificate
- \param info the information for the subject
+ \param info the information for the subject
- \sa info()
- */
- void setInfoOrdered(const CertificateInfoOrdered &info);
+ \sa info()
+ */
+ void setInfoOrdered(const CertificateInfoOrdered &info);
- /**
- set the constraints on the certificate
+ /**
+ set the constraints on the certificate
- \param constraints the constraints to be used for the certificate
- */
- void setConstraints(const Constraints &constraints);
+ \param constraints the constraints to be used for the certificate
+ */
+ void setConstraints(const Constraints &constraints);
- /**
- set the policies on the certificate
+ /**
+ set the policies on the certificate
- \param policies the policies to be used for the certificate
- */
- void setPolicies(const QStringList &policies);
+ \param policies the policies to be used for the certificate
+ */
+ void setPolicies(const QStringList &policies);
- /**
- set the CRL locations of the certificate
+ /**
+ set the CRL locations of the certificate
- each location refers to the same CRL.
+ each location refers to the same CRL.
- \param locations a list of URIs to CRL files
- */
- void setCRLLocations(const QStringList &locations);
+ \param locations a list of URIs to CRL files
+ */
+ void setCRLLocations(const QStringList &locations);
- /**
- set the issuer certificate locations of the certificate
+ /**
+ set the issuer certificate locations of the certificate
- each location refers to the same issuer file.
+ each location refers to the same issuer file.
- \param locations a list of URIs to issuer certificate files
- */
- void setIssuerLocations(const QStringList &locations);
+ \param locations a list of URIs to issuer certificate files
+ */
+ void setIssuerLocations(const QStringList &locations);
- /**
- set the OCSP service locations of the certificate
+ /**
+ set the OCSP service locations of the certificate
- \param locations a list of URIs to OCSP services
- */
- void setOCSPLocations(const QStringList &locations);
+ \param locations a list of URIs to OCSP services
+ */
+ void setOCSPLocations(const QStringList &locations);
- /**
- set the certificate to be a CA cert
+ /**
+ set the certificate to be a CA cert
- \param pathLimit the number of intermediate certificates allowable
- */
- void setAsCA(int pathLimit = 8); // value from Botan
+ \param pathLimit the number of intermediate certificates allowable
+ */
+ void setAsCA(int pathLimit = 8); // value from Botan
- /**
- set the certificate to be a user cert (this is the default)
- */
- void setAsUser();
+ /**
+ set the certificate to be a user cert (this is the default)
+ */
+ void setAsUser();
- /**
- Set the serial number property on this certificate
+ /**
+ Set the serial number property on this certificate
- \param i the serial number to use
- */
- void setSerialNumber(const BigInteger &i);
+ \param i the serial number to use
+ */
+ void setSerialNumber(const BigInteger &i);
- /**
- Set the validity period for the certificate
+ /**
+ Set the validity period for the certificate
- \param start the first time this certificate becomes valid
- \param end the last time this certificate is valid
- */
- void setValidityPeriod(const QDateTime &start, const QDateTime &end);
+ \param start the first time this certificate becomes valid
+ \param end the last time this certificate is valid
+ */
+ void setValidityPeriod(const QDateTime &start, const QDateTime &end);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class Certificate qca_cert.h QtCrypto
Public Key (X.509) certificate
This class contains one X.509 certificate
\ingroup UserAPI
*/
class QCA_EXPORT Certificate : public Algorithm
{
public:
- /**
- Create an empty Certificate
- */
- Certificate();
-
- /**
- Create a Certificate from a PEM encoded file
-
- \param fileName the name (and path, if required)
- of the file that contains the PEM encoded certificate
- */
- Certificate(const QString &fileName);
-
- /**
- Create a Certificate with specified options and a specified private
- key
-
- \param opts the options to use
- \param key the private key for this certificate
- \param provider the provider to use to create this key, if a
- particular provider is required
- */
- Certificate(const CertificateOptions &opts, const PrivateKey &key, const QString &provider = QString());
-
- /**
- Standard copy constructor
-
- \param from the certificate to copy from
- */
- Certificate(const Certificate &from);
-
- ~Certificate();
-
- /**
- Standard assignment operator
-
- \param from the Certificate to assign from
- */
- Certificate & operator=(const Certificate &from);
-
- /**
- Test if the certificate is empty (null)
- \return true if the certificate is null
- */
- bool isNull() const;
-
- /**
- The earliest date that the certificate is valid
- */
- QDateTime notValidBefore() const;
-
- /**
- The latest date that the certificate is valid
- */
- QDateTime notValidAfter() const;
-
- /**
- Properties of the subject of the certificate, as a QMultiMap
-
- This is the method that provides information on the
- subject organisation, common name, DNS name, and so
- on. The list of information types (i.e. the key to
- the multi-map) is a CertificateInfoType. The values
- are a list of QString.
-
- An example of how you can iterate over the list is:
- \code
-foreach( QString dns, info.values(QCA::DNS) )
-{
- std::cout << " " << qPrintable(dns) << std::endl;
-}
- \endcode
- */
- CertificateInfo subjectInfo() const;
-
- /**
- Properties of the subject of the certificate, as
- an ordered list (QList of CertificateInfoPair).
-
- This allows access to the certificate information
- in the same order as they appear in a certificate.
- Each pair in the list has a type and a value.
-
- For example:
- \code
-CertificateInfoOrdered info = cert.subjectInfoOrdered();
-// info[0].type == CommonName
-// info[0].value == "example.com"
- \endcode
-
- \sa subjectInfo for an unordered version
- \sa issuerInfoOrdered for the ordered information on the issuer
- \sa CertificateInfoPair for the elements in the list
- */
- CertificateInfoOrdered subjectInfoOrdered() const;
-
- /**
- Properties of the issuer of the certificate
-
- \sa subjectInfo for how the return value works.
- */
- CertificateInfo issuerInfo() const;
-
- /**
- Properties of the issuer of the certificate, as
- an ordered list (QList of CertificateInfoPair).
-
- This allows access to the certificate information
- in the same order as they appear in a certificate.
- Each pair in the list has a type and a value.
-
- \sa issuerInfo for an unordered version
- \sa subjectInfoOrdered for the ordered information on the subject
- \sa CertificateInfoPair for the elements in the list
- */
- CertificateInfoOrdered issuerInfoOrdered() const;
-
- /**
- The constraints that apply to this certificate
- */
- Constraints constraints() const;
-
- /**
- The policies that apply to this certificate
-
- Policies are specified as strings containing OIDs
- */
- QStringList policies() const;
-
- /**
- List of URI locations for CRL files
-
- Each URI refers to the same CRL file
- */
- QStringList crlLocations() const;
-
- /**
- List of URI locations for issuer certificate files
-
- Each URI refers to the same issuer file
- */
- QStringList issuerLocations() const;
-
- /**
- List of URI locations for OCSP services
- */
- QStringList ocspLocations() const;
-
- /**
- The common name of the subject of the certificate
-
- Common names are normally the name of a person, company or
- organisation
- */
- QString commonName() const;
-
- /**
- The serial number of the certificate
- */
- BigInteger serialNumber() const;
-
- /**
- The public key associated with the subject of the certificate
- */
- PublicKey subjectPublicKey() const;
-
- /**
- Test if the Certificate is valid as a Certificate Authority
-
- \return true if the Certificate is valid as a Certificate Authority
- */
- bool isCA() const;
-
- /**
- Test if the Certificate is self-signed
-
- \return true if the certificate is self-signed
- */
- bool isSelfSigned() const;
-
- /**
- Test if the Certificate has signed another Certificate
- object and is therefore the issuer
-
- \param other the certificate to test
-
- \return true if this certificate is the issuer of the argument
- */
- bool isIssuerOf(const Certificate &other) const;
-
- /**
- The upper bound of the number of links in the certificate
- chain, if any
- */
- int pathLimit() const;
-
- /**
- The signature algorithm used for the signature on this certificate
- */
- SignatureAlgorithm signatureAlgorithm() const;
-
- /**
- The key identifier associated with the subject
- */
- QByteArray subjectKeyId() const;
-
- /**
- The key identifier associated with the issuer
- */
- QByteArray issuerKeyId() const;
-
- /**
- Check the validity of a certificate
-
- \param trusted a collection of trusted certificates
- \param untrusted a collection of additional certificates, not
- necessarily trusted
- \param u the use required for the certificate
- \param vf the conditions to validate
-
- \note This function may block
- */
- Validity validate(const CertificateCollection &trusted, const CertificateCollection &untrusted, UsageMode u = UsageAny, ValidateFlags vf = ValidateAll) const;
-
- /**
- Export the Certificate into a DER format
- */
- QByteArray toDER() const;
-
- /**
- Export the Certificate into a PEM format
- */
- QString toPEM() const;
-
- /**
- Export the Certificate into PEM format in a file
-
- \param fileName the name of the file to use
- */
- bool toPEMFile(const QString &fileName) const;
-
- /**
- Import the certificate from DER
-
- \param a the array containing the certificate in DER format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
-
- \return the Certificate corresponding to the certificate in the
- provided array
- */
- static Certificate fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Import the certificate from PEM format
-
- \param s the string containing the certificate in PEM format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
-
- \return the Certificate corresponding to the certificate in the
- provided string
- */
- static Certificate fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Import the certificate from a file
-
- \param fileName the name (and path, if required) of the file
- containing the certificate in PEM format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
-
- \return the Certificate corresponding to the certificate in the
- provided string
- */
- static Certificate fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Test if the subject of the certificate matches a specified host
- name
-
- This will return true (indicating a match), if the specified host
- name meets the RFC 2818 validation rules with this certificate.
-
- If the host is an internationalized domain name, then it must be
- provided in unicode format, not in IDNA ACE/punycode format.
-
- \param host the name of the host to compare to
- */
- bool matchesHostName(const QString &host) const;
-
- /**
- Test for equality of two certificates
-
- \param a the certificate to compare this certificate with
-
- \return true if the two certificates are the same
- */
- bool operator==(const Certificate &a) const;
-
- /**
- Inequality operator
+ /**
+ Create an empty Certificate
+ */
+ Certificate();
+
+ /**
+ Create a Certificate from a PEM encoded file
+
+ \param fileName the name (and path, if required)
+ of the file that contains the PEM encoded certificate
+ */
+ Certificate(const QString &fileName);
+
+ /**
+ Create a Certificate with specified options and a specified private
+ key
+
+ \param opts the options to use
+ \param key the private key for this certificate
+ \param provider the provider to use to create this key, if a
+ particular provider is required
+ */
+ Certificate(const CertificateOptions &opts, const PrivateKey &key, const QString &provider = QString());
+
+ /**
+ Standard copy constructor
+
+ \param from the certificate to copy from
+ */
+ Certificate(const Certificate &from);
+
+ ~Certificate();
+
+ /**
+ Standard assignment operator
+
+ \param from the Certificate to assign from
+ */
+ Certificate &operator=(const Certificate &from);
+
+ /**
+ Test if the certificate is empty (null)
+ \return true if the certificate is null
+ */
+ bool isNull() const;
+
+ /**
+ The earliest date that the certificate is valid
+ */
+ QDateTime notValidBefore() const;
+
+ /**
+ The latest date that the certificate is valid
+ */
+ QDateTime notValidAfter() const;
+
+ /**
+ Properties of the subject of the certificate, as a QMultiMap
+
+ This is the method that provides information on the
+ subject organisation, common name, DNS name, and so
+ on. The list of information types (i.e. the key to
+ the multi-map) is a CertificateInfoType. The values
+ are a list of QString.
+
+ An example of how you can iterate over the list is:
+ \code
+ foreach( QString dns, info.values(QCA::DNS) )
+ {
+ std::cout << " " << qPrintable(dns) << std::endl;
+ }
+ \endcode
+ */
+ CertificateInfo subjectInfo() const;
+
+ /**
+ Properties of the subject of the certificate, as
+ an ordered list (QList of CertificateInfoPair).
+
+ This allows access to the certificate information
+ in the same order as they appear in a certificate.
+ Each pair in the list has a type and a value.
+
+ For example:
+ \code
+ CertificateInfoOrdered info = cert.subjectInfoOrdered();
+ // info[0].type == CommonName
+ // info[0].value == "example.com"
+ \endcode
+
+ \sa subjectInfo for an unordered version
+ \sa issuerInfoOrdered for the ordered information on the issuer
+ \sa CertificateInfoPair for the elements in the list
+ */
+ CertificateInfoOrdered subjectInfoOrdered() const;
+
+ /**
+ Properties of the issuer of the certificate
+
+ \sa subjectInfo for how the return value works.
+ */
+ CertificateInfo issuerInfo() const;
+
+ /**
+ Properties of the issuer of the certificate, as
+ an ordered list (QList of CertificateInfoPair).
+
+ This allows access to the certificate information
+ in the same order as they appear in a certificate.
+ Each pair in the list has a type and a value.
+
+ \sa issuerInfo for an unordered version
+ \sa subjectInfoOrdered for the ordered information on the subject
+ \sa CertificateInfoPair for the elements in the list
+ */
+ CertificateInfoOrdered issuerInfoOrdered() const;
+
+ /**
+ The constraints that apply to this certificate
+ */
+ Constraints constraints() const;
+
+ /**
+ The policies that apply to this certificate
+
+ Policies are specified as strings containing OIDs
+ */
+ QStringList policies() const;
+
+ /**
+ List of URI locations for CRL files
+
+ Each URI refers to the same CRL file
+ */
+ QStringList crlLocations() const;
+
+ /**
+ List of URI locations for issuer certificate files
+
+ Each URI refers to the same issuer file
+ */
+ QStringList issuerLocations() const;
+
+ /**
+ List of URI locations for OCSP services
+ */
+ QStringList ocspLocations() const;
+
+ /**
+ The common name of the subject of the certificate
+
+ Common names are normally the name of a person, company or
+ organisation
+ */
+ QString commonName() const;
+
+ /**
+ The serial number of the certificate
+ */
+ BigInteger serialNumber() const;
+
+ /**
+ The public key associated with the subject of the certificate
+ */
+ PublicKey subjectPublicKey() const;
+
+ /**
+ Test if the Certificate is valid as a Certificate Authority
+
+ \return true if the Certificate is valid as a Certificate Authority
+ */
+ bool isCA() const;
+
+ /**
+ Test if the Certificate is self-signed
+
+ \return true if the certificate is self-signed
+ */
+ bool isSelfSigned() const;
+
+ /**
+ Test if the Certificate has signed another Certificate
+ object and is therefore the issuer
+
+ \param other the certificate to test
+
+ \return true if this certificate is the issuer of the argument
+ */
+ bool isIssuerOf(const Certificate &other) const;
+
+ /**
+ The upper bound of the number of links in the certificate
+ chain, if any
+ */
+ int pathLimit() const;
+
+ /**
+ The signature algorithm used for the signature on this certificate
+ */
+ SignatureAlgorithm signatureAlgorithm() const;
+
+ /**
+ The key identifier associated with the subject
+ */
+ QByteArray subjectKeyId() const;
+
+ /**
+ The key identifier associated with the issuer
+ */
+ QByteArray issuerKeyId() const;
+
+ /**
+ Check the validity of a certificate
+
+ \param trusted a collection of trusted certificates
+ \param untrusted a collection of additional certificates, not
+ necessarily trusted
+ \param u the use required for the certificate
+ \param vf the conditions to validate
+
+ \note This function may block
+ */
+ Validity validate(const CertificateCollection &trusted, const CertificateCollection &untrusted, UsageMode u = UsageAny, ValidateFlags vf = ValidateAll) const;
+
+ /**
+ Export the Certificate into a DER format
+ */
+ QByteArray toDER() const;
+
+ /**
+ Export the Certificate into a PEM format
+ */
+ QString toPEM() const;
+
+ /**
+ Export the Certificate into PEM format in a file
+
+ \param fileName the name of the file to use
+ */
+ bool toPEMFile(const QString &fileName) const;
+
+ /**
+ Import the certificate from DER
+
+ \param a the array containing the certificate in DER format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
+
+ \return the Certificate corresponding to the certificate in the
+ provided array
+ */
+ static Certificate fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Import the certificate from PEM format
+
+ \param s the string containing the certificate in PEM format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
+
+ \return the Certificate corresponding to the certificate in the
+ provided string
+ */
+ static Certificate fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Import the certificate from a file
+
+ \param fileName the name (and path, if required) of the file
+ containing the certificate in PEM format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
+
+ \return the Certificate corresponding to the certificate in the
+ provided string
+ */
+ static Certificate fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Test if the subject of the certificate matches a specified host
+ name
+
+ This will return true (indicating a match), if the specified host
+ name meets the RFC 2818 validation rules with this certificate.
+
+ If the host is an internationalized domain name, then it must be
+ provided in unicode format, not in IDNA ACE/punycode format.
+
+ \param host the name of the host to compare to
+ */
+ bool matchesHostName(const QString &host) const;
+
+ /**
+ Test for equality of two certificates
+
+ \param a the certificate to compare this certificate with
+
+ \return true if the two certificates are the same
+ */
+ bool operator==(const Certificate &a) const;
+
+ /**
+ Inequality operator
- \param other the certificate to compare this certificate with
- */
- inline bool operator!=(const Certificate &other) const
- {
- return !(*this == other);
- }
-
- /**
- \internal
+ \param other the certificate to compare this certificate with
+ */
+ inline bool operator!=(const Certificate &other) const
+ {
+ return !(*this == other);
+ }
+
+ /**
+ \internal
- \param c context (internal)
- */
- void change(CertContext *c);
+ \param c context (internal)
+ */
+ void change(CertContext *c);
private:
- class Private;
- friend class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ friend class Private;
+ QSharedDataPointer<Private> d;
- friend class CertificateChain;
- Validity chain_validate(const CertificateChain &chain, const CertificateCollection &trusted, const QList<CRL> &untrusted_crls, UsageMode u, ValidateFlags vf) const;
- CertificateChain chain_complete(const CertificateChain &chain, const QList<Certificate> &issuers, Validity *result) const;
+ friend class CertificateChain;
+ Validity chain_validate(const CertificateChain &chain, const CertificateCollection &trusted, const QList<CRL> &untrusted_crls, UsageMode u, ValidateFlags vf) const;
+ CertificateChain chain_complete(const CertificateChain &chain, const QList<Certificate> &issuers, Validity *result) const;
};
/**
\class CertificateChain qca_cert.h QtCrypto
A chain of related Certificates
CertificateChain is a list (a QList) of certificates that are related by
the signature from one to another. If Certificate C signs Certificate B,
and Certificate B signs Certificate A, then C, B and A form a chain.
The normal use of a CertificateChain is from a end-user Certificate (called
the primary, equivalent to QList::first()) through some intermediate
Certificates to some other Certificate (QList::last()), which might be a
root Certificate Authority, but does not need to be.
You can build up the chain using normal QList operations, such as
QList::append().
\sa QCA::CertificateCollection for an alternative way to represent a group
of Certificates that do not necessarily have a chained relationship.
\ingroup UserAPI
*/
class CertificateChain : public QList<Certificate>
{
public:
- /**
- Create an empty certificate chain
- */
- inline CertificateChain() {}
-
- /**
- Create a certificate chain, starting at the specified certificate
-
- \param primary the end-user certificate that forms one end of the
- chain
- */
- inline CertificateChain(const Certificate &primary) { append(primary); }
-
- /**
- Return the primary (end-user) Certificate
- */
- inline const Certificate & primary() const { return first(); }
-
- /**
- Check the validity of a certificate chain
-
- \param trusted a collection of trusted certificates
- \param untrusted_crls a list of additional CRLs, not necessarily
- trusted
- \param u the use required for the primary certificate
- \param vf the conditions to validate
-
- \note This function may block
-
- \sa Certificate::validate()
- */
- inline Validity validate(const CertificateCollection &trusted, const QList<CRL> &untrusted_crls = QList<CRL>(), UsageMode u = UsageAny, ValidateFlags vf = ValidateAll) const;
-
- /**
- Complete a certificate chain for the primary certificate, using the
- rest of the certificates in the chain object, as well as those in
- \a issuers, as possible issuers in the chain. If there are issuers
- missing, then the chain might be incomplete (at the worst case, if
- no issuers exist for the primary certificate, then the resulting
- chain will consist of just the primary certificate). Use the
- \a result argument to find out if there was a problem during
- completion. A result of ValidityGood means the chain was completed
- successfully.
-
- The newly constructed CertificateChain is returned.
-
- If the certificate chain is empty, then this will return an empty
- CertificateChain object.
-
- \param issuers a pool of issuers to draw from as necessary
- \param result the result of the completion operation
-
- \note This function may block
-
- \sa validate
- */
- inline CertificateChain complete(const QList<Certificate> &issuers = QList<Certificate>(), Validity *result = 0) const;
+ /**
+ Create an empty certificate chain
+ */
+ inline CertificateChain() {}
+
+ /**
+ Create a certificate chain, starting at the specified certificate
+
+ \param primary the end-user certificate that forms one end of the
+ chain
+ */
+ inline CertificateChain(const Certificate &primary)
+ {
+ append(primary);
+ }
+
+ /**
+ Return the primary (end-user) Certificate
+ */
+ inline const Certificate &primary() const
+ {
+ return first();
+ }
+
+ /**
+ Check the validity of a certificate chain
+
+ \param trusted a collection of trusted certificates
+ \param untrusted_crls a list of additional CRLs, not necessarily
+ trusted
+ \param u the use required for the primary certificate
+ \param vf the conditions to validate
+
+ \note This function may block
+
+ \sa Certificate::validate()
+ */
+ inline Validity validate(const CertificateCollection &trusted, const QList<CRL> &untrusted_crls = QList<CRL>(), UsageMode u = UsageAny, ValidateFlags vf = ValidateAll) const;
+
+ /**
+ Complete a certificate chain for the primary certificate, using the
+ rest of the certificates in the chain object, as well as those in
+ \a issuers, as possible issuers in the chain. If there are issuers
+ missing, then the chain might be incomplete (at the worst case, if
+ no issuers exist for the primary certificate, then the resulting
+ chain will consist of just the primary certificate). Use the
+ \a result argument to find out if there was a problem during
+ completion. A result of ValidityGood means the chain was completed
+ successfully.
+
+ The newly constructed CertificateChain is returned.
+
+ If the certificate chain is empty, then this will return an empty
+ CertificateChain object.
+
+ \param issuers a pool of issuers to draw from as necessary
+ \param result the result of the completion operation
+
+ \note This function may block
+
+ \sa validate
+ */
+ inline CertificateChain complete(const QList<Certificate> &issuers = QList<Certificate>(), Validity *result = 0) const;
};
inline Validity CertificateChain::validate(const CertificateCollection &trusted, const QList<CRL> &untrusted_crls, UsageMode u, ValidateFlags vf) const
{
- if(isEmpty())
- return ErrorValidityUnknown;
- return first().chain_validate(*this, trusted, untrusted_crls, u, vf);
+ if (isEmpty()) {
+ return ErrorValidityUnknown;
+ }
+ return first().chain_validate(*this, trusted, untrusted_crls, u, vf);
}
inline CertificateChain CertificateChain::complete(const QList<Certificate> &issuers, Validity *result) const
{
- if(isEmpty())
- return CertificateChain();
- return first().chain_complete(*this, issuers, result);
+ if (isEmpty()) {
+ return CertificateChain();
+ }
+ return first().chain_complete(*this, issuers, result);
}
/**
\class CertificateRequest qca_cert.h QtCrypto
%Certificate Request
A CertificateRequest is a unsigned request for a Certificate
\ingroup UserAPI
*/
class QCA_EXPORT CertificateRequest : public Algorithm
{
public:
- /**
- Create an empty certificate request
- */
- CertificateRequest();
+ /**
+ Create an empty certificate request
+ */
+ CertificateRequest();
- /**
- Create a certificate request based on the contents of a file
+ /**
+ Create a certificate request based on the contents of a file
- \param fileName the file (and path, if necessary) containing a PEM
- encoded certificate request
- */
- CertificateRequest(const QString &fileName);
+ \param fileName the file (and path, if necessary) containing a PEM
+ encoded certificate request
+ */
+ CertificateRequest(const QString &fileName);
- /**
- Create a certificate request based on specified options
+ /**
+ Create a certificate request based on specified options
- \param opts the options to use in the certificate request
- \param key the private key that matches the certificate being
- requested
- \param provider the provider to use, if a specific provider is
- required
- */
- CertificateRequest(const CertificateOptions &opts, const PrivateKey &key, const QString &provider = QString());
+ \param opts the options to use in the certificate request
+ \param key the private key that matches the certificate being
+ requested
+ \param provider the provider to use, if a specific provider is
+ required
+ */
+ CertificateRequest(const CertificateOptions &opts, const PrivateKey &key, const QString &provider = QString());
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the request to copy from
- */
- CertificateRequest(const CertificateRequest &from);
+ \param from the request to copy from
+ */
+ CertificateRequest(const CertificateRequest &from);
- ~CertificateRequest();
+ ~CertificateRequest();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the request to assign from
- */
- CertificateRequest & operator=(const CertificateRequest &from);
+ \param from the request to assign from
+ */
+ CertificateRequest &operator=(const CertificateRequest &from);
- /**
- test if the certificate request is empty
+ /**
+ test if the certificate request is empty
- \return true if the certificate request is empty, otherwise false
- */
- bool isNull() const;
+ \return true if the certificate request is empty, otherwise false
+ */
+ bool isNull() const;
- /**
- Test if the certificate request can use a specified format
+ /**
+ Test if the certificate request can use a specified format
- \param f the format to test for
- \param provider the provider to use, if a specific provider is
- required
+ \param f the format to test for
+ \param provider the provider to use, if a specific provider is
+ required
- \return true if the certificate request can use the specified
- format
- */
- static bool canUseFormat(CertificateRequestFormat f, const QString &provider = QString());
+ \return true if the certificate request can use the specified
+ format
+ */
+ static bool canUseFormat(CertificateRequestFormat f, const QString &provider = QString());
- /**
- the format that this Certificate request is in
- */
- CertificateRequestFormat format() const;
+ /**
+ the format that this Certificate request is in
+ */
+ CertificateRequestFormat format() const;
- /**
- Information on the subject of the certificate being requested
+ /**
+ Information on the subject of the certificate being requested
- \note this only applies to PKCS#10 format certificate requests
+ \note this only applies to PKCS#10 format certificate requests
- \sa subjectInfoOrdered for a version that maintains order
- in the subject information.
- */
- CertificateInfo subjectInfo() const;
+ \sa subjectInfoOrdered for a version that maintains order
+ in the subject information.
+ */
+ CertificateInfo subjectInfo() const;
- /**
- Information on the subject of the certificate being requested, as
- an ordered list (QList of CertificateInfoPair).
+ /**
+ Information on the subject of the certificate being requested, as
+ an ordered list (QList of CertificateInfoPair).
- \note this only applies to PKCS#10 format certificate requests
+ \note this only applies to PKCS#10 format certificate requests
- \sa subjectInfo for a version that does not maintain order, but
- allows access based on a multimap.
- \sa CertificateInfoPair for the elements in the list
- */
- CertificateInfoOrdered subjectInfoOrdered() const;
+ \sa subjectInfo for a version that does not maintain order, but
+ allows access based on a multimap.
+ \sa CertificateInfoPair for the elements in the list
+ */
+ CertificateInfoOrdered subjectInfoOrdered() const;
- /**
- The constraints that apply to this certificate request
+ /**
+ The constraints that apply to this certificate request
- \note this only applies to PKCS#10 format certificate requests
- */
- Constraints constraints() const;
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ Constraints constraints() const;
- /**
- The policies that apply to this certificate request
+ /**
+ The policies that apply to this certificate request
- \note this only applies to PKCS#10 format certificate requests
- */
- QStringList policies() const;
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ QStringList policies() const;
- /**
- The public key belonging to the issuer
- */
- PublicKey subjectPublicKey() const;
+ /**
+ The public key belonging to the issuer
+ */
+ PublicKey subjectPublicKey() const;
- /**
- Test if this Certificate Request is for a Certificate Authority
- certificate
+ /**
+ Test if this Certificate Request is for a Certificate Authority
+ certificate
- \note this only applies to PKCS#10 format certificate requests
- */
- bool isCA() const;
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ bool isCA() const;
- /**
- The path limit for the certificate in this Certificate Request
+ /**
+ The path limit for the certificate in this Certificate Request
- \note this only applies to PKCS#10 format certificate requests
- */
- int pathLimit() const;
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ int pathLimit() const;
- /**
- The challenge associated with this certificate request
- */
- QString challenge() const;
+ /**
+ The challenge associated with this certificate request
+ */
+ QString challenge() const;
- /**
- The algorithm used to make the signature on this certificate
- request
- */
- SignatureAlgorithm signatureAlgorithm() const;
+ /**
+ The algorithm used to make the signature on this certificate
+ request
+ */
+ SignatureAlgorithm signatureAlgorithm() const;
- /**
- Test for equality of two certificate requests
+ /**
+ Test for equality of two certificate requests
- \param csr the certificate request to be compared to this certificate request
+ \param csr the certificate request to be compared to this certificate request
- \return true if the two certificate requests are the same
- */
- bool operator==(const CertificateRequest &csr) const;
+ \return true if the two certificate requests are the same
+ */
+ bool operator==(const CertificateRequest &csr) const;
- /**
- Inequality operator
+ /**
+ Inequality operator
- \param other the certificate request to be compared to this certificate request
- */
- inline bool operator!=(const CertificateRequest &other) const
- {
- return !(*this == other);
- }
+ \param other the certificate request to be compared to this certificate request
+ */
+ inline bool operator!=(const CertificateRequest &other) const
+ {
+ return !(*this == other);
+ }
- /**
- Export the Certificate Request into a DER format
+ /**
+ Export the Certificate Request into a DER format
- \note this only applies to PKCS#10 format certificate requests
- */
- QByteArray toDER() const;
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ QByteArray toDER() const;
- /**
- Export the Certificate Request into a PEM format
+ /**
+ Export the Certificate Request into a PEM format
- \note this only applies to PKCS#10 format certificate requests
- */
- QString toPEM() const;
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ QString toPEM() const;
- /**
- Export the Certificate into PEM format in a file
+ /**
+ Export the Certificate into PEM format in a file
- \param fileName the name of the file to use
+ \param fileName the name of the file to use
- \note this only applies to PKCS#10 format certificate requests
- */
- bool toPEMFile(const QString &fileName) const;
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ bool toPEMFile(const QString &fileName) const;
- /**
- Import the certificate request from DER
+ /**
+ Import the certificate request from DER
- \param a the array containing the certificate request in DER format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ \param a the array containing the certificate request in DER format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CertificateRequest corresponding to the certificate
- request in the provided array
+ \return the CertificateRequest corresponding to the certificate
+ request in the provided array
- \note this only applies to PKCS#10 format certificate requests
- */
- static CertificateRequest fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ static CertificateRequest fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
- /**
- Import the certificate request from PEM format
+ /**
+ Import the certificate request from PEM format
- \param s the string containing the certificate request in PEM
- format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ \param s the string containing the certificate request in PEM
+ format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CertificateRequest corresponding to the certificate
- request in the provided string
+ \return the CertificateRequest corresponding to the certificate
+ request in the provided string
- \note this only applies to PKCS#10 format certificate requests
- */
- static CertificateRequest fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ static CertificateRequest fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
- /**
- Import the certificate request from a file
+ /**
+ Import the certificate request from a file
- \param fileName the name (and path, if required) of the file
- containing the certificate request in PEM format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ \param fileName the name (and path, if required) of the file
+ containing the certificate request in PEM format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CertificateRequest corresponding to the certificate
- request in the provided string
+ \return the CertificateRequest corresponding to the certificate
+ request in the provided string
- \note this only applies to PKCS#10 format certificate requests
- */
- static CertificateRequest fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
+ \note this only applies to PKCS#10 format certificate requests
+ */
+ static CertificateRequest fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
- /**
- Export the CertificateRequest to a string
+ /**
+ Export the CertificateRequest to a string
- \return the string corresponding to the certificate request
+ \return the string corresponding to the certificate request
- \note this only applies to SPKAC format certificate requests
- */
- QString toString() const;
+ \note this only applies to SPKAC format certificate requests
+ */
+ QString toString() const;
- /**
- Import the CertificateRequest from a string
+ /**
+ Import the CertificateRequest from a string
- \param s the string containing to the certificate request
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ \param s the string containing to the certificate request
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CertificateRequest corresponding to the certificate
- request in the provided string
+ \return the CertificateRequest corresponding to the certificate
+ request in the provided string
- \note this only applies to SPKAC format certificate requests
- */
- static CertificateRequest fromString(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
+ \note this only applies to SPKAC format certificate requests
+ */
+ static CertificateRequest fromString(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
- /**
- \internal
+ /**
+ \internal
- \param c context (internal)
- */
- void change(CSRContext *c);
+ \param c context (internal)
+ */
+ void change(CSRContext *c);
private:
- class Private;
- friend class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ friend class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class CRLEntry qca_cert.h QtCrypto
Part of a CRL representing a single certificate
\ingroup UserAPI
*/
class QCA_EXPORT CRLEntry
{
public:
- /**
- The reason why the certificate has been revoked
- */
- enum Reason
- {
- Unspecified, ///< reason is unknown
- KeyCompromise, ///< private key has been compromised
- CACompromise, ///< certificate authority has been compromised
- AffiliationChanged,
- Superseded, ///< certificate has been superseded
- CessationOfOperation,
- CertificateHold, ///< certificate is on hold
- RemoveFromCRL, ///< certificate was previously in a CRL, but is now valid
- PrivilegeWithdrawn,
- AACompromise ///< attribute authority has been compromised
- };
-
- /**
- create an empty CRL entry
- */
- CRLEntry();
-
- /**
- create a CRL entry
-
- \param c the certificate to revoke
- \param r the reason that the certificate is being revoked
- */
- explicit CRLEntry(const Certificate &c, Reason r = Unspecified);
-
- /**
- create a CRL entry
-
- \param serial the serial number of the Certificate being revoked
- \param time the time the Certificate was revoked (or will be
- revoked)
- \param r the reason that the certificate is being revoked
- */
- CRLEntry(const BigInteger serial, const QDateTime &time, Reason r = Unspecified);
-
- /**
- Copy constructor
-
- \param from the CRLEntry to copy from
- */
- CRLEntry(const CRLEntry &from);
-
- ~CRLEntry();
-
- /**
- Standard assignment operator
-
- \param from the CRLEntry to copy from
- */
- CRLEntry & operator=(const CRLEntry &from);
-
- /**
- The serial number of the certificate that is the subject of this CRL entry
- */
- BigInteger serialNumber() const;
-
- /**
- The time this CRL entry was created
- */
- QDateTime time() const;
-
- /**
- Test if this CRL entry is empty
- */
- bool isNull() const;
-
- /**
- The reason that this CRL entry was created
-
- Alternatively, you might like to think of this as the reason that
- the subject certificate has been revoked
- */
- Reason reason() const;
-
- /**
- Test if one CRL entry is "less than" another
-
- CRL entries are compared based on their serial number
-
- \param a the CRL entry to be compared to this CRL entry.
- */
- bool operator<(const CRLEntry &a) const;
-
- /**
- Test for equality of two CRL Entries
-
- \param a the CRL entry to be compared to this CRL entry.
-
- \return true if the two certificates are the same
- */
- bool operator==(const CRLEntry &a) const;
-
- /**
- Inequality operator
-
- \param other the CRL entry to be compared to this CRL entry.
- */
- inline bool operator!=(const CRLEntry &other) const
- {
- return !(*this == other);
- }
+ /**
+ The reason why the certificate has been revoked
+ */
+ enum Reason {
+ Unspecified, ///< reason is unknown
+ KeyCompromise, ///< private key has been compromised
+ CACompromise, ///< certificate authority has been compromised
+ AffiliationChanged,
+ Superseded, ///< certificate has been superseded
+ CessationOfOperation,
+ CertificateHold, ///< certificate is on hold
+ RemoveFromCRL, ///< certificate was previously in a CRL, but is now valid
+ PrivilegeWithdrawn,
+ AACompromise ///< attribute authority has been compromised
+ };
+
+ /**
+ create an empty CRL entry
+ */
+ CRLEntry();
+
+ /**
+ create a CRL entry
+
+ \param c the certificate to revoke
+ \param r the reason that the certificate is being revoked
+ */
+ explicit CRLEntry(const Certificate &c, Reason r = Unspecified);
+
+ /**
+ create a CRL entry
+
+ \param serial the serial number of the Certificate being revoked
+ \param time the time the Certificate was revoked (or will be
+ revoked)
+ \param r the reason that the certificate is being revoked
+ */
+ CRLEntry(const BigInteger serial, const QDateTime &time, Reason r = Unspecified);
+
+ /**
+ Copy constructor
+
+ \param from the CRLEntry to copy from
+ */
+ CRLEntry(const CRLEntry &from);
+
+ ~CRLEntry();
+
+ /**
+ Standard assignment operator
+
+ \param from the CRLEntry to copy from
+ */
+ CRLEntry &operator=(const CRLEntry &from);
+
+ /**
+ The serial number of the certificate that is the subject of this CRL entry
+ */
+ BigInteger serialNumber() const;
+
+ /**
+ The time this CRL entry was created
+ */
+ QDateTime time() const;
+
+ /**
+ Test if this CRL entry is empty
+ */
+ bool isNull() const;
+
+ /**
+ The reason that this CRL entry was created
+
+ Alternatively, you might like to think of this as the reason that
+ the subject certificate has been revoked
+ */
+ Reason reason() const;
+
+ /**
+ Test if one CRL entry is "less than" another
+
+ CRL entries are compared based on their serial number
+
+ \param a the CRL entry to be compared to this CRL entry.
+ */
+ bool operator<(const CRLEntry &a) const;
+
+ /**
+ Test for equality of two CRL Entries
+
+ \param a the CRL entry to be compared to this CRL entry.
+
+ \return true if the two certificates are the same
+ */
+ bool operator==(const CRLEntry &a) const;
+
+ /**
+ Inequality operator
+
+ \param other the CRL entry to be compared to this CRL entry.
+ */
+ inline bool operator!=(const CRLEntry &other) const
+ {
+ return !(*this == other);
+ }
private:
- BigInteger _serial;
- QDateTime _time;
- Reason _reason;
+ BigInteger _serial;
+ QDateTime _time;
+ Reason _reason;
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class CRL qca_cert.h QtCrypto
%Certificate Revocation List
A %CRL is a list of certificates that are special in some
way. The normal reason for including a certificate on a %CRL
is that the certificate should no longer be used. For
example, if a key is compromised, then the associated
certificate may no longer provides appropriate
security. There are other reasons why a certificate may be
placed on a %CRL, as shown in the CRLEntry::Reason
enumeration.
\sa CertificateCollection for a way to handle Certificates
and CRLs as a single entity.
\sa CRLEntry for the %CRL segment representing a single Certificate.
\ingroup UserAPI
*/
class QCA_EXPORT CRL : public Algorithm
{
public:
- CRL();
+ CRL();
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the revocation list to copy from
- */
- CRL(const CRL &from);
+ \param from the revocation list to copy from
+ */
+ CRL(const CRL &from);
- ~CRL();
+ ~CRL();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the revocation list to assign from
- */
- CRL & operator=(const CRL &from);
+ \param from the revocation list to assign from
+ */
+ CRL &operator=(const CRL &from);
- /**
- Test if the CRL is empty
+ /**
+ Test if the CRL is empty
- \return true if the CRL is entry, otherwise return false
- */
- bool isNull() const;
+ \return true if the CRL is entry, otherwise return false
+ */
+ bool isNull() const;
- /**
- Information on the issuer of the CRL as a QMultiMap.
+ /**
+ Information on the issuer of the CRL as a QMultiMap.
- \sa issuerInfoOrdered for a version that maintains the order
- of information fields as per the underlying CRL.
- */
- CertificateInfo issuerInfo() const;
+ \sa issuerInfoOrdered for a version that maintains the order
+ of information fields as per the underlying CRL.
+ */
+ CertificateInfo issuerInfo() const;
- /**
- Information on the issuer of the CRL as an ordered list
- (QList of CertificateInfoPair).
+ /**
+ Information on the issuer of the CRL as an ordered list
+ (QList of CertificateInfoPair).
- \sa issuerInfo for a version that allows lookup based on
- a multimap.
- \sa CertificateInfoPair for the elements in the list
- */
- CertificateInfoOrdered issuerInfoOrdered() const;
+ \sa issuerInfo for a version that allows lookup based on
+ a multimap.
+ \sa CertificateInfoPair for the elements in the list
+ */
+ CertificateInfoOrdered issuerInfoOrdered() const;
- /**
- The CRL serial number. Note that serial numbers are a
- CRL extension, and not all certificates have one.
+ /**
+ The CRL serial number. Note that serial numbers are a
+ CRL extension, and not all certificates have one.
- \return the CRL serial number, or -1 if there is no serial number
- */
- int number() const;
+ \return the CRL serial number, or -1 if there is no serial number
+ */
+ int number() const;
- /**
- the time that this CRL became (or becomes) valid
- */
- QDateTime thisUpdate() const;
+ /**
+ the time that this CRL became (or becomes) valid
+ */
+ QDateTime thisUpdate() const;
- /**
- the time that this CRL will be obsoleted
+ /**
+ the time that this CRL will be obsoleted
- you should obtain an updated CRL at this time
- */
- QDateTime nextUpdate() const;
+ you should obtain an updated CRL at this time
+ */
+ QDateTime nextUpdate() const;
- /**
- a list of the revoked certificates in this CRL
- */
- QList<CRLEntry> revoked() const;
+ /**
+ a list of the revoked certificates in this CRL
+ */
+ QList<CRLEntry> revoked() const;
- /**
- The signature algorithm used for the signature on this CRL
- */
- SignatureAlgorithm signatureAlgorithm() const;
+ /**
+ The signature algorithm used for the signature on this CRL
+ */
+ SignatureAlgorithm signatureAlgorithm() const;
- /**
- The key identification of the CRL issuer
- */
- QByteArray issuerKeyId() const;
+ /**
+ The key identification of the CRL issuer
+ */
+ QByteArray issuerKeyId() const;
- /**
- Test for equality of two %Certificate Revocation Lists
+ /**
+ Test for equality of two %Certificate Revocation Lists
- \param a the CRL to be compared to this CRL
+ \param a the CRL to be compared to this CRL
- \return true if the two CRLs are the same
- */
- bool operator==(const CRL &a) const;
+ \return true if the two CRLs are the same
+ */
+ bool operator==(const CRL &a) const;
- /**
- Inequality operator
+ /**
+ Inequality operator
- \param other the CRL to be compared to this CRL
- */
- inline bool operator!=(const CRL &other) const
- {
- return !(*this == other);
- }
+ \param other the CRL to be compared to this CRL
+ */
+ inline bool operator!=(const CRL &other) const
+ {
+ return !(*this == other);
+ }
- /**
- Export the %Certificate Revocation List (CRL) in DER format
+ /**
+ Export the %Certificate Revocation List (CRL) in DER format
- \return an array containing the CRL in DER format
- */
- QByteArray toDER() const;
+ \return an array containing the CRL in DER format
+ */
+ QByteArray toDER() const;
- /**
- Export the %Certificate Revocation List (CRL) in PEM format
+ /**
+ Export the %Certificate Revocation List (CRL) in PEM format
- \return a string containing the CRL in PEM format
- */
- QString toPEM() const;
+ \return a string containing the CRL in PEM format
+ */
+ QString toPEM() const;
- /**
- Export the %Certificate Revocation List (CRL) into PEM format in a
- file
-
- \param fileName the name of the file to use
- */
- bool toPEMFile(const QString &fileName) const;
-
- /**
- Import a DER encoded %Certificate Revocation List (CRL)
-
- \param a the array containing the CRL in DER format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ /**
+ Export the %Certificate Revocation List (CRL) into PEM format in a
+ file
+
+ \param fileName the name of the file to use
+ */
+ bool toPEMFile(const QString &fileName) const;
+
+ /**
+ Import a DER encoded %Certificate Revocation List (CRL)
+
+ \param a the array containing the CRL in DER format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CRL corresponding to the contents of the array
- */
- static CRL fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
+ \return the CRL corresponding to the contents of the array
+ */
+ static CRL fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
- /**
- Import a PEM encoded %Certificate Revocation List (CRL)
-
- \param s the string containing the CRL in PEM format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ /**
+ Import a PEM encoded %Certificate Revocation List (CRL)
+
+ \param s the string containing the CRL in PEM format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CRL corresponding to the contents of the string
- */
- static CRL fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
+ \return the CRL corresponding to the contents of the string
+ */
+ static CRL fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
- /**
- Import a PEM encoded %Certificate Revocation List (CRL) from a file
+ /**
+ Import a PEM encoded %Certificate Revocation List (CRL) from a file
- \param fileName the name (and path, if required) of the file
- containing the certificate in PEM format
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ \param fileName the name (and path, if required) of the file
+ containing the certificate in PEM format
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CRL in the file
- */
- static CRL fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
+ \return the CRL in the file
+ */
+ static CRL fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
- /**
- \internal
+ /**
+ \internal
- \param c context (internal)
- */
- void change(CRLContext *c);
+ \param c context (internal)
+ */
+ void change(CRLContext *c);
private:
- class Private;
- friend class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ friend class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class CertificateCollection qca_cert.h QtCrypto
Bundle of Certificates and CRLs
CertificateCollection provides a bundle of Certificates and Certificate
Revocation Lists (CRLs), not necessarily related.
\sa QCA::CertificateChain for a representation of a chain of Certificates
related by signatures.
\ingroup UserAPI
*/
class QCA_EXPORT CertificateCollection
{
public:
- /**
- Create an empty Certificate / CRL collection
- */
- CertificateCollection();
+ /**
+ Create an empty Certificate / CRL collection
+ */
+ CertificateCollection();
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the CertificateCollection to copy from
- */
- CertificateCollection(const CertificateCollection &from);
+ \param from the CertificateCollection to copy from
+ */
+ CertificateCollection(const CertificateCollection &from);
- ~CertificateCollection();
+ ~CertificateCollection();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the CertificateCollection to copy from
- */
- CertificateCollection & operator=(const CertificateCollection &from);
+ \param from the CertificateCollection to copy from
+ */
+ CertificateCollection &operator=(const CertificateCollection &from);
- /**
- Append a Certificate to this collection
+ /**
+ Append a Certificate to this collection
- \param cert the Certificate to add to this CertificateCollection
- */
- void addCertificate(const Certificate &cert);
+ \param cert the Certificate to add to this CertificateCollection
+ */
+ void addCertificate(const Certificate &cert);
- /**
- Append a CRL to this collection
+ /**
+ Append a CRL to this collection
- \param crl the certificate revokation list to add to this
- CertificateCollection
- */
- void addCRL(const CRL &crl);
+ \param crl the certificate revokation list to add to this
+ CertificateCollection
+ */
+ void addCRL(const CRL &crl);
- /**
- The Certificates in this collection
- */
- QList<Certificate> certificates() const;
+ /**
+ The Certificates in this collection
+ */
+ QList<Certificate> certificates() const;
- /**
- The CRLs in this collection
- */
- QList<CRL> crls() const;
+ /**
+ The CRLs in this collection
+ */
+ QList<CRL> crls() const;
- /**
- Add another CertificateCollection to this collection
+ /**
+ Add another CertificateCollection to this collection
- \param other the CertificateCollection to add to this collection
- */
- void append(const CertificateCollection &other);
+ \param other the CertificateCollection to add to this collection
+ */
+ void append(const CertificateCollection &other);
- /**
- Add another CertificateCollection to this collection
+ /**
+ Add another CertificateCollection to this collection
- \param other the CertificateCollection to add to this collection
- */
- CertificateCollection operator+(const CertificateCollection &other) const;
+ \param other the CertificateCollection to add to this collection
+ */
+ CertificateCollection operator+(const CertificateCollection &other) const;
- /**
- Add another CertificateCollection to this collection
+ /**
+ Add another CertificateCollection to this collection
- \param other the CertificateCollection to add to this collection
- */
- CertificateCollection & operator+=(const CertificateCollection &other);
+ \param other the CertificateCollection to add to this collection
+ */
+ CertificateCollection &operator+=(const CertificateCollection &other);
- /**
- test if the CertificateCollection can be imported and exported to
- PKCS#7 format
+ /**
+ test if the CertificateCollection can be imported and exported to
+ PKCS#7 format
- \param provider the provider to use, if a specific provider is
- required
+ \param provider the provider to use, if a specific provider is
+ required
- \return true if the CertificateCollection can be imported and
- exported to PKCS#7 format
- */
- static bool canUsePKCS7(const QString &provider = QString());
+ \return true if the CertificateCollection can be imported and
+ exported to PKCS#7 format
+ */
+ static bool canUsePKCS7(const QString &provider = QString());
- /**
- export the CertificateCollection to a plain text file
+ /**
+ export the CertificateCollection to a plain text file
- \param fileName the name (and path, if required) to write the
- contents of the CertificateCollection to
+ \param fileName the name (and path, if required) to write the
+ contents of the CertificateCollection to
- \return true if the export succeeded, otherwise false
- */
- bool toFlatTextFile(const QString &fileName);
+ \return true if the export succeeded, otherwise false
+ */
+ bool toFlatTextFile(const QString &fileName);
- /**
- export the CertificateCollection to a PKCS#7 file
+ /**
+ export the CertificateCollection to a PKCS#7 file
- \param fileName the name (and path, if required) to write the
- contents of the CertificateCollection to
- \param provider the provider to use, if a specific provider is
- required
+ \param fileName the name (and path, if required) to write the
+ contents of the CertificateCollection to
+ \param provider the provider to use, if a specific provider is
+ required
- \return true if the export succeeded, otherwise false
- */
- bool toPKCS7File(const QString &fileName, const QString &provider = QString());
+ \return true if the export succeeded, otherwise false
+ */
+ bool toPKCS7File(const QString &fileName, const QString &provider = QString());
- /**
- import a CertificateCollection from a text file
+ /**
+ import a CertificateCollection from a text file
- \param fileName the name (and path, if required) to read the
- certificate collection from
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ \param fileName the name (and path, if required) to read the
+ certificate collection from
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CertificateCollection corresponding to the contents of
- the file specified in fileName
- */
- static CertificateCollection fromFlatTextFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
+ \return the CertificateCollection corresponding to the contents of
+ the file specified in fileName
+ */
+ static CertificateCollection fromFlatTextFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
- /**
- import a CertificateCollection from a PKCS#7 file
+ /**
+ import a CertificateCollection from a PKCS#7 file
- \param fileName the name (and path, if required) to read the
- certificate collection from
- \param result a pointer to a ConvertResult, which if not-null will
- be set to the conversion status
- \param provider the provider to use, if a specific provider is
- required
+ \param fileName the name (and path, if required) to read the
+ certificate collection from
+ \param result a pointer to a ConvertResult, which if not-null will
+ be set to the conversion status
+ \param provider the provider to use, if a specific provider is
+ required
- \return the CertificateCollection corresponding to the contents of
- the file specified in fileName
- */
- static CertificateCollection fromPKCS7File(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
+ \return the CertificateCollection corresponding to the contents of
+ the file specified in fileName
+ */
+ static CertificateCollection fromPKCS7File(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class CertificateAuthority qca_cert.h QtCrypto
A %Certificate Authority is used to generate Certificates and
%Certificate Revocation Lists (CRLs).
\ingroup UserAPI
*/
class QCA_EXPORT CertificateAuthority : public Algorithm
{
public:
- /**
- Create a new %Certificate Authority
+ /**
+ Create a new %Certificate Authority
- \param cert the CA certificate
- \param key the private key associated with the CA certificate
- \param provider the provider to use, if a specific provider is
- required
- */
- CertificateAuthority(const Certificate &cert, const PrivateKey &key, const QString &provider);
+ \param cert the CA certificate
+ \param key the private key associated with the CA certificate
+ \param provider the provider to use, if a specific provider is
+ required
+ */
+ CertificateAuthority(const Certificate &cert, const PrivateKey &key, const QString &provider);
- /**
- Copy constructor
+ /**
+ Copy constructor
- \param from the CertificateAuthority to copy from
- */
- CertificateAuthority(const CertificateAuthority &from);
+ \param from the CertificateAuthority to copy from
+ */
+ CertificateAuthority(const CertificateAuthority &from);
- ~CertificateAuthority();
+ ~CertificateAuthority();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the CertificateAuthority to copy from
- */
- CertificateAuthority & operator=(const CertificateAuthority &from);
+ \param from the CertificateAuthority to copy from
+ */
+ CertificateAuthority &operator=(const CertificateAuthority &from);
- /**
- The Certificate belonging to the %CertificateAuthority
+ /**
+ The Certificate belonging to the %CertificateAuthority
- This is the Certificate that was passed as an argument to the
- constructor
- */
- Certificate certificate() const;
+ This is the Certificate that was passed as an argument to the
+ constructor
+ */
+ Certificate certificate() const;
- /**
- Create a new Certificate by signing the provider CertificateRequest
+ /**
+ Create a new Certificate by signing the provider CertificateRequest
- \param req the CertificateRequest to sign
- \param notValidAfter the last date that the Certificate will be
- valid
- */
- Certificate signRequest(const CertificateRequest &req, const QDateTime &notValidAfter) const;
+ \param req the CertificateRequest to sign
+ \param notValidAfter the last date that the Certificate will be
+ valid
+ */
+ Certificate signRequest(const CertificateRequest &req, const QDateTime &notValidAfter) const;
- /**
- Create a new Certificate
+ /**
+ Create a new Certificate
- \param key the Public Key to use to create the Certificate
- \param opts the options to use for the new Certificate
- */
- Certificate createCertificate(const PublicKey &key, const CertificateOptions &opts) const;
+ \param key the Public Key to use to create the Certificate
+ \param opts the options to use for the new Certificate
+ */
+ Certificate createCertificate(const PublicKey &key, const CertificateOptions &opts) const;
- /**
- Create a new Certificate Revocation List (CRL)
+ /**
+ Create a new Certificate Revocation List (CRL)
- \param nextUpdate the date that the CRL will be updated
+ \param nextUpdate the date that the CRL will be updated
- \return an empty CRL
- */
- CRL createCRL(const QDateTime &nextUpdate) const;
+ \return an empty CRL
+ */
+ CRL createCRL(const QDateTime &nextUpdate) const;
- /**
- Update the CRL to include new entries
+ /**
+ Update the CRL to include new entries
- \param crl the CRL to update
- \param entries the entries to add to the CRL
- \param nextUpdate the date that this CRL will be updated
+ \param crl the CRL to update
+ \param entries the entries to add to the CRL
+ \param nextUpdate the date that this CRL will be updated
- \return the update CRL
- */
- CRL updateCRL(const CRL &crl, const QList<CRLEntry> &entries, const QDateTime &nextUpdate) const;
+ \return the update CRL
+ */
+ CRL updateCRL(const CRL &crl, const QList<CRLEntry> &entries, const QDateTime &nextUpdate) const;
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class KeyBundle qca_cert.h QtCrypto
Certificate chain and private key pair
KeyBundle is essentially a convience class that holds a
certificate chain and an associated private key. This class
has a number of methods that make it particularly suitable
for accessing a PKCS12 (.p12) format file, however it can
be used as just a container for a Certificate, its
associated PrivateKey and optionally additional
X.509 Certificate that form a chain.
For more information on PKCS12 "Personal Information
Exchange Syntax Standard", see <a
- href="ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf">ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf</a>.
+ href="ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf">ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1.pdf</a>.
\ingroup UserAPI
*/
class QCA_EXPORT KeyBundle
{
public:
- /**
- Create an empty KeyBundle
- */
- KeyBundle();
-
- /**
- Create a KeyBundle from a PKCS12 (.p12) encoded
- file
-
- This constructor requires appropriate plugin (provider)
- support. You must check for the "pkcs12" feature
- before using this constructor.
-
- \param fileName the name of the file to read from
- \param passphrase the passphrase that is applicable to the file
-
- \sa fromFile for a more flexible version of the
- same capability.
-
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- explicit KeyBundle(const QString &fileName, const SecureArray &passphrase = SecureArray());
-
- /**
- Standard copy constructor
-
- \param from the KeyBundle to use as source
- */
- KeyBundle(const KeyBundle &from);
-
- ~KeyBundle();
-
- /**
- Standard assignment operator
+ /**
+ Create an empty KeyBundle
+ */
+ KeyBundle();
- \param from the KeyBundle to use as source
- */
- KeyBundle & operator=(const KeyBundle &from);
+ /**
+ Create a KeyBundle from a PKCS12 (.p12) encoded
+ file
- /**
- Test if this key is empty (null)
- */
- bool isNull() const;
-
- /**
- The name associated with this key.
-
- This is also known as the "friendly name", and if
- present, is typically suitable to be displayed to
- the user.
-
- \sa setName
- */
- QString name() const;
-
- /**
- The public certificate part of this bundle
-
- \sa setCertificateChainAndKey
- */
- CertificateChain certificateChain() const;
-
- /**
- The private key part of this bundle
-
- \sa setCertificateChainAndKey
- */
- PrivateKey privateKey() const;
-
- /**
- Specify the name of this bundle
-
- \param s the name to use
- */
- void setName(const QString &s);
-
- /**
- Set the public certificate and private key
-
- \param c the CertificateChain containing the public part of the
- Bundle
- \param key the private key part of the Bundle
-
- \sa privateKey, certificateChain for getters
- */
- void setCertificateChainAndKey(const CertificateChain &c, const PrivateKey &key);
-
- /**
- Export the key bundle to an array in PKCS12 format.
-
- This method requires appropriate plugin (provider)
- support - you must check for the "pkcs12" feature,
- as shown below.
-
- \code
-if( QCA::isSupported("pkcs12") )
-{
- // can use I/O
- byteArray = bundle.toArray( "pass phrase" );
-}
-else
-{
- // not possible to use I/O
-}
- \endcode
-
- \param passphrase the passphrase to use to protect the bundle
- \param provider the provider to use, if a specific provider is
- required
- */
- QByteArray toArray(const SecureArray &passphrase, const QString &provider = QString()) const;
-
- /**
- Export the key bundle to a file in PKCS12 (.p12) format
-
- This method requires appropriate plugin (provider)
- support - you must check for the "pkcs12" feature,
- as shown below.
-
- \code
-if( QCA::isSupported("pkcs12") )
-{
- // can use I/O
- bool result = bundle.toFile( filename, "pass phrase" );
-}
-else
-{
- // not possible to use I/O
-}
- \endcode
-
- \param fileName the name of the file to save to
- \param passphrase the passphrase to use to protect the bundle
- \param provider the provider to use, if a specific provider is
- required
- */
- bool toFile(const QString &fileName, const SecureArray &passphrase, const QString &provider = QString()) const;
-
- /**
- Import the key bundle from an array in PKCS12 format
-
- This method requires appropriate plugin (provider)
- support - you must check for the "pkcs12" feature,
- as shown below.
-
- \code
-if( QCA::isSupported("pkcs12") )
-{
- // can use I/O
- bundle = QCA::KeyBundle::fromArray( array, "pass phrase" );
-}
-else
-{
- // not possible to use I/O
-}
- \endcode
-
- \param a the array to import from
- \param passphrase the passphrase for the encoded bundle
- \param result pointer to the result of the import process
- \param provider the provider to use, if a specific provider is
- required
-
- \sa QCA::KeyLoader for an asynchronous loader approach.
-
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- static KeyBundle fromArray(const QByteArray &a, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Import the key bundle from a file in PKCS12 (.p12) format
-
- This method requires appropriate plugin (provider)
- support - you must check for the "pkcs12" feature,
- as shown below.
-
- \code
-if( QCA::isSupported("pkcs12") )
-{
- // can use I/O
- bundle = QCA::KeyBundle::fromFile( filename, "pass phrase" );
-}
-else
-{
- // not possible to use I/O
-}
- \endcode
+ This constructor requires appropriate plugin (provider)
+ support. You must check for the "pkcs12" feature
+ before using this constructor.
- \param fileName the name of the file to read from
- \param passphrase the passphrase for the encoded bundle
- \param result pointer to the result of the import process
- \param provider the provider to use, if a specific provider is
- required
+ \param fileName the name of the file to read from
+ \param passphrase the passphrase that is applicable to the file
- \sa QCA::KeyLoader for an asynchronous loader approach.
+ \sa fromFile for a more flexible version of the
+ same capability.
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- static KeyBundle fromFile(const QString &fileName, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ explicit KeyBundle(const QString &fileName, const SecureArray &passphrase = SecureArray());
+
+ /**
+ Standard copy constructor
+
+ \param from the KeyBundle to use as source
+ */
+ KeyBundle(const KeyBundle &from);
+
+ ~KeyBundle();
+
+ /**
+ Standard assignment operator
+
+ \param from the KeyBundle to use as source
+ */
+ KeyBundle &operator=(const KeyBundle &from);
+
+ /**
+ Test if this key is empty (null)
+ */
+ bool isNull() const;
+
+ /**
+ The name associated with this key.
+
+ This is also known as the "friendly name", and if
+ present, is typically suitable to be displayed to
+ the user.
+
+ \sa setName
+ */
+ QString name() const;
+
+ /**
+ The public certificate part of this bundle
+
+ \sa setCertificateChainAndKey
+ */
+ CertificateChain certificateChain() const;
+
+ /**
+ The private key part of this bundle
+
+ \sa setCertificateChainAndKey
+ */
+ PrivateKey privateKey() const;
+
+ /**
+ Specify the name of this bundle
+
+ \param s the name to use
+ */
+ void setName(const QString &s);
+
+ /**
+ Set the public certificate and private key
+
+ \param c the CertificateChain containing the public part of the
+ Bundle
+ \param key the private key part of the Bundle
+
+ \sa privateKey, certificateChain for getters
+ */
+ void setCertificateChainAndKey(const CertificateChain &c, const PrivateKey &key);
+
+ /**
+ Export the key bundle to an array in PKCS12 format.
+
+ This method requires appropriate plugin (provider)
+ support - you must check for the "pkcs12" feature,
+ as shown below.
+
+ \code
+ if( QCA::isSupported("pkcs12") )
+ {
+ // can use I/O
+ byteArray = bundle.toArray( "pass phrase" );
+ }
+ else
+ {
+ // not possible to use I/O
+ }
+ \endcode
+
+ \param passphrase the passphrase to use to protect the bundle
+ \param provider the provider to use, if a specific provider is
+ required
+ */
+ QByteArray toArray(const SecureArray &passphrase, const QString &provider = QString()) const;
+
+ /**
+ Export the key bundle to a file in PKCS12 (.p12) format
+
+ This method requires appropriate plugin (provider)
+ support - you must check for the "pkcs12" feature,
+ as shown below.
+
+ \code
+ if( QCA::isSupported("pkcs12") )
+ {
+ // can use I/O
+ bool result = bundle.toFile( filename, "pass phrase" );
+ }
+ else
+ {
+ // not possible to use I/O
+ }
+ \endcode
+
+ \param fileName the name of the file to save to
+ \param passphrase the passphrase to use to protect the bundle
+ \param provider the provider to use, if a specific provider is
+ required
+ */
+ bool toFile(const QString &fileName, const SecureArray &passphrase, const QString &provider = QString()) const;
+
+ /**
+ Import the key bundle from an array in PKCS12 format
+
+ This method requires appropriate plugin (provider)
+ support - you must check for the "pkcs12" feature,
+ as shown below.
+
+ \code
+ if( QCA::isSupported("pkcs12") )
+ {
+ // can use I/O
+ bundle = QCA::KeyBundle::fromArray( array, "pass phrase" );
+ }
+ else
+ {
+ // not possible to use I/O
+ }
+ \endcode
+
+ \param a the array to import from
+ \param passphrase the passphrase for the encoded bundle
+ \param result pointer to the result of the import process
+ \param provider the provider to use, if a specific provider is
+ required
+
+ \sa QCA::KeyLoader for an asynchronous loader approach.
+
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ static KeyBundle fromArray(const QByteArray &a, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Import the key bundle from a file in PKCS12 (.p12) format
+
+ This method requires appropriate plugin (provider)
+ support - you must check for the "pkcs12" feature,
+ as shown below.
+
+ \code
+ if( QCA::isSupported("pkcs12") )
+ {
+ // can use I/O
+ bundle = QCA::KeyBundle::fromFile( filename, "pass phrase" );
+ }
+ else
+ {
+ // not possible to use I/O
+ }
+ \endcode
+
+ \param fileName the name of the file to read from
+ \param passphrase the passphrase for the encoded bundle
+ \param result pointer to the result of the import process
+ \param provider the provider to use, if a specific provider is
+ required
+
+ \sa QCA::KeyLoader for an asynchronous loader approach.
+
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ static KeyBundle fromFile(const QString &fileName, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class PGPKey qca_cert.h QtCrypto
- Pretty Good Privacy key
+ Pretty Good Privacy key
This holds either a reference to an item in a real PGP keyring,
or a standalone item created using the from*() functions.
Note that with the latter method, the key is of no use besides
being informational. The key must be in a keyring
(that is, inKeyring() == true) to actually do crypto with it.
\ingroup UserAPI
*/
class QCA_EXPORT PGPKey : public Algorithm
{
public:
- /**
- Create an empty PGP key
- */
- PGPKey();
+ /**
+ Create an empty PGP key
+ */
+ PGPKey();
- /**
- Create a PGP key from an encoded file
+ /**
+ Create a PGP key from an encoded file
- \param fileName the name (and path, if required) of the file
- that the PGP key is to be loaded from.
+ \param fileName the name (and path, if required) of the file
+ that the PGP key is to be loaded from.
- \sa fromFile for a version that allows better error checking / validation
- \sa toFile for a method to write out the key.
- */
- PGPKey(const QString &fileName);
+ \sa fromFile for a version that allows better error checking / validation
+ \sa toFile for a method to write out the key.
+ */
+ PGPKey(const QString &fileName);
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the PGPKey to use as the source
- */
- PGPKey(const PGPKey &from);
+ \param from the PGPKey to use as the source
+ */
+ PGPKey(const PGPKey &from);
- ~PGPKey();
+ ~PGPKey();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the PGPKey to use as the source
- */
- PGPKey & operator=(const PGPKey &from);
+ \param from the PGPKey to use as the source
+ */
+ PGPKey &operator=(const PGPKey &from);
- /**
- Test if the PGP key is empty (null)
+ /**
+ Test if the PGP key is empty (null)
- \return true if the PGP key is null
- */
- bool isNull() const;
+ \return true if the PGP key is null
+ */
+ bool isNull() const;
- /**
- The Key identification for the PGP key
- */
- QString keyId() const;
+ /**
+ The Key identification for the PGP key
+ */
+ QString keyId() const;
- /**
- The primary user identification for the key
- */
- QString primaryUserId() const;
+ /**
+ The primary user identification for the key
+ */
+ QString primaryUserId() const;
- /**
- The list of all user identifications associated with the key
- */
- QStringList userIds() const;
+ /**
+ The list of all user identifications associated with the key
+ */
+ QStringList userIds() const;
- /**
- Test if the PGP key is the secret key
-
- \return true if the PGP key is the secret key
- */
- bool isSecret() const;
+ /**
+ Test if the PGP key is the secret key
+
+ \return true if the PGP key is the secret key
+ */
+ bool isSecret() const;
- /**
- The creation date for the key
- */
- QDateTime creationDate() const;
+ /**
+ The creation date for the key
+ */
+ QDateTime creationDate() const;
- /**
- The expiration date for the key
- */
- QDateTime expirationDate() const;
+ /**
+ The expiration date for the key
+ */
+ QDateTime expirationDate() const;
- /**
- The key fingerpint
+ /**
+ The key fingerpint
- This will return the PGP fingerprint as a string. It comprises 40
- hex digits, without spaces.
- */
- QString fingerprint() const;
+ This will return the PGP fingerprint as a string. It comprises 40
+ hex digits, without spaces.
+ */
+ QString fingerprint() const;
- /**
- Test if this key is in a keyring
+ /**
+ Test if this key is in a keyring
- \return true if the key is in a keyring
+ \return true if the key is in a keyring
- \note keys that are not in a keyring cannot be used for encryption,
- decryption, signing or verification
- */
- bool inKeyring() const;
+ \note keys that are not in a keyring cannot be used for encryption,
+ decryption, signing or verification
+ */
+ bool inKeyring() const;
- /**
- Test if the key is trusted
+ /**
+ Test if the key is trusted
- \return true if the key is trusted
- */
- bool isTrusted() const;
+ \return true if the key is trusted
+ */
+ bool isTrusted() const;
- /**
- Export the key to an array.
+ /**
+ Export the key to an array.
- This will export the key in a binary format (that is, not in an
- "ascii armoured" form).
+ This will export the key in a binary format (that is, not in an
+ "ascii armoured" form).
- \sa fromArray for a static import method.
- \sa toString for an "ascii armoured" export method.
- */
- QByteArray toArray() const;
+ \sa fromArray for a static import method.
+ \sa toString for an "ascii armoured" export method.
+ */
+ QByteArray toArray() const;
- /**
- Export the key to a string
+ /**
+ Export the key to a string
- This will export the key in an "ascii armoured" form.
+ This will export the key in an "ascii armoured" form.
- \sa fromString for a static import method.
- \sa toArray for a binary format export method.
- */
- QString toString() const;
+ \sa fromString for a static import method.
+ \sa toArray for a binary format export method.
+ */
+ QString toString() const;
- /**
- Export the key to a file
+ /**
+ Export the key to a file
- \param fileName the name of the file to save the key to
- */
- bool toFile(const QString &fileName) const;
+ \param fileName the name of the file to save the key to
+ */
+ bool toFile(const QString &fileName) const;
- /**
- Import the key from an array
-
- \param a the array to import from
- \param result if not null, this will be set to the result of the
- import process
- \param provider the provider to use, if a particular provider is
- required
- */
- static PGPKey fromArray(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Import the key from a string
-
- \param s the string to import from
- \param result if not null, this will be set to the result of the
- import process
- \param provider the provider to use, if a particular provider is
- required
- */
- static PGPKey fromString(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Import the key from a file
+ /**
+ Import the key from an array
+
+ \param a the array to import from
+ \param result if not null, this will be set to the result of the
+ import process
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ static PGPKey fromArray(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Import the key from a string
+
+ \param s the string to import from
+ \param result if not null, this will be set to the result of the
+ import process
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ static PGPKey fromString(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Import the key from a file
- \param fileName string containing the name of the file to import
- from
- \param result if not null, this will be set to the result of the
- import process
- \param provider the provider to use, if a particular provider is
- required
- */
- static PGPKey fromFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
+ \param fileName string containing the name of the file to import
+ from
+ \param result if not null, this will be set to the result of the
+ import process
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ static PGPKey fromFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class KeyLoader qca_cert.h QtCrypto
Asynchronous private key loader
GUI applications generally must use KeyLoader to load private keys. This
is because the synchronous private key loading functions, for example
QCA::PrivateKey::fromPEMFile(), cannot be used within the same thread as an
EventHandler, and most GUI applications will use EventHandler from the main
thread. KeyLoader does not have this problem. It can be used from any
thread, including the same thread as EventHandler.
The KeyLoader class allows you to asynchronously load stand-alone private
keys (QCA::PrivateKey) or private keys with a certificate (QCA::KeyBundle)
with a signal that advises of completion.
To use this class to load a PrivateKey, you create a KeyLoader object then
use one of the loadPrivateKeyFrom...() functions, depending on the format
for your key. These functions return immediately. When you get the
finished() signal, you can check that the loading operation succeeded
(using convertResult()) and then obtain the PrivateKey using the
privateKey() function.
The same process applies for loading a KeyBundle, except that you use
either loadKeyBundleFromFile() or loadKeyBundleFromArray() instead of the
loadPrivateKeyFrom...() function, and use keyBundle() instead of
privateKey().
The loader may need a passphrase to complete the loading of the key or key
bundle. You should use the QCA::EventHandler class to ensure that you deal
with this correctly.
\note %QCA also provides synchronous private key loading using
QCA::PrivateKey::fromPEMFile(), QCA::PrivateKey::fromPEM() and
QCA::PrivateKey::fromDER(). %QCA provides synchronous key bundle loading
using QCA::KeyBundle::fromArray() and QCA::KeyBundle::fromFile().
\ingroup UserAPI
*/
class QCA_EXPORT KeyLoader : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Create a KeyLoader object.
+ /**
+ Create a KeyLoader object.
- \param parent the parent object for this object
- */
- KeyLoader(QObject *parent = 0);
- ~KeyLoader();
+ \param parent the parent object for this object
+ */
+ KeyLoader(QObject *parent = 0);
+ ~KeyLoader();
- /**
- Initiate an asynchronous loading of a PrivateKey from a PEM format
- file.
+ /**
+ Initiate an asynchronous loading of a PrivateKey from a PEM format
+ file.
- This function will return immediately.
+ This function will return immediately.
- \param fileName the name of the file (and path, if necessary) to
- load the key from
- */
- void loadPrivateKeyFromPEMFile(const QString &fileName);
+ \param fileName the name of the file (and path, if necessary) to
+ load the key from
+ */
+ void loadPrivateKeyFromPEMFile(const QString &fileName);
- /**
- Initiate an asynchronous loading of a PrivateKey from a PEM format
- string.
+ /**
+ Initiate an asynchronous loading of a PrivateKey from a PEM format
+ string.
- This function will return immediately.
+ This function will return immediately.
- \param s the string containing the PEM formatted key
- */
- void loadPrivateKeyFromPEM(const QString &s);
+ \param s the string containing the PEM formatted key
+ */
+ void loadPrivateKeyFromPEM(const QString &s);
- /**
- Initiate an asynchronous loading of a PrivateKey from a DER format
- array.
+ /**
+ Initiate an asynchronous loading of a PrivateKey from a DER format
+ array.
- This function will return immediately.
+ This function will return immediately.
- \param a the array containing the DER formatted key
- */
- void loadPrivateKeyFromDER(const SecureArray &a);
+ \param a the array containing the DER formatted key
+ */
+ void loadPrivateKeyFromDER(const SecureArray &a);
- /**
- Initiate an asynchronous loading of a KeyBundle from a file
+ /**
+ Initiate an asynchronous loading of a KeyBundle from a file
- This function will return immediately.
+ This function will return immediately.
- \param fileName the name of the file (and path, if necessary) to
- load the key bundle from
- */
- void loadKeyBundleFromFile(const QString &fileName);
+ \param fileName the name of the file (and path, if necessary) to
+ load the key bundle from
+ */
+ void loadKeyBundleFromFile(const QString &fileName);
- /**
- Initiate an asynchronous loading of a KeyBundle from an array
+ /**
+ Initiate an asynchronous loading of a KeyBundle from an array
- This function will return immediately.
+ This function will return immediately.
- \param a the array containing the key bundle
- */
- void loadKeyBundleFromArray(const QByteArray &a);
+ \param a the array containing the key bundle
+ */
+ void loadKeyBundleFromArray(const QByteArray &a);
- /**
- The result of the loading process.
+ /**
+ The result of the loading process.
- This is not valid until the finished() signal has been emitted.
- */
- ConvertResult convertResult() const;
+ This is not valid until the finished() signal has been emitted.
+ */
+ ConvertResult convertResult() const;
- /**
- The private key that has been loaded.
+ /**
+ The private key that has been loaded.
- This is only valid if loadPrivateKeyFromPEMFile(),
- loadPrivateKeyFromPEM() or loadPrivateKeyFromDER() has been used,
- the load has completed (that is, finished() has been emitted), and
- the conversion succeeded (that is, convertResult() returned
- ConvertGood).
- */
- PrivateKey privateKey() const;
+ This is only valid if loadPrivateKeyFromPEMFile(),
+ loadPrivateKeyFromPEM() or loadPrivateKeyFromDER() has been used,
+ the load has completed (that is, finished() has been emitted), and
+ the conversion succeeded (that is, convertResult() returned
+ ConvertGood).
+ */
+ PrivateKey privateKey() const;
- /**
- The key bundle that has been loaded.
+ /**
+ The key bundle that has been loaded.
- This is only valid if loadKeyBundleFromFile() or
- loadKeyBundleFromArray() has been used, the load has completed
- (that is, finished() has been emitted), and the conversion
- succeeded (that is, convertResult() returned ConvertGood).
- */
- KeyBundle keyBundle() const;
+ This is only valid if loadKeyBundleFromFile() or
+ loadKeyBundleFromArray() has been used, the load has completed
+ (that is, finished() has been emitted), and the conversion
+ succeeded (that is, convertResult() returned ConvertGood).
+ */
+ KeyBundle keyBundle() const;
Q_SIGNALS:
- /**
- Signal that is emitted when the load process has completed.
+ /**
+ Signal that is emitted when the load process has completed.
- \note The load process may not have completed successfully - check
- the result of convertResult() to confirm this before using the
- privateKey() or keyBundle() results.
- */
- void finished();
+ \note The load process may not have completed successfully - check
+ the result of convertResult() to confirm this before using the
+ privateKey() or keyBundle() results.
+ */
+ void finished();
private:
- Q_DISABLE_COPY(KeyLoader)
+ Q_DISABLE_COPY(KeyLoader)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
}
#endif
diff --git a/include/QtCrypto/qca_core.h b/include/QtCrypto/qca_core.h
index 8c25a701..07bf1f10 100644
--- a/include/QtCrypto/qca_core.h
+++ b/include/QtCrypto/qca_core.h
@@ -1,1796 +1,1801 @@
/*
* qca_core.h - Qt Cryptographic Architecture
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004,2005 Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2014-2016 Ivan Romanov <drizt@land.ru>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_core.h
Header file for core %QCA infrastructure
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_CORE_H
#define QCA_CORE_H
#include <QString>
#include <QStringList>
#include <QList>
#include <QSharedData>
#include <QSharedDataPointer>
#include "qca_export.h"
#include "qca_support.h"
#include "qca_tools.h"
#include "qca_version.h"
/**
The current version of %QCA.
This is equivalent to ::QCA_VERSION, except it provides
a runtime check of the version of %QCA that is being used.
*/
QCA_EXPORT int qcaVersion();
/**
The current version of %QCA.
This is equivalent to ::QCA_VERSION_STR, except it provides
a runtime check of the version of %QCA that is being used.
*/
QCA_EXPORT const char *qcaVersionStr();
/**
The current version of %QCA.
This is equivalent to ::QCA_MAJOR_VERSION, except it provides
a runtime check of the version of %QCA that is being used.
*/
QCA_EXPORT int qcaMajorVersion();
/**
The current version of %QCA.
This is equivalent to ::QCA_MINOR_VERSION, except it provides
a runtime check of the version of %QCA that is being used.
*/
QCA_EXPORT int qcaMinorVersion();
/**
The current version of %QCA.
This is equivalent to ::QCA_PATCH_VERSION, except it provides
a runtime check of the version of %QCA that is being used.
*/
QCA_EXPORT int qcaPatchVersion();
/**
QCA - the Qt Cryptographic Architecture
*/
-namespace QCA {
+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;
+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.
+ 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
+enum MemoryMode {
+ Practical, ///< mlock and drop root if available, else mmap
+ Locking, ///< mlock and drop root
+ LockingKeepPrivileges ///< mlock, retaining root privileges
};
/**
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
+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();
/**
\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);
/**
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();
/**
Test if secure storage memory is available
\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");
+ printf("SHA1 not supported!\n");
else
{
- QString result = QCA::SHA1::hashToString(myString);
- printf("sha1(\"%s\") = [%s]\n", myString.data(), qPrintable(result));
+ 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
+ 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.
QCA takes ownership of the provider.
\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 unloadProvider for unloading specified providers
\sa setProviderPriority for a description of the provider priority system
*/
QCA_EXPORT bool insertProvider(Provider *p, int priority = 0);
/**
Unload specified provider
The specified provider is removed from the list of providers
and deleted. If no provider with the name is found, this call fails.
\param name the name of the provider
\return true if the provider is unloaded, and false if the provider
cannot be found
\sa insertProvider for adding providers
*/
QCA_EXPORT bool unloadProvider(const QString &name);
/**
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
+ - 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-ossl") is used to look up the
+ The name of the provider (eg "qca-ossl") 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
\param name the name of the provider to search for.
*/
QCA_EXPORT Provider *findProvider(const QString &name);
/**
Return the default provider
*/
QCA_EXPORT Provider *defaultProvider();
/**
Retrieve plugin paths. It consists of:
1. QCA_PLUGIN_PATH environment if set.
2. \c %QCoreApplication::libraryPaths() .
3. Directory where plugins were installed.
QCA_PLUGIN_PATH is paths list like PATH or QT_PLUGIN_PATH.
It uses system path separator. \";\" on Windows and \":\" on Unix.
This function was introduced in %QCA 2.1.
*/
QCA_EXPORT QStringList pluginPaths();
/**
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.
\param text the diagnostic message to append
*/
QCA_EXPORT void appendPluginDiagnosticText(const QString &text);
/**
Set a global property
\param name the name of the property
\param value the value to set the property to
\sa getProperty
*/
QCA_EXPORT void setProperty(const QString &name, const QVariant &value);
/**
Retrieve a global property
\param name the name of the property to look up
\sa setProperty
*/
QCA_EXPORT QVariant getProperty(const QString &name);
/**
Set provider configuration
Allowed value types: QString, int, bool
\param name the name of the provider to set the configuration to
\param config the configuration
*/
QCA_EXPORT void setProviderConfig(const QString &name, const QVariantMap &config);
/**
Retrieve provider configuration
\param name the name of the provider to retrieve the configuration of
*/
QCA_EXPORT QVariantMap getProviderConfig(const QString &name);
/**
Save provider configuration to persistent storage
\param name the name of the provider to have its configuration saved
*/
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.
\param provider the name of the provider to use as the global random
provider.
*/
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.
+ 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 { \
- QCA::Logger::Severity s = severity; \
- QCA::Logger *l = QCA::logger (); \
- if (s <= l->level ()) { \
- l->logTextMessage (message, s); \
- } \
- } while (false)
+ do { \
+ QCA::Logger::Severity s = severity; \
+ 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 { \
- QCA::Logger::Severity s = severity; \
- QCA::Logger *l = QCA::logger (); \
- if (s <= l->level ()) { \
- l->logBinaryMessage (blob, s); \
- } \
- } while (false)
+ do { \
+ QCA::Logger::Severity s = severity; \
+ 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 Certificate Authority (CA) certificates
Many operating systems (or distributions, on Linux-type systems)
come with some trusted certificates. Typically, these include
the root certificates for major Certificate Authorities (for
example, Verisign, Comodo) and some additional certificates that
are used for system updates. They are provided in different ways
for different systems.
- This function provides an common way to access the system
+ This function provides an common way to access the system
certificates. There are other ways to access certificates - see
- the various I/O methods (such as fromDER() and fromPEM())
+ the various I/O methods (such as fromDER() and fromPEM())
in the Certificate and CertificateCollection classes.
\note Availability of the system certificates depends on how
%QCA was built. You can test whether the system certificates
are available using the haveSystemStore() function.
*/
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
+ 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
QByteArray to a printable representation.
\code
QByteArray test(10);
test.fill('a');
// 0x61 is 'a' in ASCII
if (QString("61616161616161616161") == QCA::arrayToHex(test) )
{
- printf ("arrayToHex passed\n");
+ printf ("arrayToHex passed\n");
}
\endcode
\param array the array to be converted
\return a printable representation
*/
QCA_EXPORT QString arrayToHex(const QByteArray &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");
+ 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);
/**
Convert a byte array to printable base64
representation.
This is a convenience function to convert an arbitrary
QByteArray to a printable representation.
\param array the array to be converted
\return a printable representation
*/
QCA_EXPORT QString arrayToBase64(const QByteArray &array);
/**
Convert a QString containing a base64 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::arrayToBase64.
\param base64String the string containing a printable
representation to be converted
\return the equivalent QByteArray
*/
QCA_EXPORT QByteArray base64ToArray(const QString &base64String);
/**
\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.
\ingroup UserAPI
*/
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();
+ /**
+ 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 );
\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
\ingroup UserAPI
*/
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; }
+ /**
+ 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;
+ 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
+ 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.
\ingroup ProviderAPI
*/
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();
-
- /**
- Deinitialisation routine
-
- This routine will be called just before provider destruction.
- Notably, during QCA shutdown, deinit() will be called on all
- providers before any of the providers are destructed. Use this
- opportunity to free any resources that may be used by other
- providers.
- */
- virtual void deinit();
-
- /**
- Version number of the plugin
-
- The format is the same as QCA itself. Version 1.2.3 would be
- represented as 0x010203.
-
- The default returns 0 (version 0.0.0).
- */
- virtual int version() const;
-
- /**
- 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 supply major and minor version numbers here that are
- less-than or equal to the actual 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 qcaVersion() 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(sha1)";
- 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. Only report credit text
- when absolutely required (for example, an "advertisement
- clause" related to licensing). Do not use it for
- reporting general author information.
- */
- 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;
-
- /**
- Method to set up the default configuration options.
-
- If your provider needs some configuration options,
- this method allows you to establish default options.
- The user can then change the configuration options
- as required, and set them using configChanged().
-
- You need to return a QVariantMap that has configuration
- options as the keys, and the default configuration
- as the values, as shown below:
- \code
-QVariantMap defaultConfig() const
-{
- QVariantMap myConfig;
- myConfig[ "firstOption" ] = QString("firstOptionValue");
- myConfig[ "secondOption" ] = true;
- myConfig[ "thirdOpt" ] = 1243;
- return myConfig;
-}
- \endcode
-
- \sa configChanged for how to set the configuration;
- */
- virtual QVariantMap defaultConfig() const;
-
- /**
- Method to set the configuration options.
-
- If your provider supports configuration options, you
- will be advised of user changes to the configuration
- when this method is called.
-
- \param config the new configuration to be used by the provider
- */
- virtual void configChanged(const QVariantMap &config);
+ 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();
+
+ /**
+ Deinitialisation routine
+
+ This routine will be called just before provider destruction.
+ Notably, during QCA shutdown, deinit() will be called on all
+ providers before any of the providers are destructed. Use this
+ opportunity to free any resources that may be used by other
+ providers.
+ */
+ virtual void deinit();
+
+ /**
+ Version number of the plugin
+
+ The format is the same as QCA itself. Version 1.2.3 would be
+ represented as 0x010203.
+
+ The default returns 0 (version 0.0.0).
+ */
+ virtual int version() const;
+
+ /**
+ 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 supply major and minor version numbers here that are
+ less-than or equal to the actual 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 qcaVersion() 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(sha1)";
+ 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. Only report credit text
+ when absolutely required (for example, an "advertisement
+ clause" related to licensing). Do not use it for
+ reporting general author information.
+ */
+ 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;
+
+ /**
+ Method to set up the default configuration options.
+
+ If your provider needs some configuration options,
+ this method allows you to establish default options.
+ The user can then change the configuration options
+ as required, and set them using configChanged().
+
+ You need to return a QVariantMap that has configuration
+ options as the keys, and the default configuration
+ as the values, as shown below:
+ \code
+ QVariantMap defaultConfig() const
+ {
+ QVariantMap myConfig;
+ myConfig[ "firstOption" ] = QString("firstOptionValue");
+ myConfig[ "secondOption" ] = true;
+ myConfig[ "thirdOpt" ] = 1243;
+ return myConfig;
+ }
+ \endcode
+
+ \sa configChanged for how to set the configuration;
+ */
+ virtual QVariantMap defaultConfig() const;
+
+ /**
+ Method to set the configuration options.
+
+ If your provider supports configuration options, you
+ will be advised of user changes to the configuration
+ when this method is called.
+
+ \param config the new configuration to be used by the provider
+ */
+ virtual void configChanged(const QVariantMap &config);
};
/**
\class QCA::Provider::Context qca_core.h QtCrypto
Internal context class used for the plugin
\internal
\ingroup ProviderAPI
*/
class QCA_EXPORT Provider::Context : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- virtual ~Context();
+ virtual ~Context();
- /**
- The Provider associated with this Context
- */
- Provider *provider() const;
+ /**
+ The Provider associated with this Context
+ */
+ Provider *provider() const;
- /**
- The type of context, as passed to the constructor
- */
- QString type() const;
+ /**
+ The type of context, as passed to the constructor
+ */
+ QString type() const;
- /**
- Create a duplicate of this Context
- */
- virtual Context *clone() const = 0;
+ /**
+ Create a duplicate of this Context
+ */
+ virtual Context *clone() const = 0;
- /**
- Test if two Contexts have the same Provider
+ /**
+ Test if two Contexts have the same Provider
- \param c pointer to the Context to compare to
+ \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;
+ \return true if the argument and this Context
+ have the same provider.
+ */
+ bool sameProvider(const Context *c) const;
protected:
- /**
- Standard constructor
+ /**
+ 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);
+ \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
+ /**
+ Copy constructor
- \param from the Context to copy from
- */
- Context(const Context &from);
+ \param from the Context to copy from
+ */
+ Context(const Context &from);
private:
- // disable assignment
- Context & operator=(const Context &from);
+ // disable assignment
+ Context &operator=(const Context &from);
- Provider *_provider;
- QString _type;
+ Provider *_provider;
+ QString _type;
};
/**
\class BasicContext qca_core.h QtCrypto
Base class to use for primitive provider contexts
\internal
This class inherits Provider::Context and calls moveToThread(0) on
itself, thereby disabling the event properties of the underlying
QObject. Context types that need to be a QObject should inherit from
Provider::Context, those that don't should inherit from BasicContext.
\ingroup ProviderAPI
*/
class QCA_EXPORT BasicContext : public Provider::Context
{
- Q_OBJECT
+ Q_OBJECT
public:
- ~BasicContext();
+ ~BasicContext();
protected:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param parent the parent provider for this
- context
- \param type the name of the provider context type
- */
- BasicContext(Provider *parent, const QString &type);
+ \param parent the parent provider for this
+ context
+ \param type the name of the provider context type
+ */
+ BasicContext(Provider *parent, const QString &type);
- /**
- Copy constructor
+ /**
+ Copy constructor
- \param from the Context to copy from
- */
- BasicContext(const BasicContext &from);
+ \param from the Context to copy from
+ */
+ BasicContext(const BasicContext &from);
private:
- // disable assignment
- BasicContext & operator=(const BasicContext &from);
+ // 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().
\ingroup UserAPI
*/
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 MemoryRegion &a) = 0;
-
- /**
- Complete the algorithm and return the internal state
- */
- virtual MemoryRegion 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.
-
- \param a the data to process.
- */
- MemoryRegion process(const MemoryRegion &a);
+ 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 MemoryRegion &a) = 0;
+
+ /**
+ Complete the algorithm and return the internal state
+ */
+ virtual MemoryRegion 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.
+
+ \param a the data to process.
+ */
+ MemoryRegion process(const MemoryRegion &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.
\ingroup UserAPI
*/
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 MemoryRegion update(const MemoryRegion &a) = 0;
-
- /**
- Complete the algorithm, returning any
- additional results.
- */
- virtual MemoryRegion 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.
-
- \param a the data to process in this step
- */
- MemoryRegion process(const MemoryRegion &a);
+ 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 MemoryRegion update(const MemoryRegion &a) = 0;
+
+ /**
+ Complete the algorithm, returning any
+ additional results.
+ */
+ virtual MemoryRegion 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.
+
+ \param a the data to process in this step
+ */
+ MemoryRegion process(const MemoryRegion &a);
};
/**
\class Algorithm qca_core.h QtCrypto
- General superclass for an algorithm.
+ General superclass for an algorithm.
This is a fairly abstract class, mainly used for
implementing the backend "provider" interface.
\ingroup UserAPI
*/
class QCA_EXPORT Algorithm
{
public:
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the Algorithm to copy from
- */
- Algorithm(const Algorithm &from);
+ \param from the Algorithm to copy from
+ */
+ Algorithm(const Algorithm &from);
- virtual ~Algorithm();
+ virtual ~Algorithm();
- /**
- Assignment operator
+ /**
+ Assignment operator
- \param from the Algorithm to copy state from
- */
- Algorithm & operator=(const Algorithm &from);
+ \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 algorithm type.
+ */
+ QString type() const;
- /**
- The name of the provider
+ /**
+ 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;
+ 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!
+ // Note: The next five functions are not public!
- /**
- \internal
+ /**
+ \internal
- The context associated with this algorithm
- */
- Provider::Context *context();
+ The context associated with this algorithm
+ */
+ Provider::Context *context();
- /**
- \internal
+ /**
+ \internal
- The context associated with this algorithm
- */
- const Provider::Context *context() const;
+ The context associated with this algorithm
+ */
+ const Provider::Context *context() const;
- /**
- \internal
+ /**
+ \internal
- Set the Provider for this algorithm
+ Set the Provider for this algorithm
- \param c the context for the Provider to use
- */
- void change(Provider::Context *c);
+ \param c the context for the Provider to use
+ */
+ void change(Provider::Context *c);
- /**
- \internal
+ /**
+ \internal
- \overload
+ \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);
+ \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
+ /**
+ \internal
- Take the Provider from this algorithm
- */
- Provider::Context *takeContext();
+ Take the Provider from this algorithm
+ */
+ Provider::Context *takeContext();
protected:
- /**
- Constructor for empty algorithm
- */
- Algorithm();
+ /**
+ Constructor for empty algorithm
+ */
+ Algorithm();
- /**
- Constructor of a particular 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);
+ \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 Private;
+ QSharedDataPointer<Private> d;
};
/**
\class SymmetricKey qca_core.h QtCrypto
Container for keys for symmetric encryption algorithms.
\ingroup UserAPI
*/
class QCA_EXPORT SymmetricKey : public SecureArray
{
public:
- /**
- Construct an empty (zero length) key
- */
- SymmetricKey();
+ /**
+ Construct an empty (zero length) key
+ */
+ SymmetricKey();
- /**
- Construct an key of specified size, with random contents
+ /**
+ Construct an key of specified size, with random contents
- This is intended to be used as a random session key.
+ This is intended to be used as a random session key.
- \param size the number of bytes for the key
- */
- SymmetricKey(int size);
+ \param size the number of bytes for the key
+ */
+ SymmetricKey(int size);
- /**
- Construct a key from a provided byte array
+ /**
+ Construct a key from a provided byte array
- \param a the byte array to copy
- */
- SymmetricKey(const SecureArray &a);
+ \param a the byte array to copy
+ */
+ SymmetricKey(const SecureArray &a);
- /**
- Construct a key from a provided byte array
+ /**
+ Construct a key from a provided byte array
- \param a the byte array to copy
- */
- SymmetricKey(const QByteArray &a);
+ \param a the byte array to copy
+ */
+ SymmetricKey(const QByteArray &a);
- /**
- Test for weak DES keys
+ /**
+ Test for weak DES keys
- \return true if the key is a weak key for DES
- */
- bool isWeakDESKey();
+ \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
\ingroup UserAPI
*/
class QCA_EXPORT InitializationVector : public SecureArray
{
public:
- /**
- Construct an empty (zero length) initisation vector
- */
- InitializationVector();
+ /**
+ Construct an empty (zero length) initisation vector
+ */
+ InitializationVector();
- /**
- Construct an initialisation vector of the specified size
+ /**
+ Construct an initialisation vector of the specified size
- \param size the length of the initialisation vector, in bytes
- */
- InitializationVector(int size);
+ \param size the length of the initialisation vector, in bytes
+ */
+ InitializationVector(int size);
- /**
- Construct an initialisation vector from a provided byte array
+ /**
+ Construct an initialisation vector from a provided byte array
- \param a the byte array to copy
- */
- InitializationVector(const SecureArray &a);
+ \param a the byte array to copy
+ */
+ InitializationVector(const SecureArray &a);
- /**
- Construct an initialisation vector from a provided byte array
+ /**
+ Construct an initialisation vector from a provided byte array
- \param a the byte array to copy
- */
- InitializationVector(const QByteArray &a);
+ \param a the byte array to copy
+ */
+ InitializationVector(const QByteArray &a);
};
/**
\class AuthTag qca_core.h QtCrypto
Container for authentication tag
\ingroup UserAPI
*/
class QCA_EXPORT AuthTag : public SecureArray
{
public:
- /**
- Construct an empty authentication tag
- */
- AuthTag();
+ /**
+ Construct an empty authentication tag
+ */
+ AuthTag();
- /**
- Construct an empty authentication tag of the specified size
+ /**
+ Construct an empty authentication tag of the specified size
- \param size the length of the authentication tag, in bytes
- */
- AuthTag(int size);
+ \param size the length of the authentication tag, in bytes
+ */
+ AuthTag(int size);
- /**
- Construct an authentication tag from a provided byte array
+ /**
+ Construct an authentication tag from a provided byte array
- \param a the byte array to copy
- */
- AuthTag(const SecureArray &a);
+ \param a the byte array to copy
+ */
+ AuthTag(const SecureArray &a);
- /**
- Construct an authentication tag from a provided byte array
+ /**
+ Construct an authentication tag from a provided byte array
- \param a the byte array to copy
- */
- AuthTag(const QByteArray &a);
+ \param a the byte array to copy
+ */
+ AuthTag(const QByteArray &a);
};
/**
\class Event qca_core.h QtCrypto
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.
\ingroup UserAPI
*/
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);
+ /**
+ %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
+ /**
+ Set the values for this Event
- This creates a Token type 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);
+ \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;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class EventHandler qca_core.h QtCrypto
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.
\ingroup UserAPI
*/
class QCA_EXPORT EventHandler : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Constructor
+ /**
+ Constructor
- \param parent the parent object for this object
- */
- EventHandler(QObject *parent = 0);
- ~EventHandler();
+ \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();
+ /**
+ 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.
+ /**
+ 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.
+ \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);
+ \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.
+ /**
+ function to call to indicate that the token has been inserted
+ by the user.
- \param id the id corresponding to the password request
+ \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);
+ \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.
+ /**
+ 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
+ \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);
+ \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.
+ /**
+ signal emitted when an Event requires attention.
- You typically need to connect this signal to
- a compatible slot in your callback handler
+ You typically need to connect this signal to
+ a compatible slot in your callback handler
- \param id the identification number for the event
- \param context information about the type of response required
- */
- void eventReady(int id, const QCA::Event &context);
+ \param id the identification number for the event
+ \param context information about the type of response required
+ */
+ void eventReady(int id, const QCA::Event &context);
private:
- Q_DISABLE_COPY(EventHandler)
+ Q_DISABLE_COPY(EventHandler)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class PasswordAsker qca_core.h QtCrypto
User password / passphrase / PIN handler
This class is used to obtain a password from a user.
\ingroup UserAPI
*/
class QCA_EXPORT PasswordAsker : public QObject
{
- Q_OBJECT
+ 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;
+ /**
+ 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.
+ /**
+ 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();
+ You should check whether the user accepted() the response
+ prior to relying on the password().
+ */
+ void responseReady();
private:
- Q_DISABLE_COPY(PasswordAsker)
+ Q_DISABLE_COPY(PasswordAsker)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class TokenAsker qca_core.h QtCrypto
User token handler
This class is used to request the user to insert a token.
\ingroup UserAPI
*/
class QCA_EXPORT TokenAsker : public QObject
{
- Q_OBJECT
+ 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;
+ /**
+ 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.
+ /**
+ 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();
+ You should check whether the user accepted() the response
+ prior to relying on token being present.
+ */
+ void responseReady();
private:
- Q_DISABLE_COPY(TokenAsker)
+ 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_export.h b/include/QtCrypto/qca_export.h
index 7c5a846c..4740f102 100644
--- a/include/QtCrypto/qca_export.h
+++ b/include/QtCrypto/qca_export.h
@@ -1,52 +1,52 @@
/*
* qca_export.h - Qt Cryptographic Architecture
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_export.h
- Preprocessor magic to allow export of library symbols.
+ Preprocessor magic to allow export of library symbols.
This is strictly internal.
\note You should not include this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_EXPORT_H
#define QCA_EXPORT_H
#include <QtGlobal>
#ifdef Q_OS_WIN
# ifndef QCA_STATIC
# ifdef QCA_MAKEDLL
# define QCA_EXPORT Q_DECL_EXPORT
# else
# define QCA_EXPORT Q_DECL_IMPORT
# endif
# endif
#endif
#ifndef QCA_EXPORT
# define QCA_EXPORT
#endif
#endif
diff --git a/include/QtCrypto/qca_keystore.h b/include/QtCrypto/qca_keystore.h
index 9fe279d4..b040fa49 100644
--- a/include/QtCrypto/qca_keystore.h
+++ b/include/QtCrypto/qca_keystore.h
@@ -1,798 +1,797 @@
/*
* qca_keystore.h - Qt Cryptographic Architecture
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_keystore.h
Header file for classes that provide and manage keys
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_KEYSTORE_H
#define QCA_KEYSTORE_H
#include "qca_core.h"
#include "qca_cert.h"
-namespace QCA {
+namespace QCA
+{
class KeyStoreTracker;
class KeyStoreManagerPrivate;
class KeyStorePrivate;
/**
\class KeyStoreEntry qca_keystore.h QtCrypto
Single entry in a KeyStore
This is a container for any kind of object in a KeyStore
(such as PGP keys, or X.509 certificates / private keys).
KeyStoreEntry objects are obtained through KeyStore or loaded from a
serialized string format. The latter method requires a KeyStoreEntry
obtained through KeyStore to be serialized for future loading. For
example:
\code
QString str = someKeyStoreEntry.toString();
[ app saves str to disk ]
[ app quits ]
...
[ app launches ]
[ app reads str from disk ]
KeyStoreEntry entry(str);
printf("Entry name: [%s]\n", qPrintable(entry.name()));
\endcode
KeyStoreEntry objects may or may not be available. An entry is
unavailable if it has a private content that is not present. The
private content might exist on external hardware. To determine if an
entry is available, call isAvailable(). To ensure an entry is available
before performing a private key operation, call ensureAvailable. For
example:
\code
if(entry.ensureAvailable())
{
entry.keyBundle().privateKey().signMessage(...);
...
}
\endcode
ensureAvailable() blocks and may cause hardware access, but
if it completes successfully then you may use the entry's private
content. It also means, in the case of a Smart Card token, that
it is probably inserted.
To watch this entry asynchronously, you would do:
\code
KeyStoreEntryWatcher *watcher = new KeyStoreEntryWatcher(entry);
connect(watcher, SIGNAL(available()), SLOT(entry_available()));
...
void entry_available()
{
// entry now available
watcher->entry().keyBundle().privateKey().signMessage(...);
}
\endcode
Unlike private content, public content is always usable even if the
entry is not available. Serialized entry data contains all of the
metadata necessary to reconstruct the public content.
Now, even though an entry may be available, it does not
mean you have access to use it for operations. For
example, even though a KeyBundle entry offered by a Smart Card
may be available, as soon as you try to use the PrivateKey object
for a signing operation, a PIN might be asked for. You can call
ensureAccess() if you want to synchronously provide the PIN
early on:
\code
if(entry.ensureAccess())
{
// do private key stuff
...
}
\endcode
Note that you don't have to call ensureAvailable() before
ensureAccess(). Calling the latter is enough to imply
both.
After an application is configured to use a particular key,
it is expected that its usual running procedure will be:
1) Construct KeyStoreEntry from the serialized data.
2) If the content object is not available, wait for it
(with either ensureAvailable() or KeyStoreEntryWatcher).
3) Pass the content object(s) to a high level operation like TLS.
In this case, any PIN prompting and private key operations
would be caused/handled from the TLS object. Omit step 2 and
the private key operations might cause token prompting.
\ingroup UserAPI
*/
class QCA_EXPORT KeyStoreEntry : public Algorithm
{
public:
- /**
- The type of entry in the KeyStore
- */
- enum Type
- {
- TypeKeyBundle,
- TypeCertificate,
- TypeCRL,
- TypePGPSecretKey,
- TypePGPPublicKey
- };
-
- /**
- Create an empty KeyStoreEntry
- */
- KeyStoreEntry();
-
- /**
- Create a passive KeyStoreEntry based on a serialized
- string
-
- \param serialized the string containing the keystore entry information
-
- \sa fromString
- */
- KeyStoreEntry(const QString &serialized);
-
- /**
- Standard copy constructor
-
- \param from the source entry
- */
- KeyStoreEntry(const KeyStoreEntry &from);
-
- ~KeyStoreEntry();
-
- /**
- Standard assignment operator
-
- \param from the source entry
- */
- KeyStoreEntry & operator=(const KeyStoreEntry &from);
-
- /**
- Test if this key is empty (null)
- */
- bool isNull() const;
-
- /**
- Test if the key is available for use.
-
- A key is considered available if the key's private
- content is present.
-
- \sa ensureAvailable
- \sa isAccessible
- */
- bool isAvailable() const;
-
- /**
- Test if the key is currently accessible.
-
- This means that the private key part can be used
- at this time. For a smartcard, this means that all
- required operations (e.g. login / PIN entry) are
- completed.
-
- If isAccessible() is true, then the key
- is necessarily available (i.e. isAvailable() is
- also true).
-
- \sa ensureAccessible
- \sa isAvailable
- */
- bool isAccessible() const;
-
- /**
- Determine the type of key stored in this object
- */
- Type type() const;
-
- /**
- The name associated with the key stored in this object
- */
- QString name() const;
-
- /**
- The ID associated with the key stored in this object.
- */
- QString id() const;
-
- /**
- The name of the KeyStore for this key object
- */
- QString storeName() const;
-
- /**
- The id of the KeyStore for this key object
-
- \sa KeyStore::id()
- */
- QString storeId() const;
-
- /**
- Serialize into a string for use as a passive entry
- */
- QString toString() const;
-
- /**
- Load a passive entry by using a serialized string
- as input
-
- \param serialized the string containing the keystore entry information
-
- \return the newly created KeyStoreEntry
- */
- static KeyStoreEntry fromString(const QString &serialized);
-
- /**
- If a KeyBundle is stored in this object, return that
- bundle.
- */
- KeyBundle keyBundle() const;
-
- /**
- If a Certificate is stored in this object, return that
- certificate.
- */
- Certificate certificate() const;
-
- /**
- If a CRL is stored in this object, return the value
- of the CRL
- */
- CRL crl() const;
-
- /**
- If the key stored in this object is a private
- PGP key, return the contents of that key.
- */
- PGPKey pgpSecretKey() const;
-
- /**
- If the key stored in this object is either an
- public or private PGP key, extract the public key
- part of that PGP key.
- */
- PGPKey pgpPublicKey() const;
-
- /**
- Returns true if the entry is available, otherwise false.
-
- Available means that any private content for this entry is
- present and ready for use. In the case of a smart card, this
- will ensure the card is inserted, and may invoke a token
- prompt.
-
- Calling this function on an already available entry may cause
- the entry to be refreshed.
-
- \sa isAvailable
- \sa ensureAccess
-
- \note This function is blocking.
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- bool ensureAvailable();
-
- /**
- Like ensureAvailable, but will also ensure
- that the PIN is provided if needed.
-
- \sa isAccessible
- \sa ensureAvailable
-
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- bool ensureAccess();
+ /**
+ The type of entry in the KeyStore
+ */
+ enum Type {
+ TypeKeyBundle,
+ TypeCertificate,
+ TypeCRL,
+ TypePGPSecretKey,
+ TypePGPPublicKey
+ };
+
+ /**
+ Create an empty KeyStoreEntry
+ */
+ KeyStoreEntry();
+
+ /**
+ Create a passive KeyStoreEntry based on a serialized
+ string
+
+ \param serialized the string containing the keystore entry information
+
+ \sa fromString
+ */
+ KeyStoreEntry(const QString &serialized);
+
+ /**
+ Standard copy constructor
+
+ \param from the source entry
+ */
+ KeyStoreEntry(const KeyStoreEntry &from);
+
+ ~KeyStoreEntry();
+
+ /**
+ Standard assignment operator
+
+ \param from the source entry
+ */
+ KeyStoreEntry &operator=(const KeyStoreEntry &from);
+
+ /**
+ Test if this key is empty (null)
+ */
+ bool isNull() const;
+
+ /**
+ Test if the key is available for use.
+
+ A key is considered available if the key's private
+ content is present.
+
+ \sa ensureAvailable
+ \sa isAccessible
+ */
+ bool isAvailable() const;
+
+ /**
+ Test if the key is currently accessible.
+
+ This means that the private key part can be used
+ at this time. For a smartcard, this means that all
+ required operations (e.g. login / PIN entry) are
+ completed.
+
+ If isAccessible() is true, then the key
+ is necessarily available (i.e. isAvailable() is
+ also true).
+
+ \sa ensureAccessible
+ \sa isAvailable
+ */
+ bool isAccessible() const;
+
+ /**
+ Determine the type of key stored in this object
+ */
+ Type type() const;
+
+ /**
+ The name associated with the key stored in this object
+ */
+ QString name() const;
+
+ /**
+ The ID associated with the key stored in this object.
+ */
+ QString id() const;
+
+ /**
+ The name of the KeyStore for this key object
+ */
+ QString storeName() const;
+
+ /**
+ The id of the KeyStore for this key object
+
+ \sa KeyStore::id()
+ */
+ QString storeId() const;
+
+ /**
+ Serialize into a string for use as a passive entry
+ */
+ QString toString() const;
+
+ /**
+ Load a passive entry by using a serialized string
+ as input
+
+ \param serialized the string containing the keystore entry information
+
+ \return the newly created KeyStoreEntry
+ */
+ static KeyStoreEntry fromString(const QString &serialized);
+
+ /**
+ If a KeyBundle is stored in this object, return that
+ bundle.
+ */
+ KeyBundle keyBundle() const;
+
+ /**
+ If a Certificate is stored in this object, return that
+ certificate.
+ */
+ Certificate certificate() const;
+
+ /**
+ If a CRL is stored in this object, return the value
+ of the CRL
+ */
+ CRL crl() const;
+
+ /**
+ If the key stored in this object is a private
+ PGP key, return the contents of that key.
+ */
+ PGPKey pgpSecretKey() const;
+
+ /**
+ If the key stored in this object is either an
+ public or private PGP key, extract the public key
+ part of that PGP key.
+ */
+ PGPKey pgpPublicKey() const;
+
+ /**
+ Returns true if the entry is available, otherwise false.
+
+ Available means that any private content for this entry is
+ present and ready for use. In the case of a smart card, this
+ will ensure the card is inserted, and may invoke a token
+ prompt.
+
+ Calling this function on an already available entry may cause
+ the entry to be refreshed.
+
+ \sa isAvailable
+ \sa ensureAccess
+
+ \note This function is blocking.
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ bool ensureAvailable();
+
+ /**
+ Like ensureAvailable, but will also ensure
+ that the PIN is provided if needed.
+
+ \sa isAccessible
+ \sa ensureAvailable
+
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ bool ensureAccess();
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
- friend class KeyStoreTracker;
+ friend class KeyStoreTracker;
};
/**
\class KeyStoreEntryWatcher qca_keystore.h QtCrypto
Class to monitor the availability of a KeyStoreEntry
Some KeyStore types have the concept of an entry that can be
available only part of the time (for example, a smart card that
- can be removed). This class allows you to identify when a
+ can be removed). This class allows you to identify when a
KeyStoreEntry becomes available / unavailable.
\note You can also monitor availability of a whole KeyStore,
using KeyStoreManager::keyStoreAvailable() signal, and
- the KeyStore::unavailable() signal.
+ the KeyStore::unavailable() signal.
- \sa KeyStore for more discussion on availability of
+ \sa KeyStore for more discussion on availability of
keys and related objects.
\ingroup UserAPI
*/
class QCA_EXPORT KeyStoreEntryWatcher : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor.
+ /**
+ Standard constructor.
- This creates an object that monitors the specified KeyStore entry,
- emitting available() and unavailable() as the entry becomes available
- and unavailable respectively.
+ This creates an object that monitors the specified KeyStore entry,
+ emitting available() and unavailable() as the entry becomes available
+ and unavailable respectively.
- \param e the KeyStoreEntry to monitor
- \param parent the parent object for this object
- */
- explicit KeyStoreEntryWatcher(const KeyStoreEntry &e, QObject *parent = 0);
+ \param e the KeyStoreEntry to monitor
+ \param parent the parent object for this object
+ */
+ explicit KeyStoreEntryWatcher(const KeyStoreEntry &e, QObject *parent = 0);
- ~KeyStoreEntryWatcher();
+ ~KeyStoreEntryWatcher();
- /**
- The KeyStoreEntry that is being monitored
- */
- KeyStoreEntry entry() const;
+ /**
+ The KeyStoreEntry that is being monitored
+ */
+ KeyStoreEntry entry() const;
Q_SIGNALS:
- /**
- This signal is emitted when the entry that is being monitored
- becomes available.
- */
- void available();
-
- /**
- This signal is emitted when the entry that is being monitored
- becomes unavailble.
- */
- void unavailable();
+ /**
+ This signal is emitted when the entry that is being monitored
+ becomes available.
+ */
+ void available();
+
+ /**
+ This signal is emitted when the entry that is being monitored
+ becomes unavailble.
+ */
+ void unavailable();
private:
- Q_DISABLE_COPY(KeyStoreEntryWatcher)
+ Q_DISABLE_COPY(KeyStoreEntryWatcher)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class KeyStore qca_keystore.h QtCrypto
General purpose key storage object
Examples of use of this are:
- systemstore: System TrustedCertificates
- accepted self-signed: Application TrustedCertificates
- apple keychain: User Identities
- smartcard: SmartCard Identities
- gnupg: PGPKeyring Identities,PGPPublicKeys
\note
- there can be multiple KeyStore objects referring to the same id
- when a KeyStore is constructed, it refers to a given id (deviceId)
and internal contextId. if the context goes away, the KeyStore
becomes invalid (isValid() == false), and unavailable() is emitted.
even if the device later reappears, the KeyStore remains invalid.
a new KeyStore will have to be created to use the device again.
\ingroup UserAPI
*/
class QCA_EXPORT KeyStore : public QObject, public Algorithm
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The type of keystore
- */
- enum Type
- {
- System, ///< objects such as root certificates
- User, ///< objects such as Apple Keychain, KDE Wallet
- Application, ///< for caching accepted self-signed certificates
- SmartCard, ///< for smartcards
- PGPKeyring ///< for a PGP keyring
- };
-
- /**
- Obtain a specific KeyStore
-
- \param id the identification for the key store
- \param keyStoreManager the parent manager for this keystore
- */
- KeyStore(const QString &id, KeyStoreManager *keyStoreManager);
-
- ~KeyStore();
-
- /**
- Check if this KeyStore is valid
-
- \return true if the KeyStore is valid
- */
- bool isValid() const;
-
- /**
- The KeyStore Type
- */
- Type type() const;
-
- /**
- The name associated with the KeyStore
- */
- QString name() const;
-
- /**
- The ID associated with the KeyStore
- */
- QString id() const;
-
- /**
- Test if the KeyStore is writeable or not
-
- \return true if the KeyStore is read-only
- */
- bool isReadOnly() const;
-
- /**
- Turns on asynchronous mode for this KeyStore instance.
-
- Normally, entryList() and writeEntry() are blocking
- calls. However, if startAsynchronousMode() is called,
- then these functions will return immediately. entryList()
- will return with the latest known entries, or an empty
- list if none are known yet (in this mode, updated() will
- be emitted once the initial entries are known, even if the
- store has not actually been altered). writeEntry() will
- always return an empty string, and the entryWritten()
- signal indicates the result of a write.
- */
- void startAsynchronousMode();
-
- /**
- A list of the KeyStoreEntry objects in this store
-
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler
- (this is not a concern if asynchronous mode is enabled).
-
- \sa startAsynchronousMode
- */
- QList<KeyStoreEntry> entryList() const;
-
- /**
- test if the KeyStore holds trusted certificates (and CRLs)
- */
- bool holdsTrustedCertificates() const;
-
- /**
- test if the KeyStore holds identities (eg KeyBundle or PGPSecretKey)
- */
- bool holdsIdentities() const;
-
- /**
- test if the KeyStore holds PGPPublicKey objects
- */
- bool holdsPGPPublicKeys() const;
-
- /**
- Add a entry to the KeyStore
-
- Returns the entryId of the written entry or an empty
- string on failure.
-
- \param kb the KeyBundle to add to the KeyStore
-
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler
- (this is not a concern if asynchronous mode is enabled).
+ /**
+ The type of keystore
+ */
+ enum Type {
+ System, ///< objects such as root certificates
+ User, ///< objects such as Apple Keychain, KDE Wallet
+ Application, ///< for caching accepted self-signed certificates
+ SmartCard, ///< for smartcards
+ PGPKeyring ///< for a PGP keyring
+ };
+
+ /**
+ Obtain a specific KeyStore
+
+ \param id the identification for the key store
+ \param keyStoreManager the parent manager for this keystore
+ */
+ KeyStore(const QString &id, KeyStoreManager *keyStoreManager);
+
+ ~KeyStore();
+
+ /**
+ Check if this KeyStore is valid
+
+ \return true if the KeyStore is valid
+ */
+ bool isValid() const;
+
+ /**
+ The KeyStore Type
+ */
+ Type type() const;
+
+ /**
+ The name associated with the KeyStore
+ */
+ QString name() const;
+
+ /**
+ The ID associated with the KeyStore
+ */
+ QString id() const;
+
+ /**
+ Test if the KeyStore is writeable or not
+
+ \return true if the KeyStore is read-only
+ */
+ bool isReadOnly() const;
+
+ /**
+ Turns on asynchronous mode for this KeyStore instance.
+
+ Normally, entryList() and writeEntry() are blocking
+ calls. However, if startAsynchronousMode() is called,
+ then these functions will return immediately. entryList()
+ will return with the latest known entries, or an empty
+ list if none are known yet (in this mode, updated() will
+ be emitted once the initial entries are known, even if the
+ store has not actually been altered). writeEntry() will
+ always return an empty string, and the entryWritten()
+ signal indicates the result of a write.
+ */
+ void startAsynchronousMode();
+
+ /**
+ A list of the KeyStoreEntry objects in this store
+
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler
+ (this is not a concern if asynchronous mode is enabled).
+
+ \sa startAsynchronousMode
+ */
+ QList<KeyStoreEntry> entryList() const;
+
+ /**
+ test if the KeyStore holds trusted certificates (and CRLs)
+ */
+ bool holdsTrustedCertificates() const;
+
+ /**
+ test if the KeyStore holds identities (eg KeyBundle or PGPSecretKey)
+ */
+ bool holdsIdentities() const;
+
+ /**
+ test if the KeyStore holds PGPPublicKey objects
+ */
+ bool holdsPGPPublicKeys() const;
+
+ /**
+ Add a entry to the KeyStore
+
+ Returns the entryId of the written entry or an empty
+ string on failure.
+
+ \param kb the KeyBundle to add to the KeyStore
+
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler
+ (this is not a concern if asynchronous mode is enabled).
- \sa startAsynchronousMode
- */
- QString writeEntry(const KeyBundle &kb);
+ \sa startAsynchronousMode
+ */
+ QString writeEntry(const KeyBundle &kb);
- /**
- \overload
+ /**
+ \overload
- \param cert the Certificate to add to the KeyStore
- */
- QString writeEntry(const Certificate &cert);
+ \param cert the Certificate to add to the KeyStore
+ */
+ QString writeEntry(const Certificate &cert);
- /**
- \overload
+ /**
+ \overload
- \param crl the CRL to add to the KeyStore
- */
- QString writeEntry(const CRL &crl);
+ \param crl the CRL to add to the KeyStore
+ */
+ QString writeEntry(const CRL &crl);
- /**
- \overload
+ /**
+ \overload
- \param key the PGPKey to add to the KeyStore
+ \param key the PGPKey to add to the KeyStore
- \return a ref to the key in the keyring
- */
- QString writeEntry(const PGPKey &key);
+ \return a ref to the key in the keyring
+ */
+ QString writeEntry(const PGPKey &key);
- /**
- Delete the a specified KeyStoreEntry from this KeyStore
+ /**
+ Delete the a specified KeyStoreEntry from this KeyStore
- \param id the ID for the entry to be deleted
+ \param id the ID for the entry to be deleted
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler
- (this is not a concern if asynchronous mode is enabled).
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler
+ (this is not a concern if asynchronous mode is enabled).
- \sa startAsynchronousMode
- */
- bool removeEntry(const QString &id);
+ \sa startAsynchronousMode
+ */
+ bool removeEntry(const QString &id);
Q_SIGNALS:
- /**
- Emitted when the KeyStore is changed
+ /**
+ Emitted when the KeyStore is changed
- This occurs if entries are added, removed, or changed in this
- KeyStore, including changes in entry availability.
- */
- void updated();
+ This occurs if entries are added, removed, or changed in this
+ KeyStore, including changes in entry availability.
+ */
+ void updated();
- /**
- Emitted when the KeyStore becomes unavailable
- */
- void unavailable();
+ /**
+ Emitted when the KeyStore becomes unavailable
+ */
+ void unavailable();
- /**
- Emitted when an entry has been written, in asynchronous
- mode.
+ /**
+ Emitted when an entry has been written, in asynchronous
+ mode.
- \param entryId is the newly written entry id on success,
- or an empty string if the write failed.
- */
- void entryWritten(const QString &entryId);
+ \param entryId is the newly written entry id on success,
+ or an empty string if the write failed.
+ */
+ void entryWritten(const QString &entryId);
- /**
- Emitted when an entry has been removed, in asynchronous
- mode.
+ /**
+ Emitted when an entry has been removed, in asynchronous
+ mode.
- \param success indicates if the removal succeeded (true) or not (false).
- */
- void entryRemoved(bool success);
+ \param success indicates if the removal succeeded (true) or not (false).
+ */
+ void entryRemoved(bool success);
private:
- Q_DISABLE_COPY(KeyStore)
+ Q_DISABLE_COPY(KeyStore)
- friend class KeyStorePrivate;
- KeyStorePrivate *d;
+ friend class KeyStorePrivate;
+ KeyStorePrivate *d;
- friend class KeyStoreManagerPrivate;
+ friend class KeyStoreManagerPrivate;
};
/**
\class KeyStoreInfo qca_keystore.h QtCrypto
Key store information, outside of a KeyStore object
This class is used in conjunction with the Event class,
and related classes such as PasswordAsker and TokenAsker,
to describe the key store source of the Event.
Each KeyStoreInfo represents a single KeyStore, and describes
- the type of store (e.g. smartcard or PGP keyring - see
+ the type of store (e.g. smartcard or PGP keyring - see
KeyStore::Type), and a couple of names. The id() of a KeyStore
- is used to reference it, and is typically of the form
+ is used to reference it, and is typically of the form
"qca-mystorename". The name() of a KeyStore is used to describe
it (i.e. this is the "pretty" name to show the user), and is
typically of the form "My Store Name".
\ingroup UserAPI
*/
class QCA_EXPORT KeyStoreInfo
{
public:
- /**
- Constructor.
+ /**
+ Constructor.
- \note This form of constructor for KeyStoreInfo
- produces an object that does not describe any
- KeyStore, and isNull() will return true.
- */
- KeyStoreInfo();
+ \note This form of constructor for KeyStoreInfo
+ produces an object that does not describe any
+ KeyStore, and isNull() will return true.
+ */
+ KeyStoreInfo();
- /**
- Standard constructor.
+ /**
+ Standard constructor.
- This builds a KeyStoreInfo object that descibes a
- KeyStore.
+ This builds a KeyStoreInfo object that descibes a
+ KeyStore.
- \param type the type of KeyStore
- \param id the identification of the KeyStore
- \param name the descriptive name of the KeyStore
- */
- KeyStoreInfo(KeyStore::Type type, const QString &id, const QString &name);
+ \param type the type of KeyStore
+ \param id the identification of the KeyStore
+ \param name the descriptive name of the KeyStore
+ */
+ KeyStoreInfo(KeyStore::Type type, const QString &id, const QString &name);
- /**
- Copy constructor.
+ /**
+ Copy constructor.
- \param from the KeyStoreInfo to copy from
- */
- KeyStoreInfo(const KeyStoreInfo &from);
+ \param from the KeyStoreInfo to copy from
+ */
+ KeyStoreInfo(const KeyStoreInfo &from);
- ~KeyStoreInfo();
+ ~KeyStoreInfo();
- /**
- Assignment operator.
+ /**
+ Assignment operator.
- \param from the KeyStoreInfo to copy from
- */
- KeyStoreInfo & operator=(const KeyStoreInfo &from);
+ \param from the KeyStoreInfo to copy from
+ */
+ KeyStoreInfo &operator=(const KeyStoreInfo &from);
- /**
- Test if this object is valid
+ /**
+ Test if this object is valid
- \return true if the object is not valid
- */
- bool isNull() const;
+ \return true if the object is not valid
+ */
+ bool isNull() const;
- /**
- The Type of KeyStore that this KeyStoreInfo object
- describes.
- */
- KeyStore::Type type() const;
+ /**
+ The Type of KeyStore that this KeyStoreInfo object
+ describes.
+ */
+ KeyStore::Type type() const;
- /**
- The unique identification of the KeyStore that
- this KeyStoreInfo object describes.
- */
- QString id() const;
+ /**
+ The unique identification of the KeyStore that
+ this KeyStoreInfo object describes.
+ */
+ QString id() const;
- /**
- The descriptive name of the KeyStore that this
- KeyStoreInfo object describes.
- */
- QString name() const;
+ /**
+ The descriptive name of the KeyStore that this
+ KeyStoreInfo object describes.
+ */
+ QString name() const;
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class KeyStoreManager qca_keystore.h QtCrypto
Access keystores, and monitor keystores for changes.
Before you can access a KeyStore, you must create a
KeyStoreManager. You then need to start()
the KeyStoreManager, and either wait for the busyFinished()
signal, or block using waitForBusyFinished().
If you know the KeyStoreEntry that you need, you can
use KeyStore passively, as described in the KeyStoreEntry
documentation.
\ingroup UserAPI
*/
class QCA_EXPORT KeyStoreManager : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Create a new KeyStoreManager
-
- \param parent the parent for this object
- */
- KeyStoreManager(QObject *parent = 0);
- ~KeyStoreManager();
-
- /**
- Initialize all key store providers
- */
- static void start();
-
- /**
- Initialize a specific key store provider
-
- \param provider the name of the provider to start
- */
- static void start(const QString &provider);
-
- /**
- Indicates if the manager is busy looking for key stores
- */
- bool isBusy() const;
-
- /**
- Blocks until the manager is done looking for key stores
- */
- void waitForBusyFinished();
-
- /**
- A list of all the key stores
- */
- QStringList keyStores() const;
-
- /**
- The diagnostic result of key store operations, such as
- warnings and errors
- */
- static QString diagnosticText();
-
- /**
- Clears the diagnostic result log
- */
- static void clearDiagnosticText();
-
- /**
- If you are not using the eventloop, call this to update
- the object state to the present
- */
- void sync();
+ /**
+ Create a new KeyStoreManager
+
+ \param parent the parent for this object
+ */
+ KeyStoreManager(QObject *parent = 0);
+ ~KeyStoreManager();
+
+ /**
+ Initialize all key store providers
+ */
+ static void start();
+
+ /**
+ Initialize a specific key store provider
+
+ \param provider the name of the provider to start
+ */
+ static void start(const QString &provider);
+
+ /**
+ Indicates if the manager is busy looking for key stores
+ */
+ bool isBusy() const;
+
+ /**
+ Blocks until the manager is done looking for key stores
+ */
+ void waitForBusyFinished();
+
+ /**
+ A list of all the key stores
+ */
+ QStringList keyStores() const;
+
+ /**
+ The diagnostic result of key store operations, such as
+ warnings and errors
+ */
+ static QString diagnosticText();
+
+ /**
+ Clears the diagnostic result log
+ */
+ static void clearDiagnosticText();
+
+ /**
+ If you are not using the eventloop, call this to update
+ the object state to the present
+ */
+ void sync();
Q_SIGNALS:
- /**
- emitted when the manager has started looking for key stores
- */
- void busyStarted();
+ /**
+ emitted when the manager has started looking for key stores
+ */
+ void busyStarted();
- /**
- emitted when the manager has finished looking for key stores
- */
- void busyFinished();
+ /**
+ emitted when the manager has finished looking for key stores
+ */
+ void busyFinished();
- /**
- emitted when a new key store becomes available
+ /**
+ emitted when a new key store becomes available
- \param id the name of the key store that has become available
- */
- void keyStoreAvailable(const QString &id);
+ \param id the name of the key store that has become available
+ */
+ void keyStoreAvailable(const QString &id);
private:
- Q_DISABLE_COPY(KeyStoreManager)
+ Q_DISABLE_COPY(KeyStoreManager)
- friend class KeyStoreManagerPrivate;
- KeyStoreManagerPrivate *d;
+ friend class KeyStoreManagerPrivate;
+ KeyStoreManagerPrivate *d;
- friend class Global;
- friend class KeyStorePrivate;
+ friend class Global;
+ friend class KeyStorePrivate;
- static void scan();
- static void shutdown();
+ static void scan();
+ static void shutdown();
};
}
#endif
diff --git a/include/QtCrypto/qca_publickey.h b/include/QtCrypto/qca_publickey.h
index 57b2292c..a3a8a28e 100644
--- a/include/QtCrypto/qca_publickey.h
+++ b/include/QtCrypto/qca_publickey.h
@@ -1,1540 +1,1535 @@
/*
* qca_publickey.h - Qt Cryptographic Architecture
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_publickey.h
Header file for PublicKey and PrivateKey related classes
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_PUBLICKEY_H
#define QCA_PUBLICKEY_H
#include <QObject>
#include "qca_core.h"
-namespace QCA {
+namespace QCA
+{
class PublicKey;
class PrivateKey;
class KeyGenerator;
class RSAPublicKey;
class RSAPrivateKey;
class DSAPublicKey;
class DSAPrivateKey;
class DHPublicKey;
class DHPrivateKey;
/**
Encryption algorithms
*/
-enum EncryptionAlgorithm
-{
- EME_PKCS1v15, ///< Block type 2 (PKCS#1, Version 1.5)
- EME_PKCS1_OAEP, ///< Optimal asymmetric encryption padding (PKCS#1, Version 2.0)
- EME_PKCS1v15_SSL, ///< PKCS#1, Version 1.5 with an SSL-specific modification
- EME_NO_PADDING ///< Raw RSA encryption
+enum EncryptionAlgorithm {
+ EME_PKCS1v15, ///< Block type 2 (PKCS#1, Version 1.5)
+ EME_PKCS1_OAEP, ///< Optimal asymmetric encryption padding (PKCS#1, Version 2.0)
+ EME_PKCS1v15_SSL, ///< PKCS#1, Version 1.5 with an SSL-specific modification
+ EME_NO_PADDING ///< Raw RSA encryption
};
/**
Signature algorithm variants
Note that most signature algorithms follow a process of first hashing the
plaintext data to be signed, creating a payload format that wraps the hash
value (among other things), and then signing the payload with the private
key. So, for example, an EMSA3(SHA1) signature outputted by QCA cannot be
verified by merely performing RSA and SHA1 operations (e.g.
"openssl rsautl -verify" and comparing with sha1sum), because that would not
take the EMSA3 payload format into consideration.
*/
-enum SignatureAlgorithm
-{
- SignatureUnknown, ///< Unknown signing algorithm
- EMSA1_SHA1, ///< SHA1, with EMSA1 (IEEE1363-2000) encoding (this is the usual DSA algorithm - FIPS186)
- EMSA3_SHA1, ///< SHA1, with EMSA3 (ie PKCS#1 Version 1.5) encoding
- EMSA3_MD5, ///< MD5, with EMSA3 (ie PKCS#1 Version 1.5) encoding (this is the usual RSA algorithm)
- EMSA3_MD2, ///< MD2, with EMSA3 (ie PKCS#1 Version 1.5) encoding
- EMSA3_RIPEMD160, ///< RIPEMD160, with EMSA3 (ie PKCS#1 Version 1.5) encoding
- EMSA3_Raw, ///< EMSA3 without computing a message digest or a DigestInfo encoding (identical to PKCS#11's CKM_RSA_PKCS mechanism)
- EMSA3_SHA224, ///< SHA224, with EMSA3 (ie PKCS#1 Version 1.5) encoding
- EMSA3_SHA256, ///< SHA256, with EMSA3 (ie PKCS#1 Version 1.5) encoding
- EMSA3_SHA384, ///< SHA384, with EMSA3 (ie PKCS#1 Version 1.5) encoding
- EMSA3_SHA512 ///< SHA512, with EMSA3 (ie PKCS#1 Version 1.5) encoding
+enum SignatureAlgorithm {
+ SignatureUnknown, ///< Unknown signing algorithm
+ EMSA1_SHA1, ///< SHA1, with EMSA1 (IEEE1363-2000) encoding (this is the usual DSA algorithm - FIPS186)
+ EMSA3_SHA1, ///< SHA1, with EMSA3 (ie PKCS#1 Version 1.5) encoding
+ EMSA3_MD5, ///< MD5, with EMSA3 (ie PKCS#1 Version 1.5) encoding (this is the usual RSA algorithm)
+ EMSA3_MD2, ///< MD2, with EMSA3 (ie PKCS#1 Version 1.5) encoding
+ EMSA3_RIPEMD160, ///< RIPEMD160, with EMSA3 (ie PKCS#1 Version 1.5) encoding
+ EMSA3_Raw, ///< EMSA3 without computing a message digest or a DigestInfo encoding (identical to PKCS#11's CKM_RSA_PKCS mechanism)
+ EMSA3_SHA224, ///< SHA224, with EMSA3 (ie PKCS#1 Version 1.5) encoding
+ EMSA3_SHA256, ///< SHA256, with EMSA3 (ie PKCS#1 Version 1.5) encoding
+ EMSA3_SHA384, ///< SHA384, with EMSA3 (ie PKCS#1 Version 1.5) encoding
+ EMSA3_SHA512 ///< SHA512, with EMSA3 (ie PKCS#1 Version 1.5) encoding
};
/**
Signature formats (DSA only)
*/
-enum SignatureFormat
-{
- DefaultFormat, ///< For DSA, this is the same as IEEE_1363
- IEEE_1363, ///< 40-byte format from IEEE 1363 (Botan/.NET)
- DERSequence ///< Signature wrapped in DER formatting (OpenSSL/Java)
+enum SignatureFormat {
+ DefaultFormat, ///< For DSA, this is the same as IEEE_1363
+ IEEE_1363, ///< 40-byte format from IEEE 1363 (Botan/.NET)
+ DERSequence ///< Signature wrapped in DER formatting (OpenSSL/Java)
};
/**
Password-based encryption
*/
-enum PBEAlgorithm
-{
- PBEDefault, ///< Use modern default (same as PBES2_TripleDES_SHA1)
- PBES2_DES_SHA1, ///< PKCS#5 v2.0 DES/CBC,SHA1
- PBES2_TripleDES_SHA1, ///< PKCS#5 v2.0 TripleDES/CBC,SHA1
- PBES2_AES128_SHA1, ///< PKCS#5 v2.0 AES-128/CBC,SHA1
- PBES2_AES192_SHA1, ///< PKCS#5 v2.0 AES-192/CBC,SHA1
- PBES2_AES256_SHA1 ///< PKCS#5 v2.0 AES-256/CBC,SHA1
+enum PBEAlgorithm {
+ PBEDefault, ///< Use modern default (same as PBES2_TripleDES_SHA1)
+ PBES2_DES_SHA1, ///< PKCS#5 v2.0 DES/CBC,SHA1
+ PBES2_TripleDES_SHA1, ///< PKCS#5 v2.0 TripleDES/CBC,SHA1
+ PBES2_AES128_SHA1, ///< PKCS#5 v2.0 AES-128/CBC,SHA1
+ PBES2_AES192_SHA1, ///< PKCS#5 v2.0 AES-192/CBC,SHA1
+ PBES2_AES256_SHA1 ///< PKCS#5 v2.0 AES-256/CBC,SHA1
};
/**
Return value from a format conversion
Note that if you are checking for any result other than ConvertGood,
then you may be introducing a provider specific dependency.
*/
-enum ConvertResult
-{
- ConvertGood, ///< Conversion succeeded, results should be valid
- ErrorDecode, ///< General failure in the decode stage
- ErrorPassphrase, ///< Failure because of incorrect passphrase
- ErrorFile ///< Failure because of incorrect file
+enum ConvertResult {
+ ConvertGood, ///< Conversion succeeded, results should be valid
+ ErrorDecode, ///< General failure in the decode stage
+ ErrorPassphrase, ///< Failure because of incorrect passphrase
+ ErrorFile ///< Failure because of incorrect file
};
/**
Well known discrete logarithm group sets
These sets are derived from three main sources:
- Java Cryptographic Extensions,
+ Java Cryptographic Extensions,
<a href="http://www.ietf.org/rfc/rfc2412.txt">RFC2412</a> and
<a href="http://www.ietf.org/rfc/rfc3526.txt">RFC3526</a>.
*/
-enum DLGroupSet
-{
- DSA_512, ///< 512 bit group, for compatibility with JCE
- DSA_768, ///< 768 bit group, for compatibility with JCE
- DSA_1024, ///< 1024 bit group, for compatibility with JCE
- IETF_768, ///< Group 1 from RFC 2412, Section E.1
- IETF_1024, ///< Group 2 from RFC 2412, Section E.2
- IETF_1536, ///< 1536-bit MODP Group ("group 5") from RFC3526 Section 2.
- IETF_2048, ///< 2048-bit MODP Group ("group 14") from RFC3526 Section 3.
- IETF_3072, ///< 3072-bit MODP Group ("group 15") from RFC3526 Section 4.
- IETF_4096, ///< 4096-bit MODP Group ("group 16") from RFC3526 Section 5.
- IETF_6144, ///< 6144-bit MODP Group ("group 17") from RFC3526 Section 6.
- IETF_8192 ///< 8192-bit MODP Group ("group 18") from RFC3526 Section 7.
+enum DLGroupSet {
+ DSA_512, ///< 512 bit group, for compatibility with JCE
+ DSA_768, ///< 768 bit group, for compatibility with JCE
+ DSA_1024, ///< 1024 bit group, for compatibility with JCE
+ IETF_768, ///< Group 1 from RFC 2412, Section E.1
+ IETF_1024, ///< Group 2 from RFC 2412, Section E.2
+ IETF_1536, ///< 1536-bit MODP Group ("group 5") from RFC3526 Section 2.
+ IETF_2048, ///< 2048-bit MODP Group ("group 14") from RFC3526 Section 3.
+ IETF_3072, ///< 3072-bit MODP Group ("group 15") from RFC3526 Section 4.
+ IETF_4096, ///< 4096-bit MODP Group ("group 16") from RFC3526 Section 5.
+ IETF_6144, ///< 6144-bit MODP Group ("group 17") from RFC3526 Section 6.
+ IETF_8192 ///< 8192-bit MODP Group ("group 18") from RFC3526 Section 7.
};
/**
Encode a hash result in EMSA3 (PKCS#1) format
This is a convenience function for providers that only have access
to raw RSA signing (mainly smartcard providers). This is a built-in
function of QCA and does not utilize a provider. SHA1, MD5, MD2,
and RIPEMD160 are supported.
\param hashName the hash type used to create the digest
\param digest the digest to encode in EMSA3 format
\param size the desired size of the encoding output (-1 for automatic size)
*/
QCA_EXPORT QByteArray emsa3Encode(const QString &hashName, const QByteArray &digest, int size = -1);
/**
\class DLGroup qca_publickey.h QtCrypto
A discrete logarithm group
\ingroup UserAPI
*/
class QCA_EXPORT DLGroup
{
public:
- DLGroup();
+ DLGroup();
- /**
- Construct a discrete logarithm group from raw parameters
+ /**
+ Construct a discrete logarithm group from raw parameters
- \param p the P parameter
- \param q the Q parameter
- \param g the G parameter
- */
- DLGroup(const BigInteger &p, const BigInteger &q, const BigInteger &g);
+ \param p the P parameter
+ \param q the Q parameter
+ \param g the G parameter
+ */
+ DLGroup(const BigInteger &p, const BigInteger &q, const BigInteger &g);
- /**
- Construct a discrete logarithm group from raw parameters
+ /**
+ Construct a discrete logarithm group from raw parameters
- \param p the P parameter
- \param g the G parameter
- */
- DLGroup(const BigInteger &p, const BigInteger &g);
+ \param p the P parameter
+ \param g the G parameter
+ */
+ DLGroup(const BigInteger &p, const BigInteger &g);
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the group to copy from
- */
- DLGroup(const DLGroup &from);
- ~DLGroup();
+ \param from the group to copy from
+ */
+ DLGroup(const DLGroup &from);
+ ~DLGroup();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the DLGroup to copy from
- */
- DLGroup & operator=(const DLGroup &from);
+ \param from the DLGroup to copy from
+ */
+ DLGroup &operator=(const DLGroup &from);
- /**
- Provide a list of the supported group sets
+ /**
+ Provide a list of the supported group sets
- \param provider the provider to report which group sets are
- available. If not specified, all providers will be checked
- */
- static QList<DLGroupSet> supportedGroupSets(const QString &provider = QString());
+ \param provider the provider to report which group sets are
+ available. If not specified, all providers will be checked
+ */
+ static QList<DLGroupSet> supportedGroupSets(const QString &provider = QString());
- /**
- Test if the group is empty
- */
- bool isNull() const;
+ /**
+ Test if the group is empty
+ */
+ bool isNull() const;
- /**
- Provide the p component of the group
- */
- BigInteger p() const;
+ /**
+ Provide the p component of the group
+ */
+ BigInteger p() const;
- /**
- Provide the q component of the group
- */
- BigInteger q() const;
+ /**
+ Provide the q component of the group
+ */
+ BigInteger q() const;
- /**
- Provide the g component of the group
- */
- BigInteger g() const;
+ /**
+ Provide the g component of the group
+ */
+ BigInteger g() const;
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class PKey qca_publickey.h QtCrypto
General superclass for public (PublicKey) and private (PrivateKey) keys
used with asymmetric encryption techniques.
\ingroup UserAPI
*/
class QCA_EXPORT PKey : public Algorithm
{
public:
- /**
- Types of public key cryptography keys supported by QCA
- */
- enum Type {
- RSA, ///< RSA key
- DSA, ///< DSA key
- DH ///< Diffie Hellman key
- };
-
- /**
- Standard constructor
- */
- PKey();
-
- /**
- Standard copy constructor
-
- \param from the key to copy from
- */
- PKey(const PKey &from);
-
- ~PKey();
-
- /**
- Standard assignment operator
-
- \param from the PKey to copy from
- */
- PKey & operator=(const PKey &from);
-
- /**
- Test what types of keys are supported.
-
- Normally you would just test if the capability is present, however
- for PKey, you also need to test which types of keys are available.
- So if you want to figure out if RSA keys are supported, you need to
- do something like:
- \code
-if(!QCA::isSupported("pkey") ||
- !QCA::PKey::supportedTypes().contains(QCA::PKey::RSA))
-{
- // then there is no RSA key support
-}
-else
-{
- // there is RSA key support
-}
- \endcode
-
- To make things a bit more complex, supportedTypes() only
- checks for basic functionality. If you want to check that
- you can do operations with PEM or DER (eg toPEM(), fromPEM(), and
- the equivalent DER and PEMfile operations, plus anything else
- that uses them, including the constructor form that takes a
- fileName), then you need to check for supportedIOTypes() instead.
-
- \param provider the name of the provider to use, if a particular
- provider is required.
-
- \sa supportedIOTypes()
- */
- static QList<Type> supportedTypes(const QString &provider = QString());
-
- /**
- Test what types of keys are supported for IO operations
-
- If you are using PKey DER or PEM operations, then you need
- to check for appropriate support using this method. For example,
- if you want to check if you can export or import an RSA key, then
- you need to do something like:
- \code
-if(!QCA::isSupported("pkey") ||
- !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA))
-{
- // then there is no RSA key IO support
-}
-else
-{
- // there is RSA key IO support
-}
- \endcode
-
- Note that if you only want to check for basic functionality
- (ie not PEM or DER import/export), then you can use
- supportedTypes(). There is no need to use both - if the key type
- is supported for IO, then is also supported for basic operations.
-
- \param provider the name of the provider to use, if a particular
- provider is required.
-
- \sa supportedTypes()
- */
- static QList<Type> supportedIOTypes(const QString &provider = QString());
-
- /**
- Test if the key is null (empty)
-
- \return true if the key is null
- */
- bool isNull() const;
-
- /**
- Report the Type of key (eg RSA, DSA or Diffie Hellman)
-
- \sa isRSA, isDSA and isDH for boolean tests.
- */
- Type type() const;
-
- /**
- Report the number of bits in the key
- */
- int bitSize() const;
-
- /**
- Test if the key is an RSA key
- */
- bool isRSA() const;
-
- /**
- Test if the key is a DSA key
- */
- bool isDSA() const;
-
- /**
- Test if the key is a Diffie Hellman key
- */
- bool isDH() const;
-
- /**
- Test if the key is a public key
- */
- bool isPublic() const;
-
- /**
- Test if the key is a private key
- */
- bool isPrivate() const;
-
- /**
- Test if the key data can be exported. If the key resides on a
- smart card or other such device, this will likely return false.
- */
- bool canExport() const;
-
- /**
- Test if the key can be used for key agreement
- */
- bool canKeyAgree() const;
-
- /**
- Interpret this key as a PublicKey
-
- \sa toRSAPublicKey(), toDSAPublicKey() and toDHPublicKey()
- for protected forms of this call.
- */
- PublicKey toPublicKey() const;
-
- /**
- Interpret this key as a PrivateKey
- */
- PrivateKey toPrivateKey() const;
-
- /**
- test if two keys are equal
-
- \param a the key to compare with this key
- */
- bool operator==(const PKey &a) const;
-
- /**
- test if two keys are not equal
-
- \param a the key to compare with this key
- */
- bool operator!=(const PKey &a) const;
+ /**
+ Types of public key cryptography keys supported by QCA
+ */
+ enum Type {
+ RSA, ///< RSA key
+ DSA, ///< DSA key
+ DH ///< Diffie Hellman key
+ };
+
+ /**
+ Standard constructor
+ */
+ PKey();
+
+ /**
+ Standard copy constructor
+
+ \param from the key to copy from
+ */
+ PKey(const PKey &from);
+
+ ~PKey();
+
+ /**
+ Standard assignment operator
+
+ \param from the PKey to copy from
+ */
+ PKey &operator=(const PKey &from);
+
+ /**
+ Test what types of keys are supported.
+
+ Normally you would just test if the capability is present, however
+ for PKey, you also need to test which types of keys are available.
+ So if you want to figure out if RSA keys are supported, you need to
+ do something like:
+ \code
+ if(!QCA::isSupported("pkey") ||
+ !QCA::PKey::supportedTypes().contains(QCA::PKey::RSA))
+ {
+ // then there is no RSA key support
+ }
+ else
+ {
+ // there is RSA key support
+ }
+ \endcode
+
+ To make things a bit more complex, supportedTypes() only
+ checks for basic functionality. If you want to check that
+ you can do operations with PEM or DER (eg toPEM(), fromPEM(), and
+ the equivalent DER and PEMfile operations, plus anything else
+ that uses them, including the constructor form that takes a
+ fileName), then you need to check for supportedIOTypes() instead.
+
+ \param provider the name of the provider to use, if a particular
+ provider is required.
+
+ \sa supportedIOTypes()
+ */
+ static QList<Type> supportedTypes(const QString &provider = QString());
+
+ /**
+ Test what types of keys are supported for IO operations
+
+ If you are using PKey DER or PEM operations, then you need
+ to check for appropriate support using this method. For example,
+ if you want to check if you can export or import an RSA key, then
+ you need to do something like:
+ \code
+ if(!QCA::isSupported("pkey") ||
+ !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA))
+ {
+ // then there is no RSA key IO support
+ }
+ else
+ {
+ // there is RSA key IO support
+ }
+ \endcode
+
+ Note that if you only want to check for basic functionality
+ (ie not PEM or DER import/export), then you can use
+ supportedTypes(). There is no need to use both - if the key type
+ is supported for IO, then is also supported for basic operations.
+
+ \param provider the name of the provider to use, if a particular
+ provider is required.
+
+ \sa supportedTypes()
+ */
+ static QList<Type> supportedIOTypes(const QString &provider = QString());
+
+ /**
+ Test if the key is null (empty)
+
+ \return true if the key is null
+ */
+ bool isNull() const;
+
+ /**
+ Report the Type of key (eg RSA, DSA or Diffie Hellman)
+
+ \sa isRSA, isDSA and isDH for boolean tests.
+ */
+ Type type() const;
+
+ /**
+ Report the number of bits in the key
+ */
+ int bitSize() const;
+
+ /**
+ Test if the key is an RSA key
+ */
+ bool isRSA() const;
+
+ /**
+ Test if the key is a DSA key
+ */
+ bool isDSA() const;
+
+ /**
+ Test if the key is a Diffie Hellman key
+ */
+ bool isDH() const;
+
+ /**
+ Test if the key is a public key
+ */
+ bool isPublic() const;
+
+ /**
+ Test if the key is a private key
+ */
+ bool isPrivate() const;
+
+ /**
+ Test if the key data can be exported. If the key resides on a
+ smart card or other such device, this will likely return false.
+ */
+ bool canExport() const;
+
+ /**
+ Test if the key can be used for key agreement
+ */
+ bool canKeyAgree() const;
+
+ /**
+ Interpret this key as a PublicKey
+
+ \sa toRSAPublicKey(), toDSAPublicKey() and toDHPublicKey()
+ for protected forms of this call.
+ */
+ PublicKey toPublicKey() const;
+
+ /**
+ Interpret this key as a PrivateKey
+ */
+ PrivateKey toPrivateKey() const;
+
+ /**
+ test if two keys are equal
+
+ \param a the key to compare with this key
+ */
+ bool operator==(const PKey &a) const;
+
+ /**
+ test if two keys are not equal
+
+ \param a the key to compare with this key
+ */
+ bool operator!=(const PKey &a) const;
protected:
- /**
- Create a key of the specified type
+ /**
+ Create a key of the specified type
- \param type the name of the type of key to create
- \param provider the name of the provider to create the key in
- */
- PKey(const QString &type, const QString &provider);
+ \param type the name of the type of key to create
+ \param provider the name of the provider to create the key in
+ */
+ PKey(const QString &type, const QString &provider);
- /**
- Set the key
+ /**
+ Set the key
- \param k the key to assign from
- */
- void set(const PKey &k);
+ \param k the key to assign from
+ */
+ void set(const PKey &k);
- /**
- Interpret this key as an RSAPublicKey
+ /**
+ Interpret this key as an RSAPublicKey
- \note This function is essentially a convenience cast - if the
- key was created as a DSA key, this function cannot turn it into
- an RSA key.
+ \note This function is essentially a convenience cast - if the
+ key was created as a DSA key, this function cannot turn it into
+ an RSA key.
- \sa toPublicKey() for the public version of this method
- */
- RSAPublicKey toRSAPublicKey() const;
+ \sa toPublicKey() for the public version of this method
+ */
+ RSAPublicKey toRSAPublicKey() const;
- /**
- Interpret this key as an RSAPrivateKey
+ /**
+ Interpret this key as an RSAPrivateKey
- \note This function is essentially a convenience cast - if the
- key was created as a DSA key, this function cannot turn it into
- a RSA key.
+ \note This function is essentially a convenience cast - if the
+ key was created as a DSA key, this function cannot turn it into
+ a RSA key.
- \sa toPrivateKey() for the public version of this method
- */
- RSAPrivateKey toRSAPrivateKey() const;
+ \sa toPrivateKey() for the public version of this method
+ */
+ RSAPrivateKey toRSAPrivateKey() const;
- /**
- Interpret this key as an DSAPublicKey
+ /**
+ Interpret this key as an DSAPublicKey
- \note This function is essentially a convenience cast - if the
- key was created as an RSA key, this function cannot turn it into
- a DSA key.
+ \note This function is essentially a convenience cast - if the
+ key was created as an RSA key, this function cannot turn it into
+ a DSA key.
- \sa toPublicKey() for the public version of this method
- */
- DSAPublicKey toDSAPublicKey() const;
+ \sa toPublicKey() for the public version of this method
+ */
+ DSAPublicKey toDSAPublicKey() const;
- /**
- Interpret this key as a DSAPrivateKey
+ /**
+ Interpret this key as a DSAPrivateKey
- \note This function is essentially a convenience cast - if the
- key was created as an RSA key, this function cannot turn it into
- a DSA key.
+ \note This function is essentially a convenience cast - if the
+ key was created as an RSA key, this function cannot turn it into
+ a DSA key.
- \sa toPrivateKey() for the public version of this method
- */
- DSAPrivateKey toDSAPrivateKey() const;
+ \sa toPrivateKey() for the public version of this method
+ */
+ DSAPrivateKey toDSAPrivateKey() const;
- /**
- Interpret this key as an DHPublicKey
+ /**
+ Interpret this key as an DHPublicKey
- \note This function is essentially a convenience cast - if the
- key was created as a DSA key, this function cannot turn it into
- a DH key.
+ \note This function is essentially a convenience cast - if the
+ key was created as a DSA key, this function cannot turn it into
+ a DH key.
- \sa toPublicKey() for the public version of this method
- */
- DHPublicKey toDHPublicKey() const;
+ \sa toPublicKey() for the public version of this method
+ */
+ DHPublicKey toDHPublicKey() const;
- /**
- Interpret this key as a DHPrivateKey
+ /**
+ Interpret this key as a DHPrivateKey
- \note This function is essentially a convenience cast - if the
- key was created as a DSA key, this function cannot turn it into
- a DH key.
+ \note This function is essentially a convenience cast - if the
+ key was created as a DSA key, this function cannot turn it into
+ a DH key.
- \sa toPrivateKey() for the public version of this method
- */
- DHPrivateKey toDHPrivateKey() const;
+ \sa toPrivateKey() for the public version of this method
+ */
+ DHPrivateKey toDHPrivateKey() const;
private:
- void assignToPublic(PKey *dest) const;
- void assignToPrivate(PKey *dest) const;
+ void assignToPublic(PKey *dest) const;
+ void assignToPrivate(PKey *dest) const;
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class PublicKey qca_publickey.h QtCrypto
Generic public key
\ingroup UserAPI
*/
class QCA_EXPORT PublicKey : public PKey
{
public:
- /**
- Create an empty (null) public key
- */
- PublicKey();
-
- /**
- Create a public key based on a specified private key
-
- \param k the private key to extract the public key parts from
- */
- PublicKey(const PrivateKey &k);
-
- /**
- Import a public key from a PEM representation in a file
-
- \param fileName the name of the file containing the public key
-
- \sa fromPEMFile for an alternative method
- */
- PublicKey(const QString &fileName);
-
- /**
- Copy constructor
-
- \param from the PublicKey to copy from
- */
- PublicKey(const PublicKey &from);
-
- ~PublicKey();
-
- /**
- Assignment operator
-
- \param from the PublicKey to copy from
- */
- PublicKey & operator=(const PublicKey &from);
+ /**
+ Create an empty (null) public key
+ */
+ PublicKey();
- /**
- Convenience method to convert this key to an RSAPublicKey
+ /**
+ Create a public key based on a specified private key
- Note that if the key is not an RSA key (eg it is DSA or DH),
- then this will produce a null key.
- */
- RSAPublicKey toRSA() const;
+ \param k the private key to extract the public key parts from
+ */
+ PublicKey(const PrivateKey &k);
- /**
- Convenience method to convert this key to a DSAPublicKey
+ /**
+ Import a public key from a PEM representation in a file
- Note that if the key is not an DSA key (eg it is RSA or DH),
- then this will produce a null key.
- */
- DSAPublicKey toDSA() const;
+ \param fileName the name of the file containing the public key
- /**
- Convenience method to convert this key to a DHPublicKey
+ \sa fromPEMFile for an alternative method
+ */
+ PublicKey(const QString &fileName);
- Note that if the key is not an DH key (eg it is DSA or RSA),
- then this will produce a null key.
- */
- DHPublicKey toDH() const;
+ /**
+ Copy constructor
- /**
- Test if this key can be used for encryption
+ \param from the PublicKey to copy from
+ */
+ PublicKey(const PublicKey &from);
- \return true if the key can be used for encryption
- */
- bool canEncrypt() const;
+ ~PublicKey();
- /**
- Test if this key can be used for decryption
+ /**
+ Assignment operator
- \return true if the key can be used for decryption
- */
- bool canDecrypt() const;
+ \param from the PublicKey to copy from
+ */
+ PublicKey &operator=(const PublicKey &from);
- /**
- Test if the key can be used for verifying signatures
+ /**
+ Convenience method to convert this key to an RSAPublicKey
- \return true of the key can be used for verification
- */
- bool canVerify() const;
+ Note that if the key is not an RSA key (eg it is DSA or DH),
+ then this will produce a null key.
+ */
+ RSAPublicKey toRSA() const;
+
+ /**
+ Convenience method to convert this key to a DSAPublicKey
- /**
- The maximum message size that can be encrypted with a specified
- algorithm
+ Note that if the key is not an DSA key (eg it is RSA or DH),
+ then this will produce a null key.
+ */
+ DSAPublicKey toDSA() const;
- \param alg the algorithm to check
- */
- int maximumEncryptSize(EncryptionAlgorithm alg) const;
+ /**
+ Convenience method to convert this key to a DHPublicKey
- /**
- Encrypt a message using a specified algorithm
+ Note that if the key is not an DH key (eg it is DSA or RSA),
+ then this will produce a null key.
+ */
+ DHPublicKey toDH() const;
- \param a the message to encrypt
- \param alg the algorithm to use
- */
- SecureArray encrypt(const SecureArray &a, EncryptionAlgorithm alg);
+ /**
+ Test if this key can be used for encryption
- /**
- Decrypt the message
+ \return true if the key can be used for encryption
+ */
+ bool canEncrypt() const;
- \param in the cipher (encrypted) data
- \param out the plain text data
- \param alg the algorithm to use
+ /**
+ Test if this key can be used for decryption
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg);
+ \return true if the key can be used for decryption
+ */
+ bool canDecrypt() const;
- /**
- Initialise the signature verification process
+ /**
+ Test if the key can be used for verifying signatures
- \param alg the algorithm to use for signing
- \param format the specific format to use, for DSA
- */
- void startVerify(SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
+ \return true of the key can be used for verification
+ */
+ bool canVerify() const;
- /**
- Update the signature verification process with more data
+ /**
+ The maximum message size that can be encrypted with a specified
+ algorithm
- \param a the array containing the data that should be added to the signature
- */
- void update(const MemoryRegion &a);
-
- /**
- Check the signature is valid for the message
-
- The process to check that a signature is correct is shown below:
- \code
-// note that pubkey is a PublicKey
-if( pubkey.canVerify() )
-{
- pubkey.startVerify( QCA::EMSA3_MD5 );
- pubkey.update( theMessage ); // might be called multiple times
- if ( pubkey.validSignature( theSignature ) )
- {
- // then signature is valid
- }
- else
- {
- // then signature is invalid
- }
-}
- \endcode
-
- \param sig the signature to check
-
- \return true if the signature is correct
- */
- bool validSignature(const QByteArray &sig);
-
- /**
- Single step message verification
-
- If you have the whole message to be verified, then this offers a
- more convenient approach to verification.
-
- \param a the message to check the signature on
- \param sig the signature to be checked
- \param alg the algorithm to use
- \param format the signature format to use, for DSA
-
- \return true if the signature is valid for the message
- */
- bool verifyMessage(const MemoryRegion &a, const QByteArray &sig, SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
-
- /**
- Export the key in Distinguished Encoding Rules (DER) format
- */
- QByteArray toDER() const;
-
- /**
- Export the key in Privacy Enhanced Mail (PEM) format
-
- \sa toPEMFile provides a convenient way to save the PEM encoded key
- to a file
- \sa fromPEM provides an inverse of toPEM, converting the PEM
- encoded key back to a PublicKey
- */
- QString toPEM() const;
-
- /**
- Export the key in Privacy Enhanced Mail (PEM) to a file
-
- \param fileName the name (and path, if necessary) of the file to
- save the PEM encoded key to.
-
- \sa toPEM for a version that exports to a QString, which may be
- useful if you need to do more sophisticated handling
- \sa fromPEMFile provides an inverse of toPEMFile, reading a PEM
- encoded key from a file
- */
- bool toPEMFile(const QString &fileName) const;
-
- /**
- Import a key in Distinguished Encoding Rules (DER) format
-
- This function takes a binary array, which is assumed to contain a
- public key in DER encoding, and returns the key. Unless you don't
- care whether the import succeeded, you should test the result, as
- shown below.
-
- \code
-QCA::ConvertResult conversionResult;
-QCA::PublicKey publicKey = QCA::PublicKey::fromDER(keyArray, &conversionResult);
-if (! QCA::ConvertGood == conversionResult)
-{
- std::cout << "Public key read failed" << std::endl;
-}
- \endcode
-
- \param a the array containing a DER encoded key
- \param result pointer to a variable, which returns whether the
- conversion succeeded (ConvertGood) or not
- \param provider the name of the provider to use for the import.
- */
- static PublicKey fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Import a key in Privacy Enhanced Mail (PEM) format
-
- This function takes a string, which is assumed to contain a public
- key in PEM encoding, and returns that key. Unless you don't care
- whether the import succeeded, you should test the result, as shown
- below.
-
- \code
-QCA::ConvertResult conversionResult;
-QCA::PublicKey publicKey = QCA::PublicKey::fromPEM(keyAsString, &conversionResult);
-if (! QCA::ConvertGood == conversionResult)
-{
- std::cout << "Public key read failed" << std::endl;
-}
- \endcode
-
- \param s the string containing a PEM encoded key
- \param result pointer to a variable, which returns whether the
- conversion succeeded (ConvertGood) or not
- \param provider the name of the provider to use for the import.
-
- \sa toPEM, which provides an inverse of fromPEM()
- \sa fromPEMFile, which provides an import direct from a file.
- */
- static PublicKey fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
-
- /**
- Import a key in Privacy Enhanced Mail (PEM) format from a file
-
- This function takes the name of a file, which is assumed to contain
- a public key in PEM encoding, and returns that key. Unless you
- don't care whether the import succeeded, you should test the
- result, as shown below.
-
- \code
-QCA::ConvertResult conversionResult;
-QCA::PublicKey publicKey = QCA::PublicKey::fromPEMFile(fileName, &conversionResult);
-if (! QCA::ConvertGood == conversionResult)
-{
- std::cout << "Public key read failed" << std::endl;
-}
- \endcode
+ \param alg the algorithm to check
+ */
+ int maximumEncryptSize(EncryptionAlgorithm alg) const;
- \param fileName a string containing the name of the file
- \param result pointer to a variable, which returns whether the
- conversion succeeded (ConvertGood) or not
- \param provider the name of the provider to use for the import.
+ /**
+ Encrypt a message using a specified algorithm
+
+ \param a the message to encrypt
+ \param alg the algorithm to use
+ */
+ SecureArray encrypt(const SecureArray &a, EncryptionAlgorithm alg);
- \sa toPEMFile, which provides an inverse of fromPEMFile()
- \sa fromPEM, which provides an import from a string
+ /**
+ Decrypt the message
+
+ \param in the cipher (encrypted) data
+ \param out the plain text data
+ \param alg the algorithm to use
- \note there is also a constructor form that can import from a file
- */
- static PublicKey fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg);
+
+ /**
+ Initialise the signature verification process
+
+ \param alg the algorithm to use for signing
+ \param format the specific format to use, for DSA
+ */
+ void startVerify(SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
+
+ /**
+ Update the signature verification process with more data
+
+ \param a the array containing the data that should be added to the signature
+ */
+ void update(const MemoryRegion &a);
+
+ /**
+ Check the signature is valid for the message
+
+ The process to check that a signature is correct is shown below:
+ \code
+ // note that pubkey is a PublicKey
+ if( pubkey.canVerify() )
+ {
+ pubkey.startVerify( QCA::EMSA3_MD5 );
+ pubkey.update( theMessage ); // might be called multiple times
+ if ( pubkey.validSignature( theSignature ) )
+ {
+ // then signature is valid
+ }
+ else
+ {
+ // then signature is invalid
+ }
+ }
+ \endcode
+
+ \param sig the signature to check
+
+ \return true if the signature is correct
+ */
+ bool validSignature(const QByteArray &sig);
+
+ /**
+ Single step message verification
+
+ If you have the whole message to be verified, then this offers a
+ more convenient approach to verification.
+
+ \param a the message to check the signature on
+ \param sig the signature to be checked
+ \param alg the algorithm to use
+ \param format the signature format to use, for DSA
+
+ \return true if the signature is valid for the message
+ */
+ bool verifyMessage(const MemoryRegion &a, const QByteArray &sig, SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
+
+ /**
+ Export the key in Distinguished Encoding Rules (DER) format
+ */
+ QByteArray toDER() const;
+
+ /**
+ Export the key in Privacy Enhanced Mail (PEM) format
+
+ \sa toPEMFile provides a convenient way to save the PEM encoded key
+ to a file
+ \sa fromPEM provides an inverse of toPEM, converting the PEM
+ encoded key back to a PublicKey
+ */
+ QString toPEM() const;
+
+ /**
+ Export the key in Privacy Enhanced Mail (PEM) to a file
+
+ \param fileName the name (and path, if necessary) of the file to
+ save the PEM encoded key to.
+
+ \sa toPEM for a version that exports to a QString, which may be
+ useful if you need to do more sophisticated handling
+ \sa fromPEMFile provides an inverse of toPEMFile, reading a PEM
+ encoded key from a file
+ */
+ bool toPEMFile(const QString &fileName) const;
+
+ /**
+ Import a key in Distinguished Encoding Rules (DER) format
+
+ This function takes a binary array, which is assumed to contain a
+ public key in DER encoding, and returns the key. Unless you don't
+ care whether the import succeeded, you should test the result, as
+ shown below.
+
+ \code
+ QCA::ConvertResult conversionResult;
+ QCA::PublicKey publicKey = QCA::PublicKey::fromDER(keyArray, &conversionResult);
+ if (! QCA::ConvertGood == conversionResult)
+ {
+ std::cout << "Public key read failed" << std::endl;
+ }
+ \endcode
+
+ \param a the array containing a DER encoded key
+ \param result pointer to a variable, which returns whether the
+ conversion succeeded (ConvertGood) or not
+ \param provider the name of the provider to use for the import.
+ */
+ static PublicKey fromDER(const QByteArray &a, ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Import a key in Privacy Enhanced Mail (PEM) format
+
+ This function takes a string, which is assumed to contain a public
+ key in PEM encoding, and returns that key. Unless you don't care
+ whether the import succeeded, you should test the result, as shown
+ below.
+
+ \code
+ QCA::ConvertResult conversionResult;
+ QCA::PublicKey publicKey = QCA::PublicKey::fromPEM(keyAsString, &conversionResult);
+ if (! QCA::ConvertGood == conversionResult)
+ {
+ std::cout << "Public key read failed" << std::endl;
+ }
+ \endcode
+
+ \param s the string containing a PEM encoded key
+ \param result pointer to a variable, which returns whether the
+ conversion succeeded (ConvertGood) or not
+ \param provider the name of the provider to use for the import.
+
+ \sa toPEM, which provides an inverse of fromPEM()
+ \sa fromPEMFile, which provides an import direct from a file.
+ */
+ static PublicKey fromPEM(const QString &s, ConvertResult *result = 0, const QString &provider = QString());
+
+ /**
+ Import a key in Privacy Enhanced Mail (PEM) format from a file
+
+ This function takes the name of a file, which is assumed to contain
+ a public key in PEM encoding, and returns that key. Unless you
+ don't care whether the import succeeded, you should test the
+ result, as shown below.
+
+ \code
+ QCA::ConvertResult conversionResult;
+ QCA::PublicKey publicKey = QCA::PublicKey::fromPEMFile(fileName, &conversionResult);
+ if (! QCA::ConvertGood == conversionResult)
+ {
+ std::cout << "Public key read failed" << std::endl;
+ }
+ \endcode
+
+ \param fileName a string containing the name of the file
+ \param result pointer to a variable, which returns whether the
+ conversion succeeded (ConvertGood) or not
+ \param provider the name of the provider to use for the import.
+
+ \sa toPEMFile, which provides an inverse of fromPEMFile()
+ \sa fromPEM, which provides an import from a string
+
+ \note there is also a constructor form that can import from a file
+ */
+ static PublicKey fromPEMFile(const QString &fileName, ConvertResult *result = 0, const QString &provider = QString());
protected:
- /**
- Create a new key of a specified type
+ /**
+ Create a new key of a specified type
- \param type the type of key to create
- \param provider the provider to use, if required
- */
- PublicKey(const QString &type, const QString &provider);
+ \param type the type of key to create
+ \param provider the provider to use, if required
+ */
+ PublicKey(const QString &type, const QString &provider);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class PrivateKey qca_publickey.h QtCrypto
Generic private key
\ingroup UserAPI
*/
class QCA_EXPORT PrivateKey : public PKey
{
public:
- /**
- Create an empty private key
- */
- PrivateKey();
+ /**
+ Create an empty private key
+ */
+ PrivateKey();
- /**
- Import a private key from a PEM representation in a file
+ /**
+ Import a private key from a PEM representation in a file
- \param fileName the name of the file containing the private key
- \param passphrase the pass phrase for the private key
+ \param fileName the name of the file containing the private key
+ \param passphrase the pass phrase for the private key
- \sa fromPEMFile for an alternative method
+ \sa fromPEMFile for an alternative method
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- explicit PrivateKey(const QString &fileName, const SecureArray &passphrase = SecureArray());
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ explicit PrivateKey(const QString &fileName, const SecureArray &passphrase = SecureArray());
- /**
- Copy constructor
+ /**
+ Copy constructor
- \param from the PrivateKey to copy from
- */
- PrivateKey(const PrivateKey &from);
+ \param from the PrivateKey to copy from
+ */
+ PrivateKey(const PrivateKey &from);
- ~PrivateKey();
+ ~PrivateKey();
- /**
- Assignment operator
+ /**
+ Assignment operator
- \param from the PrivateKey to copy from
- */
- PrivateKey & operator=(const PrivateKey &from);
+ \param from the PrivateKey to copy from
+ */
+ PrivateKey &operator=(const PrivateKey &from);
- /**
- Interpret / convert the key to an RSA key
- */
- RSAPrivateKey toRSA() const;
+ /**
+ Interpret / convert the key to an RSA key
+ */
+ RSAPrivateKey toRSA() const;
- /**
- Interpret / convert the key to a DSA key
- */
- DSAPrivateKey toDSA() const;
+ /**
+ Interpret / convert the key to a DSA key
+ */
+ DSAPrivateKey toDSA() const;
- /**
- Interpret / convert the key to a Diffie-Hellman key
- */
- DHPrivateKey toDH() const;
+ /**
+ Interpret / convert the key to a Diffie-Hellman key
+ */
+ DHPrivateKey toDH() const;
- /**
- Test if this key can be used for decryption
+ /**
+ Test if this key can be used for decryption
- \return true if the key can be used for decryption
- */
- bool canDecrypt() const;
+ \return true if the key can be used for decryption
+ */
+ bool canDecrypt() const;
- /**
- Test if this key can be used for encryption
+ /**
+ Test if this key can be used for encryption
- \return true if the key can be used for encryption
- */
- bool canEncrypt() const;
+ \return true if the key can be used for encryption
+ */
+ bool canEncrypt() const;
- /**
- Test if this key can be used for signing
+ /**
+ Test if this key can be used for signing
- \return true if the key can be used to make a signature
- */
- bool canSign() const;
+ \return true if the key can be used to make a signature
+ */
+ bool canSign() const;
- /**
- The maximum message size that can be encrypted with a specified
- algorithm
+ /**
+ The maximum message size that can be encrypted with a specified
+ algorithm
- \param alg the algorithm to check
- */
- int maximumEncryptSize(EncryptionAlgorithm alg) const;
+ \param alg the algorithm to check
+ */
+ int maximumEncryptSize(EncryptionAlgorithm alg) const;
- /**
- Decrypt the message
+ /**
+ Decrypt the message
- \param in the cipher (encrypted) data
- \param out the plain text data
- \param alg the algorithm to use
+ \param in the cipher (encrypted) data
+ \param out the plain text data
+ \param alg the algorithm to use
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg);
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg);
- /**
- Encrypt a message using a specified algorithm
+ /**
+ Encrypt a message using a specified algorithm
- \param a the message to encrypt
- \param alg the algorithm to use
- */
- SecureArray encrypt(const SecureArray &a, EncryptionAlgorithm alg);
+ \param a the message to encrypt
+ \param alg the algorithm to use
+ */
+ SecureArray encrypt(const SecureArray &a, EncryptionAlgorithm alg);
- /**
- Initialise the message signature process
+ /**
+ Initialise the message signature process
- \param alg the algorithm to use for the message signature process
- \param format the signature format to use, for DSA
+ \param alg the algorithm to use for the message signature process
+ \param format the signature format to use, for DSA
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- void startSign(SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ void startSign(SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
- /**
- Update the signature process
+ /**
+ Update the signature process
- \param a the message to use to update the signature
+ \param a the message to use to update the signature
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- void update(const MemoryRegion &a);
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ void update(const MemoryRegion &a);
- /**
- The resulting signature
+ /**
+ The resulting signature
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- QByteArray signature();
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ QByteArray signature();
- /**
- One step signature process
+ /**
+ One step signature process
- \param a the message to sign
- \param alg the algorithm to use for the signature
- \param format the signature format to use, for DSA
+ \param a the message to sign
+ \param alg the algorithm to use for the signature
+ \param format the signature format to use, for DSA
- \return the signature
+ \return the signature
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- QByteArray signMessage(const MemoryRegion &a, SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ QByteArray signMessage(const MemoryRegion &a, SignatureAlgorithm alg, SignatureFormat format = DefaultFormat);
- /**
- Derive a shared secret key from a public key
+ /**
+ Derive a shared secret key from a public key
- \param theirs the public key to derive from
- */
- SymmetricKey deriveKey(const PublicKey &theirs);
+ \param theirs the public key to derive from
+ */
+ SymmetricKey deriveKey(const PublicKey &theirs);
- /**
- List the supported Password Based Encryption Algorithms that can be
- used to protect the key.
+ /**
+ List the supported Password Based Encryption Algorithms that can be
+ used to protect the key.
- \param provider the provider to use, if a particular provider is
- required
- */
- static QList<PBEAlgorithm> supportedPBEAlgorithms(const QString &provider = QString());
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ static QList<PBEAlgorithm> supportedPBEAlgorithms(const QString &provider = QString());
- /**
- Export the key in Distinguished Encoding Rules (DER) format
+ /**
+ Export the key in Distinguished Encoding Rules (DER) format
- \param passphrase the pass phrase to use to protect the key
- \param pbe the symmetric encryption algorithm to use to protect the
- key
+ \param passphrase the pass phrase to use to protect the key
+ \param pbe the symmetric encryption algorithm to use to protect the
+ key
- \sa fromDER provides an inverse of toDER, converting the DER
- encoded key back to a PrivateKey
- */
- SecureArray toDER(const SecureArray &passphrase = SecureArray(), PBEAlgorithm pbe = PBEDefault) const;
+ \sa fromDER provides an inverse of toDER, converting the DER
+ encoded key back to a PrivateKey
+ */
+ SecureArray toDER(const SecureArray &passphrase = SecureArray(), PBEAlgorithm pbe = PBEDefault) const;
- /**
- Export the key in Privacy Enhanced Mail (PEM) format
+ /**
+ Export the key in Privacy Enhanced Mail (PEM) format
- \param passphrase the pass phrase to use to protect the key
- \param pbe the symmetric encryption algorithm to use to protect the
- key
+ \param passphrase the pass phrase to use to protect the key
+ \param pbe the symmetric encryption algorithm to use to protect the
+ key
- \sa toPEMFile provides a convenient way to save the PEM encoded key
- to a file
- \sa fromPEM provides an inverse of toPEM, converting the PEM
- encoded key back to a PrivateKey
- */
- QString toPEM(const SecureArray &passphrase = SecureArray(), PBEAlgorithm pbe = PBEDefault) const;
+ \sa toPEMFile provides a convenient way to save the PEM encoded key
+ to a file
+ \sa fromPEM provides an inverse of toPEM, converting the PEM
+ encoded key back to a PrivateKey
+ */
+ QString toPEM(const SecureArray &passphrase = SecureArray(), PBEAlgorithm pbe = PBEDefault) const;
- /**
- Export the key in Privacy Enhanced Mail (PEM) format to a file
+ /**
+ Export the key in Privacy Enhanced Mail (PEM) format to a file
- \param fileName the name (and path, if required) that the key
- should be exported to.
- \param passphrase the pass phrase to use to protect the key
- \param pbe the symmetric encryption algorithm to use to protect the
- key
+ \param fileName the name (and path, if required) that the key
+ should be exported to.
+ \param passphrase the pass phrase to use to protect the key
+ \param pbe the symmetric encryption algorithm to use to protect the
+ key
- \return true if the export succeeds
+ \return true if the export succeeds
- \sa toPEM provides a convenient way to save the PEM encoded key to
- a file
- \sa fromPEM provides an inverse of toPEM, converting the PEM
- encoded key back to a PrivateKey
- */
- bool toPEMFile(const QString &fileName, const SecureArray &passphrase = SecureArray(), PBEAlgorithm pbe = PBEDefault) const;
+ \sa toPEM provides a convenient way to save the PEM encoded key to
+ a file
+ \sa fromPEM provides an inverse of toPEM, converting the PEM
+ encoded key back to a PrivateKey
+ */
+ bool toPEMFile(const QString &fileName, const SecureArray &passphrase = SecureArray(), PBEAlgorithm pbe = PBEDefault) const;
- /**
- Import the key from Distinguished Encoding Rules (DER) format
+ /**
+ Import the key from Distinguished Encoding Rules (DER) format
- \param a the array containing the DER representation of the key
- \param passphrase the pass phrase that is used to protect the key
- \param result a pointer to a ConvertResult, that if specified, will
- be set to reflect the result of the import
- \param provider the provider to use, if a particular provider is
- required
+ \param a the array containing the DER representation of the key
+ \param passphrase the pass phrase that is used to protect the key
+ \param result a pointer to a ConvertResult, that if specified, will
+ be set to reflect the result of the import
+ \param provider the provider to use, if a particular provider is
+ required
- \sa toDER provides an inverse of fromDER, exporting the key to an
- array
+ \sa toDER provides an inverse of fromDER, exporting the key to an
+ array
- \sa QCA::KeyLoader for an asynchronous loader approach.
+ \sa QCA::KeyLoader for an asynchronous loader approach.
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- static PrivateKey fromDER(const SecureArray &a, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ static PrivateKey fromDER(const SecureArray &a, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
- /**
- Import the key from Privacy Enhanced Mail (PEM) format
+ /**
+ Import the key from Privacy Enhanced Mail (PEM) format
- \param s the string containing the PEM representation of the key
- \param passphrase the pass phrase that is used to protect the key
- \param result a pointer to a ConvertResult, that if specified, will
- be set to reflect the result of the import
- \param provider the provider to use, if a particular provider is
- required
+ \param s the string containing the PEM representation of the key
+ \param passphrase the pass phrase that is used to protect the key
+ \param result a pointer to a ConvertResult, that if specified, will
+ be set to reflect the result of the import
+ \param provider the provider to use, if a particular provider is
+ required
- \sa toPEM provides an inverse of fromPEM, exporting the key to a
- string in PEM encoding.
+ \sa toPEM provides an inverse of fromPEM, exporting the key to a
+ string in PEM encoding.
- \sa QCA::KeyLoader for an asynchronous loader approach.
+ \sa QCA::KeyLoader for an asynchronous loader approach.
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- static PrivateKey fromPEM(const QString &s, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ static PrivateKey fromPEM(const QString &s, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
- /**
- Import the key in Privacy Enhanced Mail (PEM) format from a file
+ /**
+ Import the key in Privacy Enhanced Mail (PEM) format from a file
- \param fileName the name (and path, if required) of the file
- containing the PEM representation of the key
- \param passphrase the pass phrase that is used to protect the key
- \param result a pointer to a ConvertResult, that if specified, will
- be set to reflect the result of the import
- \param provider the provider to use, if a particular provider is
- required
+ \param fileName the name (and path, if required) of the file
+ containing the PEM representation of the key
+ \param passphrase the pass phrase that is used to protect the key
+ \param result a pointer to a ConvertResult, that if specified, will
+ be set to reflect the result of the import
+ \param provider the provider to use, if a particular provider is
+ required
- \sa toPEMFile provides an inverse of fromPEMFile
- \sa fromPEM which allows import from a string
+ \sa toPEMFile provides an inverse of fromPEMFile
+ \sa fromPEM which allows import from a string
- \sa QCA::KeyLoader for an asynchronous loader approach.
+ \sa QCA::KeyLoader for an asynchronous loader approach.
- \note there is also a constructor form, that allows you to create
- the key directly
+ \note there is also a constructor form, that allows you to create
+ the key directly
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- static PrivateKey fromPEMFile(const QString &fileName, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ static PrivateKey fromPEMFile(const QString &fileName, const SecureArray &passphrase = SecureArray(), ConvertResult *result = 0, const QString &provider = QString());
protected:
- /**
- Create a new private key
+ /**
+ Create a new private key
- \param type the type of key to create
- \param provider the provider to use, if a specific provider is
- required.
- */
- PrivateKey(const QString &type, const QString &provider);
+ \param type the type of key to create
+ \param provider the provider to use, if a specific provider is
+ required.
+ */
+ PrivateKey(const QString &type, const QString &provider);
private:
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class KeyGenerator qca_publickey.h QtCrypto
Class for generating asymmetric key pairs
This class is used for generating asymmetric keys (public/private key
pairs).
\ingroup UserAPI
*/
class QCA_EXPORT KeyGenerator : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Create a new key generator
+ /**
+ Create a new key generator
- \param parent the parent object, if applicable
- */
- KeyGenerator(QObject *parent = 0);
+ \param parent the parent object, if applicable
+ */
+ KeyGenerator(QObject *parent = 0);
- ~KeyGenerator();
-
- /**
- Test whether the key generator is set to operate in blocking mode,
- or not
+ ~KeyGenerator();
+
+ /**
+ Test whether the key generator is set to operate in blocking mode,
+ or not
- \return true if the key generator is in blocking mode
+ \return true if the key generator is in blocking mode
- \sa setBlockingEnabled
- */
- bool blockingEnabled() const;
+ \sa setBlockingEnabled
+ */
+ bool blockingEnabled() const;
- /**
- Set whether the key generator is in blocking mode, nor not
+ /**
+ Set whether the key generator is in blocking mode, nor not
- \param b if true, the key generator will be set to operate in
- blocking mode, otherwise it will operate in non-blocking mode
+ \param b if true, the key generator will be set to operate in
+ blocking mode, otherwise it will operate in non-blocking mode
- \sa blockingEnabled()
- */
- void setBlockingEnabled(bool b);
+ \sa blockingEnabled()
+ */
+ void setBlockingEnabled(bool b);
- /**
- Test if the key generator is currently busy, or not
+ /**
+ Test if the key generator is currently busy, or not
- \return true if the key generator is busy generating a key already
- */
- bool isBusy() const;
+ \return true if the key generator is busy generating a key already
+ */
+ bool isBusy() const;
- /**
- Generate an RSA key of the specified length
+ /**
+ Generate an RSA key of the specified length
- This method creates both the public key and corresponding private
- key. You almost certainly want to extract the public key part out -
- see PKey::toPublicKey for an easy way.
+ This method creates both the public key and corresponding private
+ key. You almost certainly want to extract the public key part out -
+ see PKey::toPublicKey for an easy way.
- Key length is a tricky judgment - using less than 2048 is probably
- being too liberal for long term use. Don't use less than 1024
- without serious analysis.
+ Key length is a tricky judgment - using less than 2048 is probably
+ being too liberal for long term use. Don't use less than 1024
+ without serious analysis.
- \param bits the length of key that is required
- \param exp the exponent - typically 3, 17 or 65537
- \param provider the name of the provider to use, if a particular
- provider is required
- */
- PrivateKey createRSA(int bits, int exp = 65537, const QString &provider = QString());
+ \param bits the length of key that is required
+ \param exp the exponent - typically 3, 17 or 65537
+ \param provider the name of the provider to use, if a particular
+ provider is required
+ */
+ PrivateKey createRSA(int bits, int exp = 65537, const QString &provider = QString());
- /**
- Generate a DSA key
+ /**
+ Generate a DSA key
- This method creates both the public key and corresponding private
- key. You almost certainly want to extract the public key part out -
- see PKey::toPublicKey for an easy way.
+ This method creates both the public key and corresponding private
+ key. You almost certainly want to extract the public key part out -
+ see PKey::toPublicKey for an easy way.
- \param domain the discrete logarithm group that this key should be
- generated from
- \param provider the name of the provider to use, if a particular
- provider is required
+ \param domain the discrete logarithm group that this key should be
+ generated from
+ \param provider the name of the provider to use, if a particular
+ provider is required
- \note Not every DLGroup makes sense for DSA. You should use one of
- DSA_512, DSA_768 and DSA_1024.
- */
- PrivateKey createDSA(const DLGroup &domain, const QString &provider = QString());
+ \note Not every DLGroup makes sense for DSA. You should use one of
+ DSA_512, DSA_768 and DSA_1024.
+ */
+ PrivateKey createDSA(const DLGroup &domain, const QString &provider = QString());
- /**
- Generate a Diffie-Hellman key
+ /**
+ Generate a Diffie-Hellman key
- This method creates both the public key and corresponding private
- key. You almost certainly want to extract the public key part out -
- see PKey::toPublicKey for an easy way.
+ This method creates both the public key and corresponding private
+ key. You almost certainly want to extract the public key part out -
+ see PKey::toPublicKey for an easy way.
- \param domain the discrete logarithm group that this key should be
- generated from
- \param provider the name of the provider to use, if a particular
- provider is required
- \note For compatibility, you should use one of the IETF_ groupsets
- as the domain argument.
- */
- PrivateKey createDH(const DLGroup &domain, const QString &provider = QString());
+ \param domain the discrete logarithm group that this key should be
+ generated from
+ \param provider the name of the provider to use, if a particular
+ provider is required
+ \note For compatibility, you should use one of the IETF_ groupsets
+ as the domain argument.
+ */
+ PrivateKey createDH(const DLGroup &domain, const QString &provider = QString());
- /**
- Return the last generated key
+ /**
+ Return the last generated key
- This is really only useful when you are working with non-blocking
- key generation
- */
- PrivateKey key() const;
+ This is really only useful when you are working with non-blocking
+ key generation
+ */
+ PrivateKey key() const;
- /**
- Create a new discrete logarithm group
+ /**
+ Create a new discrete logarithm group
- \param set the set of discrete logarithm parameters to generate
- from
- \param provider the name of the provider to use, if a particular
- provider is required.
- */
- DLGroup createDLGroup(QCA::DLGroupSet set, const QString &provider = QString());
+ \param set the set of discrete logarithm parameters to generate
+ from
+ \param provider the name of the provider to use, if a particular
+ provider is required.
+ */
+ DLGroup createDLGroup(QCA::DLGroupSet set, const QString &provider = QString());
- /**
- The current discrete logarithm group
- */
- DLGroup dlGroup() const;
+ /**
+ The current discrete logarithm group
+ */
+ DLGroup dlGroup() const;
Q_SIGNALS:
- /**
- Emitted when the key generation is complete.
+ /**
+ Emitted when the key generation is complete.
- This is only used in non-blocking mode
- */
- void finished();
+ This is only used in non-blocking mode
+ */
+ void finished();
private:
- Q_DISABLE_COPY(KeyGenerator)
+ Q_DISABLE_COPY(KeyGenerator)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class RSAPublicKey qca_publickey.h QtCrypto
RSA Public Key
\ingroup UserAPI
*/
class QCA_EXPORT RSAPublicKey : public PublicKey
{
public:
- /**
- Generate an empty RSA public key
- */
- RSAPublicKey();
-
- /**
- Generate an RSA public key from specified parameters
-
- \param n the public key value
- \param e the public key exponent
- \param provider the provider to use, if a particular provider is
- required
- */
- RSAPublicKey(const BigInteger &n, const BigInteger &e, const QString &provider = QString());
-
- /**
- Extract the public key components from an RSA private key
-
- \param k the private key to use as the basis for the public key
- */
- RSAPublicKey(const RSAPrivateKey &k);
-
- /**
- The public key value
-
- This value is the actual public key value (the product of p and q,
- the random prime numbers used to generate the RSA key), also known
- as the public modulus.
- */
- BigInteger n() const;
-
- /**
- The public key exponent
-
- This value is the exponent chosen in the original key generator
- step
- */
- BigInteger e() const;
+ /**
+ Generate an empty RSA public key
+ */
+ RSAPublicKey();
+
+ /**
+ Generate an RSA public key from specified parameters
+
+ \param n the public key value
+ \param e the public key exponent
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ RSAPublicKey(const BigInteger &n, const BigInteger &e, const QString &provider = QString());
+
+ /**
+ Extract the public key components from an RSA private key
+
+ \param k the private key to use as the basis for the public key
+ */
+ RSAPublicKey(const RSAPrivateKey &k);
+
+ /**
+ The public key value
+
+ This value is the actual public key value (the product of p and q,
+ the random prime numbers used to generate the RSA key), also known
+ as the public modulus.
+ */
+ BigInteger n() const;
+
+ /**
+ The public key exponent
+
+ This value is the exponent chosen in the original key generator
+ step
+ */
+ BigInteger e() const;
};
/**
\class RSAPrivateKey qca_publickey.h QtCrypto
RSA Private Key
\ingroup UserAPI
*/
class QCA_EXPORT RSAPrivateKey : public PrivateKey
{
public:
- /**
- Generate an empty RSA private key
- */
- RSAPrivateKey();
-
- /**
- Generate an RSA private key from specified parameters
-
- \param n the public key value
- \param e the public key exponent
- \param p one of the two chosen primes
- \param q the other of the two chosen primes
- \param d inverse of the exponent, modulo (p-1)(q-1)
- \param provider the provider to use, if a particular provider is
- required
- */
- RSAPrivateKey(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d, const QString &provider = QString());
-
- /**
- The public key value
-
- This value is the actual public key value (the product of p and q,
- the random prime numbers used to generate the RSA key), also known
- as the public modulus.
- */
- BigInteger n() const;
-
- /**
- The public key exponent
-
- This value is the exponent chosen in the original key generator
- step
- */
- BigInteger e() const;
-
- /**
- One of the two random primes used to generate the private key
- */
- BigInteger p() const;
-
- /**
- The second of the two random primes used to generate the private
- key
- */
- BigInteger q() const;
-
- /**
- The inverse of the exponent, module (p-1)(q-1)
- */
- BigInteger d() const;
+ /**
+ Generate an empty RSA private key
+ */
+ RSAPrivateKey();
+
+ /**
+ Generate an RSA private key from specified parameters
+
+ \param n the public key value
+ \param e the public key exponent
+ \param p one of the two chosen primes
+ \param q the other of the two chosen primes
+ \param d inverse of the exponent, modulo (p-1)(q-1)
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ RSAPrivateKey(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d, const QString &provider = QString());
+
+ /**
+ The public key value
+
+ This value is the actual public key value (the product of p and q,
+ the random prime numbers used to generate the RSA key), also known
+ as the public modulus.
+ */
+ BigInteger n() const;
+
+ /**
+ The public key exponent
+
+ This value is the exponent chosen in the original key generator
+ step
+ */
+ BigInteger e() const;
+
+ /**
+ One of the two random primes used to generate the private key
+ */
+ BigInteger p() const;
+
+ /**
+ The second of the two random primes used to generate the private
+ key
+ */
+ BigInteger q() const;
+
+ /**
+ The inverse of the exponent, module (p-1)(q-1)
+ */
+ BigInteger d() const;
};
/**
\class DSAPublicKey qca_publickey.h QtCrypto
Digital Signature %Algorithm Public Key
\ingroup UserAPI
*/
class QCA_EXPORT DSAPublicKey : public PublicKey
{
public:
- /**
- Create an empty DSA public key
- */
- DSAPublicKey();
-
- /**
- Create a DSA public key
-
- \param domain the discrete logarithm group to use
- \param y the public random value
- \param provider the provider to use, if a specific provider is
- required
- */
- DSAPublicKey(const DLGroup &domain, const BigInteger &y, const QString &provider = QString());
-
- /**
- Create a DSA public key from a specified private key
-
- \param k the DSA private key to use as the source
- */
- DSAPublicKey(const DSAPrivateKey &k);
-
- /**
- The discrete logarithm group that is being used
- */
- DLGroup domain() const;
-
- /**
- The public random value associated with this key
- */
- BigInteger y() const;
+ /**
+ Create an empty DSA public key
+ */
+ DSAPublicKey();
+
+ /**
+ Create a DSA public key
+
+ \param domain the discrete logarithm group to use
+ \param y the public random value
+ \param provider the provider to use, if a specific provider is
+ required
+ */
+ DSAPublicKey(const DLGroup &domain, const BigInteger &y, const QString &provider = QString());
+
+ /**
+ Create a DSA public key from a specified private key
+
+ \param k the DSA private key to use as the source
+ */
+ DSAPublicKey(const DSAPrivateKey &k);
+
+ /**
+ The discrete logarithm group that is being used
+ */
+ DLGroup domain() const;
+
+ /**
+ The public random value associated with this key
+ */
+ BigInteger y() const;
};
/**
\class DSAPrivateKey qca_publickey.h QtCrypto
Digital Signature %Algorithm Private Key
\ingroup UserAPI
*/
class QCA_EXPORT DSAPrivateKey : public PrivateKey
{
public:
- /**
- Create an empty DSA private key
- */
- DSAPrivateKey();
-
- /**
- Create a DSA public key
-
- \param domain the discrete logarithm group to use
- \param y the public random value
- \param x the private random value
- \param provider the provider to use, if a specific provider is
- required
- */
- DSAPrivateKey(const DLGroup &domain, const BigInteger &y, const BigInteger &x, const QString &provider = QString());
-
- /**
- The discrete logarithm group that is being used
- */
- DLGroup domain() const;
-
- /**
- the public random value
- */
- BigInteger y() const;
-
- /**
- the private random value
- */
- BigInteger x() const;
+ /**
+ Create an empty DSA private key
+ */
+ DSAPrivateKey();
+
+ /**
+ Create a DSA public key
+
+ \param domain the discrete logarithm group to use
+ \param y the public random value
+ \param x the private random value
+ \param provider the provider to use, if a specific provider is
+ required
+ */
+ DSAPrivateKey(const DLGroup &domain, const BigInteger &y, const BigInteger &x, const QString &provider = QString());
+
+ /**
+ The discrete logarithm group that is being used
+ */
+ DLGroup domain() const;
+
+ /**
+ the public random value
+ */
+ BigInteger y() const;
+
+ /**
+ the private random value
+ */
+ BigInteger x() const;
};
/**
\class DHPublicKey qca_publickey.h QtCrypto
Diffie-Hellman Public Key
\ingroup UserAPI
*/
class QCA_EXPORT DHPublicKey : public PublicKey
{
public:
- /**
- Create an empty Diffie-Hellman public key
- */
- DHPublicKey();
-
- /**
- Create a Diffie-Hellman public key
-
- \param domain the discrete logarithm group to use
- \param y the public random value
- \param provider the provider to use, if a specific provider is
- required
- */
- DHPublicKey(const DLGroup &domain, const BigInteger &y, const QString &provider = QString());
-
- /**
- Create a Diffie-Hellman public key from a specified private key
-
- \param k the Diffie-Hellman private key to use as the source
- */
- DHPublicKey(const DHPrivateKey &k);
-
- /**
- The discrete logarithm group that is being used
- */
- DLGroup domain() const;
-
- /**
- The public random value associated with this key
- */
- BigInteger y() const;
+ /**
+ Create an empty Diffie-Hellman public key
+ */
+ DHPublicKey();
+
+ /**
+ Create a Diffie-Hellman public key
+
+ \param domain the discrete logarithm group to use
+ \param y the public random value
+ \param provider the provider to use, if a specific provider is
+ required
+ */
+ DHPublicKey(const DLGroup &domain, const BigInteger &y, const QString &provider = QString());
+
+ /**
+ Create a Diffie-Hellman public key from a specified private key
+
+ \param k the Diffie-Hellman private key to use as the source
+ */
+ DHPublicKey(const DHPrivateKey &k);
+
+ /**
+ The discrete logarithm group that is being used
+ */
+ DLGroup domain() const;
+
+ /**
+ The public random value associated with this key
+ */
+ BigInteger y() const;
};
/**
\class DHPrivateKey qca_publickey.h QtCrypto
Diffie-Hellman Private Key
\ingroup UserAPI
*/
class QCA_EXPORT DHPrivateKey : public PrivateKey
{
public:
- /**
- Create an empty Diffie-Hellman private key
- */
- DHPrivateKey();
-
- /**
- Create a Diffie-Hellman private key
-
- \param domain the discrete logarithm group to use
- \param y the public random value
- \param x the private random value
- \param provider the provider to use, if a particular provider is
- required
- */
- DHPrivateKey(const DLGroup &domain, const BigInteger &y, const BigInteger &x, const QString &provider = QString());
-
- /**
- The discrete logarithm group that is being used
- */
- DLGroup domain() const;
-
- /**
- The public random value associated with this key
- */
- BigInteger y() const;
-
- /**
- The private random value associated with this key
- */
- BigInteger x() const;
+ /**
+ Create an empty Diffie-Hellman private key
+ */
+ DHPrivateKey();
+
+ /**
+ Create a Diffie-Hellman private key
+
+ \param domain the discrete logarithm group to use
+ \param y the public random value
+ \param x the private random value
+ \param provider the provider to use, if a particular provider is
+ required
+ */
+ DHPrivateKey(const DLGroup &domain, const BigInteger &y, const BigInteger &x, const QString &provider = QString());
+
+ /**
+ The discrete logarithm group that is being used
+ */
+ DLGroup domain() const;
+
+ /**
+ The public random value associated with this key
+ */
+ BigInteger y() const;
+
+ /**
+ The private random value associated with this key
+ */
+ BigInteger x() const;
};
/*@}*/
}
#endif
diff --git a/include/QtCrypto/qca_safetimer.h b/include/QtCrypto/qca_safetimer.h
index 2de0d433..4054da16 100644
--- a/include/QtCrypto/qca_safetimer.h
+++ b/include/QtCrypto/qca_safetimer.h
@@ -1,70 +1,71 @@
/*
* qca_safetimer.h - Qt Cryptographic Architecture
* Copyright (C) 2014 Ivan Romanov <drizt@land.ru>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#ifndef QCA_SAFETIMER_H
#define QCA_SAFETIMER_H
#include "qca_export.h"
#include <QObject>
class QEvent;
class QTimerEvent;
-namespace QCA {
+namespace QCA
+{
class QCA_EXPORT SafeTimer : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SafeTimer(QObject *parent = 0);
- ~SafeTimer();
+ SafeTimer(QObject *parent = 0);
+ ~SafeTimer();
- int interval() const;
- bool isActive() const;
- bool isSingleShot() const;
- void setInterval(int msec);
- void setSingleShot(bool singleShot);
- int timerId() const;
+ int interval() const;
+ bool isActive() const;
+ bool isSingleShot() const;
+ void setInterval(int msec);
+ void setSingleShot(bool singleShot);
+ int timerId() const;
public Q_SLOTS:
- void start(int msec);
- void start();
- void stop();
+ void start(int msec);
+ void start();
+ void stop();
Q_SIGNALS:
- void timeout();
+ void timeout();
protected:
- bool event(QEvent *event);
- void timerEvent(QTimerEvent *event);
+ bool event(QEvent *event);
+ void timerEvent(QTimerEvent *event);
private:
- // Functions is used internally. Outer world mustn't have access them.
- void startTimer() {}
- void killTimer(int) {}
+ // Functions is used internally. Outer world mustn't have access them.
+ void startTimer() {}
+ void killTimer(int) {}
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
}
#endif // QCA_SAFETIMER_H
diff --git a/include/QtCrypto/qca_securelayer.h b/include/QtCrypto/qca_securelayer.h
index deb01c0b..0f07b3a5 100644
--- a/include/QtCrypto/qca_securelayer.h
+++ b/include/QtCrypto/qca_securelayer.h
@@ -1,1256 +1,1247 @@
/*
* qca_securelayer.h - Qt Cryptographic Architecture
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_securelayer.h
Header file for SecureLayer and its subclasses
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_SECURELAYER_H
#define QCA_SECURELAYER_H
#include <QObject>
#include "qca_core.h"
#include "qca_publickey.h"
#include "qca_cert.h"
-namespace QCA {
+namespace QCA
+{
/**
Specify the lower-bound for acceptable TLS/SASL security layers
For TLS, the interpretation of these levels is:
- Any cipher suite that provides non-authenticated communications
- (usually anonymous Diffie-Hellman) is SL_Integrity.
+ (usually anonymous Diffie-Hellman) is SL_Integrity.
- Any cipher suite that is limited to 40 bits (export-version
crippled forms of RC2, RC4 or DES) is SL_Export. Standard
DES (56 bits) and some forms of RC4 (64 bits) are also SL_Export.
- Any normal cipher (AES, Camellia, RC4 or similar) with 128 bits, or
Elliptic Curve Ciphers with 283 bits, is SL_Baseline
- AES or Camellia at least 192 bits, triple-DES and similar
- ciphers are SL_High. ECC with 409 or more bits is also SL_High.
+ ciphers are SL_High. ECC with 409 or more bits is also SL_High.
- Highest does not have an equivalent strength. It
indicates that the provider should use the strongest
- ciphers available (but not less than SL_High).
+ ciphers available (but not less than SL_High).
*/
-enum SecurityLevel
-{
- SL_None, ///< indicates that no security is ok
- SL_Integrity, ///< must at least get integrity protection
- SL_Export, ///< must be export level bits or more
- SL_Baseline, ///< must be 128 bit or more
- SL_High, ///< must be more than 128 bit
- SL_Highest ///< SL_High or max possible, whichever is greater
+enum SecurityLevel {
+ SL_None, ///< indicates that no security is ok
+ SL_Integrity, ///< must at least get integrity protection
+ SL_Export, ///< must be export level bits or more
+ SL_Baseline, ///< must be 128 bit or more
+ SL_High, ///< must be more than 128 bit
+ SL_Highest ///< SL_High or max possible, whichever is greater
};
/**
\class SecureLayer qca_securelayer.h QtCrypto
Abstract interface to a security layer
SecureLayer is normally used between an application and a
potentially insecure network. It provides secure
communications over that network.
The concept is that (after some initial setup), the
application can write() some data to the SecureLayer
implementation, and that data is encrypted (or otherwise
protected, depending on the setup). The SecureLayer
implementation then emits the readyReadOutgoing() signal,
and the application uses readOutgoing() to retrieve the the
encrypted data from the SecureLayer implementation. The
encrypted data is then sent out on the network.
When some encrypted data comes back from the network, the
application does a writeIncoming() to the SecureLayer
implementation. Some time later, the SecureLayer
implementation may emit readyRead() to the application,
which then read()s the decrypted data from the SecureLayer
implementation.
Note that sometimes data is sent or received between the
SecureLayer implementation and the network without any data
being sent between the application and the SecureLayer
implementation. This is a result of the initial negotiation
activities (which require network traffic to agree a
configuration to use) and other overheads associated with
the secure link.
\ingroup UserAPI
*/
class QCA_EXPORT SecureLayer : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Constructor for an abstract secure communications
- layer
-
- \param parent the parent object for this object
- */
- SecureLayer(QObject *parent = 0);
-
- /**
- Returns true if the layer has a meaningful "close".
- */
- virtual bool isClosable() const;
-
- /**
- Returns the number of bytes available to be read()
- on the application side.
- */
- virtual int bytesAvailable() const = 0;
-
- /**
- Returns the number of bytes available to be
- readOutgoing() on the network side.
- */
- virtual int bytesOutgoingAvailable() const = 0;
-
- /**
- Close the link. Note that this may not be
- meaningful / possible for all implementations.
-
- \sa isClosable() for a test that verifies if the
- link can be %closed.
- */
- virtual void close();
-
- /**
- This method writes unencrypted (plain) data to
- the SecureLayer implementation. You normally
- call this function on the application side.
-
- \param a the source of the application-side data
- */
- virtual void write(const QByteArray &a) = 0;
-
- /**
- This method reads decrypted (plain) data from
- the SecureLayer implementation. You normally call
- this function on the application side after receiving
- the readyRead() signal.
- */
- virtual QByteArray read() = 0;
-
- /**
- This method accepts encoded (typically encrypted) data
- for processing. You normally call this function using
- data read from the network socket (e.g. using
- QTcpSocket::readAll()) after receiving a signal that
- indicates that the socket has data to read.
-
- \param a the ByteArray to take network-side data from
- */
- virtual void writeIncoming(const QByteArray &a) = 0;
-
- /**
- This method provides encoded (typically encrypted)
- data. You normally call this function to get data
- to write out to the network socket (e.g. using
- QTcpSocket::write()) after receiving the
- readyReadOutgoing() signal.
-
- \param plainBytes the number of bytes that were read.
- */
- virtual QByteArray readOutgoing(int *plainBytes = 0) = 0;
-
- /**
- This allows you to read data without having it
- decrypted first. This is intended to be used for
- protocols that close off the connection and return
- to plain text transfer. You do not normally need to
- use this function.
- */
- virtual QByteArray readUnprocessed();
-
- /**
- Convert encrypted bytes written to plain text bytes written
-
- \param encryptedBytes the number of bytes to convert
- */
- virtual int convertBytesWritten(qint64 encryptedBytes) = 0;
+ /**
+ Constructor for an abstract secure communications
+ layer
+
+ \param parent the parent object for this object
+ */
+ SecureLayer(QObject *parent = 0);
+
+ /**
+ Returns true if the layer has a meaningful "close".
+ */
+ virtual bool isClosable() const;
+
+ /**
+ Returns the number of bytes available to be read()
+ on the application side.
+ */
+ virtual int bytesAvailable() const = 0;
+
+ /**
+ Returns the number of bytes available to be
+ readOutgoing() on the network side.
+ */
+ virtual int bytesOutgoingAvailable() const = 0;
+
+ /**
+ Close the link. Note that this may not be
+ meaningful / possible for all implementations.
+
+ \sa isClosable() for a test that verifies if the
+ link can be %closed.
+ */
+ virtual void close();
+
+ /**
+ This method writes unencrypted (plain) data to
+ the SecureLayer implementation. You normally
+ call this function on the application side.
+
+ \param a the source of the application-side data
+ */
+ virtual void write(const QByteArray &a) = 0;
+
+ /**
+ This method reads decrypted (plain) data from
+ the SecureLayer implementation. You normally call
+ this function on the application side after receiving
+ the readyRead() signal.
+ */
+ virtual QByteArray read() = 0;
+
+ /**
+ This method accepts encoded (typically encrypted) data
+ for processing. You normally call this function using
+ data read from the network socket (e.g. using
+ QTcpSocket::readAll()) after receiving a signal that
+ indicates that the socket has data to read.
+
+ \param a the ByteArray to take network-side data from
+ */
+ virtual void writeIncoming(const QByteArray &a) = 0;
+
+ /**
+ This method provides encoded (typically encrypted)
+ data. You normally call this function to get data
+ to write out to the network socket (e.g. using
+ QTcpSocket::write()) after receiving the
+ readyReadOutgoing() signal.
+
+ \param plainBytes the number of bytes that were read.
+ */
+ virtual QByteArray readOutgoing(int *plainBytes = 0) = 0;
+
+ /**
+ This allows you to read data without having it
+ decrypted first. This is intended to be used for
+ protocols that close off the connection and return
+ to plain text transfer. You do not normally need to
+ use this function.
+ */
+ virtual QByteArray readUnprocessed();
+
+ /**
+ Convert encrypted bytes written to plain text bytes written
+
+ \param encryptedBytes the number of bytes to convert
+ */
+ virtual int convertBytesWritten(qint64 encryptedBytes) = 0;
Q_SIGNALS:
- /**
- This signal is emitted when SecureLayer has
- decrypted (application side) data ready to be
- read. Typically you will connect this signal to a
- slot that reads the data (using read()).
- */
- void readyRead();
-
- /**
- This signal is emitted when SecureLayer has encrypted
- (network side) data ready to be read. Typically you
- will connect this signal to a slot that reads the data
- (using readOutgoing()) and writes it to a network socket.
- */
- void readyReadOutgoing();
-
- /**
- This signal is emitted when the SecureLayer connection
- is %closed.
- */
- void closed();
-
- /**
- This signal is emitted when an error is detected. You
- can determine the error type using errorCode().
- */
- void error();
+ /**
+ This signal is emitted when SecureLayer has
+ decrypted (application side) data ready to be
+ read. Typically you will connect this signal to a
+ slot that reads the data (using read()).
+ */
+ void readyRead();
+
+ /**
+ This signal is emitted when SecureLayer has encrypted
+ (network side) data ready to be read. Typically you
+ will connect this signal to a slot that reads the data
+ (using readOutgoing()) and writes it to a network socket.
+ */
+ void readyReadOutgoing();
+
+ /**
+ This signal is emitted when the SecureLayer connection
+ is %closed.
+ */
+ void closed();
+
+ /**
+ This signal is emitted when an error is detected. You
+ can determine the error type using errorCode().
+ */
+ void error();
private:
- Q_DISABLE_COPY(SecureLayer)
+ Q_DISABLE_COPY(SecureLayer)
};
/**
\class TLSSession qca_securelayer.h QtCrypto
Session token, used for TLS resuming
\ingroup UserAPI
*/
class QCA_EXPORT TLSSession : public Algorithm
{
public:
- TLSSession();
+ TLSSession();
- /**
- Copy constructor
+ /**
+ Copy constructor
- \param from the session token to copy from
- */
- TLSSession(const TLSSession &from);
+ \param from the session token to copy from
+ */
+ TLSSession(const TLSSession &from);
- ~TLSSession();
+ ~TLSSession();
- /**
- Assignment operator
+ /**
+ Assignment operator
- \param from the session token to assign from
- */
- TLSSession & operator=(const TLSSession &from);
+ \param from the session token to assign from
+ */
+ TLSSession &operator=(const TLSSession &from);
- /**
- Test if the session token is valid
- */
- bool isNull() const;
+ /**
+ Test if the session token is valid
+ */
+ bool isNull() const;
};
/**
\class TLS qca_securelayer.h QtCrypto
- Transport Layer Security / Secure Socket Layer
+ Transport Layer Security / Secure Socket Layer
Transport Layer Security (%TLS) is the current
state-of-the-art in secure transport mechanisms over the
internet. It can be used in a way where only one side of
the link needs to authenticate to the other. This makes it
very useful for servers to provide their identity to
clients. Note that is is possible to use %TLS to
authenticate both client and server.
%TLS is a IETF standard (<a
href="http://www.ietf.org/rfc/rfc2712.txt">RFC2712</a> for
TLS version 1.0, and <a
href="http://www.ietf.org/rfc/rfc4346.txt">RFC4346</a> for
TLS version 1.1) based on earlier Netscape work on Secure
Socket Layer (SSL version 2 and SSL version 3). New
applications should use at least TLS 1.0, and SSL version 2
should be avoided due to known security problems.
\ingroup UserAPI
*/
class QCA_EXPORT TLS : public SecureLayer, public Algorithm
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Operating mode
- */
- enum Mode
- {
- Stream, ///< stream mode
- Datagram ///< datagram mode
- };
-
- /**
- Version of %TLS or SSL
- */
- enum Version
- {
- TLS_v1, ///< Transport Layer Security, version 1
- SSL_v3, ///< Secure Socket Layer, version 3
- SSL_v2, ///< Secure Socket Layer, version 2
- DTLS_v1 ///< Datagram Transport Layer Security, version 1
- };
-
- /**
- Type of error
- */
- enum Error
- {
- ErrorSignerExpired, ///< local certificate is expired
- ErrorSignerInvalid, ///< local certificate is invalid in some way
- ErrorCertKeyMismatch, ///< certificate and private key don't match
- ErrorInit, ///< problem starting up %TLS
- ErrorHandshake, ///< problem during the negotiation
- ErrorCrypt ///< problem at anytime after
- };
-
- /**
- Type of identity
- */
- enum IdentityResult
- {
- Valid, ///< identity is verified
- HostMismatch, ///< valid cert provided, but wrong owner
- InvalidCertificate, ///< invalid cert
- NoCertificate ///< identity unknown
- };
-
- /**
- Constructor for Transport Layer Security connection
-
- This produces a Stream (normal %TLS) rather than Datagram (DTLS)
- object.
- If you want to do DTLS, see below.
-
- \param parent the parent object for this object
- \param provider the name of the provider, if a specific provider
- is required
- */
- explicit TLS(QObject *parent = 0, const QString &provider = QString());
-
- /**
- Constructor for Transport Layer Security connection.
-
- This constructor can be used for both normal %TLS (set mode to TLS::Stream)
- or DTLS (set mode to TLS::Datagram).
-
- \param mode the connection Mode
- \param parent the parent object for this object
- \param provider the name of the provider, if a specific provider is
- required
- */
- explicit TLS(Mode mode, QObject *parent = 0, const QString &provider = QString());
-
- /**
- Destructor
- */
- ~TLS();
-
- /**
- Reset the connection
- */
- void reset();
-
- /**
- Get the list of cipher suites that are available for use.
-
- A cipher suite is a combination of key exchange,
- encryption and hashing algorithms that are agreed
- during the initial handshake between client and
- server.
-
- \param version the protocol Version that the cipher
- suites are required for
-
- \return list of the the names of the cipher suites
- supported.
- */
- QStringList supportedCipherSuites(const Version &version = TLS_v1) const;
-
- /**
- The local certificate to use. This is the
- certificate that will be provided to the peer. This
- is almost always required on the server side
- (because the server has to provide a certificate to
- the client), and may be used on the client side.
-
- \param cert a chain of certificates that
- link the host certificate to a trusted root
- certificate.
- \param key the private key for the certificate
- chain
- */
- void setCertificate(const CertificateChain &cert, const PrivateKey &key);
-
- /**
- \overload
-
- Allows setting a certificate from a KeyBundle.
-
- \param kb key bundle containing the local certificate
- and associated private key.
- */
- void setCertificate(const KeyBundle &kb);
-
- /**
- Return the trusted certificates set for this object
- */
- CertificateCollection trustedCertificates() const;
-
- /**
- Set up the set of trusted certificates that will be used to verify
- that the certificate provided is valid.
-
- Typically, this will be the collection of root certificates from
- the system, which you can get using QCA::systemStore(), however you
- may choose to pass whatever certificates match your assurance
- needs.
-
- \param trusted a bundle of trusted certificates.
- */
- void setTrustedCertificates(const CertificateCollection &trusted);
-
- /**
- The security level required for this link
-
- \param s the level required for this link.
- */
- void setConstraints(SecurityLevel s);
-
- /**
- \overload
-
- \param minSSF the minimum Security Strength Factor
- required for this link.
- \param maxSSF the maximum Security Strength Factor
- required for this link.
- */
- void setConstraints(int minSSF, int maxSSF);
-
- /**
- \overload
-
- \param cipherSuiteList a list of the names of
- cipher suites that can be used for this link.
-
- \note the names are the same as the names in the
- applicable IETF RFCs (or Internet Drafts if there
- is no applicable RFC).
- */
- void setConstraints(const QStringList &cipherSuiteList);
-
- /**
- Retrieve the list of allowed issuers by the server,
- if the server has provided them. Only DN types will
- be present.
-
- \code
-Certificate someCert = ...
-PrivateKey someKey = ...
-
-// see if the server will take our cert
-CertificateInfoOrdered issuerInfo = someCert.issuerInfoOrdered().dnOnly();
-foreach(const CertificateInfoOrdered &info, tls->issuerList())
-{
- if(info == issuerInfo)
- {
- // server will accept someCert, let's present it
- tls->setCertificate(someCert, someKey);
- break;
- }
-}
- \endcode
- */
- QList<CertificateInfoOrdered> issuerList() const;
-
- /**
- Sets the issuer list to present to the client. For
- use with servers only. Only DN types are allowed.
-
- \param issuers the list of valid issuers to be used.
- */
- void setIssuerList(const QList<CertificateInfoOrdered> &issuers);
-
- /**
- Resume a %TLS session using the given session object
-
- \param session the session state to use for resumption.
- */
- void setSession(const TLSSession &session);
-
- /**
- Test if the link can use compression
-
- \return true if the link can use compression
- */
- bool canCompress() const;
-
- /**
- Test if the link can specify a hostname (Server Name
- Indication)
-
- \return true if the link can specify a hostname
- */
- bool canSetHostName() const;
-
- /**
- Returns true if compression is enabled
-
- This only indicates whether or not the object is configured to use
- compression, not whether or not the link is actually compressed.
- Use isCompressed() for that.
- */
- bool compressionEnabled() const;
-
- /**
- Set the link to use compression
-
- \param b true if the link should use compression, or false to
- disable compression
- */
- void setCompressionEnabled(bool b);
-
- /**
- Returns the host name specified or an empty string if no host
- name is specified.
- */
- QString hostName() const;
-
- /**
- Start the %TLS/SSL connection as a client
-
- Typically, you'll want to perform RFC 2818 validation on the
- server's certificate, based on the hostname you're intending
- to connect to. Pass a value for \a host in order to have the
- validation for you. If you want to bypass this behavior and
- do the validation yourself, pass an empty string for \a host.
-
- If the host is an internationalized domain name, then it must be
- provided in unicode format, not in IDNA ACE/punycode format.
-
- \param host the hostname that you want to connect to
-
- \note The hostname will be used for Server Name Indication
- extension (see
- <a href="http://www.ietf.org/rfc/rfc3546.txt">RFC 3546</a> Section
- 3.1) if supported by the backend provider.
- */
- void startClient(const QString &host = QString());
-
- /**
- Start the %TLS/SSL connection as a server.
- */
- void startServer();
-
- /**
- Resumes %TLS processing.
-
- Call this function after hostNameReceived(), certificateRequested()
- peerCertificateAvailable() or handshaken() is emitted. By
- requiring this function to be called in order to proceed,
- applications are given a chance to perform user interaction between
- steps in the %TLS process.
- */
- void continueAfterStep();
-
- /**
- test if the handshake is complete
-
- \return true if the handshake is complete
-
- \sa handshaken
- */
- bool isHandshaken() const;
-
- /**
- test if the link is compressed
-
- \return true if the link is compressed
- */
- bool isCompressed() const;
-
- /**
- The protocol version that is in use for this connection.
- */
- Version version() const;
-
- /**
- The cipher suite that has been negotiated for this connection.
-
- The name returned here is the name used in the applicable RFC
- (or Internet Draft, where there is no RFC).
- */
- QString cipherSuite() const;
-
- /**
- The number of effective bits of security being used for this
- connection.
-
- This can differ from the actual number of bits in
- the cipher for certain
- older "export ciphers" that are deliberately crippled. If you
- want that information, use cipherMaxBits().
- */
- int cipherBits() const;
-
- /**
- The number of bits of security that the cipher could use.
-
- This is normally the same as cipherBits(), but can be greater
- for older "export ciphers".
- */
- int cipherMaxBits() const;
-
- /**
- The session object of the %TLS connection, which can be used
- for resuming.
- */
- TLSSession session() const;
-
- /**
- This method returns the type of error that has
- occurred. You should only need to check this if the
- error() signal is emitted.
- */
- Error errorCode() const;
-
- /**
- After the SSL/%TLS handshake is complete, this
- method allows you to determine if the other end
- of the connection (if the application is a client,
- this is the server; if the application is a server,
- this is the client) has a valid identity.
-
- Note that the security of %TLS/SSL depends on
- checking this. It is not enough to check that the
- certificate is valid - you must check that the
- certificate is valid for the entity that you are
- trying to communicate with.
-
- \note If this returns QCA::TLS::InvalidCertificate,
- you may wish to use peerCertificateValidity() to
- determine whether to proceed or not.
- */
- IdentityResult peerIdentityResult() const;
-
- /**
- After the SSL/%TLS handshake is valid, this method
- allows you to check if the received certificate
- from the other end is valid. As noted in
- peerIdentityResult(), you also need to check that
- the certificate matches the entity you are trying
- to communicate with.
- */
- Validity peerCertificateValidity() const;
-
- /**
- The CertificateChain for the local host
- certificate.
- */
- CertificateChain localCertificateChain() const;
-
- /**
- The PrivateKey for the local host
- certificate.
- */
- PrivateKey localPrivateKey() const;
-
- /**
- The CertificateChain from the peer (other end of
- the connection to the trusted root certificate).
- */
- CertificateChain peerCertificateChain() const;
-
- // reimplemented
- virtual bool isClosable() const;
- virtual int bytesAvailable() const;
- virtual int bytesOutgoingAvailable() const;
- virtual void close();
- virtual void write(const QByteArray &a);
- virtual QByteArray read();
- virtual void writeIncoming(const QByteArray &a);
- virtual QByteArray readOutgoing(int *plainBytes = 0);
- virtual QByteArray readUnprocessed();
- virtual int convertBytesWritten(qint64 encryptedBytes);
-
- /**
- Determine the number of packets available to be
- read on the application side.
-
- \note this is only used with DTLS.
- */
- int packetsAvailable() const;
-
- /**
- Determine the number of packets available to be
- read on the network side.
-
- \note this is only used with DTLS.
- */
- int packetsOutgoingAvailable() const;
-
- /**
- Return the currently configured maximum packet size
-
- \note this is only used with DTLS
- */
- int packetMTU() const;
-
- /**
- Set the maximum packet size to use.
-
- \param size the number of bytes to set as the MTU.
-
- \note this is only used with DTLS.
- */
- void setPacketMTU(int size) const;
+ /**
+ Operating mode
+ */
+ enum Mode {
+ Stream, ///< stream mode
+ Datagram ///< datagram mode
+ };
+
+ /**
+ Version of %TLS or SSL
+ */
+ enum Version {
+ TLS_v1, ///< Transport Layer Security, version 1
+ SSL_v3, ///< Secure Socket Layer, version 3
+ SSL_v2, ///< Secure Socket Layer, version 2
+ DTLS_v1 ///< Datagram Transport Layer Security, version 1
+ };
+
+ /**
+ Type of error
+ */
+ enum Error {
+ ErrorSignerExpired, ///< local certificate is expired
+ ErrorSignerInvalid, ///< local certificate is invalid in some way
+ ErrorCertKeyMismatch, ///< certificate and private key don't match
+ ErrorInit, ///< problem starting up %TLS
+ ErrorHandshake, ///< problem during the negotiation
+ ErrorCrypt ///< problem at anytime after
+ };
+
+ /**
+ Type of identity
+ */
+ enum IdentityResult {
+ Valid, ///< identity is verified
+ HostMismatch, ///< valid cert provided, but wrong owner
+ InvalidCertificate, ///< invalid cert
+ NoCertificate ///< identity unknown
+ };
+
+ /**
+ Constructor for Transport Layer Security connection
+
+ This produces a Stream (normal %TLS) rather than Datagram (DTLS)
+ object.
+ If you want to do DTLS, see below.
+
+ \param parent the parent object for this object
+ \param provider the name of the provider, if a specific provider
+ is required
+ */
+ explicit TLS(QObject *parent = 0, const QString &provider = QString());
+
+ /**
+ Constructor for Transport Layer Security connection.
+
+ This constructor can be used for both normal %TLS (set mode to TLS::Stream)
+ or DTLS (set mode to TLS::Datagram).
+
+ \param mode the connection Mode
+ \param parent the parent object for this object
+ \param provider the name of the provider, if a specific provider is
+ required
+ */
+ explicit TLS(Mode mode, QObject *parent = 0, const QString &provider = QString());
+
+ /**
+ Destructor
+ */
+ ~TLS();
+
+ /**
+ Reset the connection
+ */
+ void reset();
+
+ /**
+ Get the list of cipher suites that are available for use.
+
+ A cipher suite is a combination of key exchange,
+ encryption and hashing algorithms that are agreed
+ during the initial handshake between client and
+ server.
+
+ \param version the protocol Version that the cipher
+ suites are required for
+
+ \return list of the the names of the cipher suites
+ supported.
+ */
+ QStringList supportedCipherSuites(const Version &version = TLS_v1) const;
+
+ /**
+ The local certificate to use. This is the
+ certificate that will be provided to the peer. This
+ is almost always required on the server side
+ (because the server has to provide a certificate to
+ the client), and may be used on the client side.
+
+ \param cert a chain of certificates that
+ link the host certificate to a trusted root
+ certificate.
+ \param key the private key for the certificate
+ chain
+ */
+ void setCertificate(const CertificateChain &cert, const PrivateKey &key);
+
+ /**
+ \overload
+
+ Allows setting a certificate from a KeyBundle.
+
+ \param kb key bundle containing the local certificate
+ and associated private key.
+ */
+ void setCertificate(const KeyBundle &kb);
+
+ /**
+ Return the trusted certificates set for this object
+ */
+ CertificateCollection trustedCertificates() const;
+
+ /**
+ Set up the set of trusted certificates that will be used to verify
+ that the certificate provided is valid.
+
+ Typically, this will be the collection of root certificates from
+ the system, which you can get using QCA::systemStore(), however you
+ may choose to pass whatever certificates match your assurance
+ needs.
+
+ \param trusted a bundle of trusted certificates.
+ */
+ void setTrustedCertificates(const CertificateCollection &trusted);
+
+ /**
+ The security level required for this link
+
+ \param s the level required for this link.
+ */
+ void setConstraints(SecurityLevel s);
+
+ /**
+ \overload
+
+ \param minSSF the minimum Security Strength Factor
+ required for this link.
+ \param maxSSF the maximum Security Strength Factor
+ required for this link.
+ */
+ void setConstraints(int minSSF, int maxSSF);
+
+ /**
+ \overload
+
+ \param cipherSuiteList a list of the names of
+ cipher suites that can be used for this link.
+
+ \note the names are the same as the names in the
+ applicable IETF RFCs (or Internet Drafts if there
+ is no applicable RFC).
+ */
+ void setConstraints(const QStringList &cipherSuiteList);
+
+ /**
+ Retrieve the list of allowed issuers by the server,
+ if the server has provided them. Only DN types will
+ be present.
+
+ \code
+ Certificate someCert = ...
+ PrivateKey someKey = ...
+
+ // see if the server will take our cert
+ CertificateInfoOrdered issuerInfo = someCert.issuerInfoOrdered().dnOnly();
+ foreach(const CertificateInfoOrdered &info, tls->issuerList())
+ {
+ if(info == issuerInfo)
+ {
+ // server will accept someCert, let's present it
+ tls->setCertificate(someCert, someKey);
+ break;
+ }
+ }
+ \endcode
+ */
+ QList<CertificateInfoOrdered> issuerList() const;
+
+ /**
+ Sets the issuer list to present to the client. For
+ use with servers only. Only DN types are allowed.
+
+ \param issuers the list of valid issuers to be used.
+ */
+ void setIssuerList(const QList<CertificateInfoOrdered> &issuers);
+
+ /**
+ Resume a %TLS session using the given session object
+
+ \param session the session state to use for resumption.
+ */
+ void setSession(const TLSSession &session);
+
+ /**
+ Test if the link can use compression
+
+ \return true if the link can use compression
+ */
+ bool canCompress() const;
+
+ /**
+ Test if the link can specify a hostname (Server Name
+ Indication)
+
+ \return true if the link can specify a hostname
+ */
+ bool canSetHostName() const;
+
+ /**
+ Returns true if compression is enabled
+
+ This only indicates whether or not the object is configured to use
+ compression, not whether or not the link is actually compressed.
+ Use isCompressed() for that.
+ */
+ bool compressionEnabled() const;
+
+ /**
+ Set the link to use compression
+
+ \param b true if the link should use compression, or false to
+ disable compression
+ */
+ void setCompressionEnabled(bool b);
+
+ /**
+ Returns the host name specified or an empty string if no host
+ name is specified.
+ */
+ QString hostName() const;
+
+ /**
+ Start the %TLS/SSL connection as a client
+
+ Typically, you'll want to perform RFC 2818 validation on the
+ server's certificate, based on the hostname you're intending
+ to connect to. Pass a value for \a host in order to have the
+ validation for you. If you want to bypass this behavior and
+ do the validation yourself, pass an empty string for \a host.
+
+ If the host is an internationalized domain name, then it must be
+ provided in unicode format, not in IDNA ACE/punycode format.
+
+ \param host the hostname that you want to connect to
+
+ \note The hostname will be used for Server Name Indication
+ extension (see
+ <a href="http://www.ietf.org/rfc/rfc3546.txt">RFC 3546</a> Section
+ 3.1) if supported by the backend provider.
+ */
+ void startClient(const QString &host = QString());
+
+ /**
+ Start the %TLS/SSL connection as a server.
+ */
+ void startServer();
+
+ /**
+ Resumes %TLS processing.
+
+ Call this function after hostNameReceived(), certificateRequested()
+ peerCertificateAvailable() or handshaken() is emitted. By
+ requiring this function to be called in order to proceed,
+ applications are given a chance to perform user interaction between
+ steps in the %TLS process.
+ */
+ void continueAfterStep();
+
+ /**
+ test if the handshake is complete
+
+ \return true if the handshake is complete
+
+ \sa handshaken
+ */
+ bool isHandshaken() const;
+
+ /**
+ test if the link is compressed
+
+ \return true if the link is compressed
+ */
+ bool isCompressed() const;
+
+ /**
+ The protocol version that is in use for this connection.
+ */
+ Version version() const;
+
+ /**
+ The cipher suite that has been negotiated for this connection.
+
+ The name returned here is the name used in the applicable RFC
+ (or Internet Draft, where there is no RFC).
+ */
+ QString cipherSuite() const;
+
+ /**
+ The number of effective bits of security being used for this
+ connection.
+
+ This can differ from the actual number of bits in
+ the cipher for certain
+ older "export ciphers" that are deliberately crippled. If you
+ want that information, use cipherMaxBits().
+ */
+ int cipherBits() const;
+
+ /**
+ The number of bits of security that the cipher could use.
+
+ This is normally the same as cipherBits(), but can be greater
+ for older "export ciphers".
+ */
+ int cipherMaxBits() const;
+
+ /**
+ The session object of the %TLS connection, which can be used
+ for resuming.
+ */
+ TLSSession session() const;
+
+ /**
+ This method returns the type of error that has
+ occurred. You should only need to check this if the
+ error() signal is emitted.
+ */
+ Error errorCode() const;
+
+ /**
+ After the SSL/%TLS handshake is complete, this
+ method allows you to determine if the other end
+ of the connection (if the application is a client,
+ this is the server; if the application is a server,
+ this is the client) has a valid identity.
+
+ Note that the security of %TLS/SSL depends on
+ checking this. It is not enough to check that the
+ certificate is valid - you must check that the
+ certificate is valid for the entity that you are
+ trying to communicate with.
+
+ \note If this returns QCA::TLS::InvalidCertificate,
+ you may wish to use peerCertificateValidity() to
+ determine whether to proceed or not.
+ */
+ IdentityResult peerIdentityResult() const;
+
+ /**
+ After the SSL/%TLS handshake is valid, this method
+ allows you to check if the received certificate
+ from the other end is valid. As noted in
+ peerIdentityResult(), you also need to check that
+ the certificate matches the entity you are trying
+ to communicate with.
+ */
+ Validity peerCertificateValidity() const;
+
+ /**
+ The CertificateChain for the local host
+ certificate.
+ */
+ CertificateChain localCertificateChain() const;
+
+ /**
+ The PrivateKey for the local host
+ certificate.
+ */
+ PrivateKey localPrivateKey() const;
+
+ /**
+ The CertificateChain from the peer (other end of
+ the connection to the trusted root certificate).
+ */
+ CertificateChain peerCertificateChain() const;
+
+ // reimplemented
+ virtual bool isClosable() const;
+ virtual int bytesAvailable() const;
+ virtual int bytesOutgoingAvailable() const;
+ virtual void close();
+ virtual void write(const QByteArray &a);
+ virtual QByteArray read();
+ virtual void writeIncoming(const QByteArray &a);
+ virtual QByteArray readOutgoing(int *plainBytes = 0);
+ virtual QByteArray readUnprocessed();
+ virtual int convertBytesWritten(qint64 encryptedBytes);
+
+ /**
+ Determine the number of packets available to be
+ read on the application side.
+
+ \note this is only used with DTLS.
+ */
+ int packetsAvailable() const;
+
+ /**
+ Determine the number of packets available to be
+ read on the network side.
+
+ \note this is only used with DTLS.
+ */
+ int packetsOutgoingAvailable() const;
+
+ /**
+ Return the currently configured maximum packet size
+
+ \note this is only used with DTLS
+ */
+ int packetMTU() const;
+
+ /**
+ Set the maximum packet size to use.
+
+ \param size the number of bytes to set as the MTU.
+
+ \note this is only used with DTLS.
+ */
+ void setPacketMTU(int size) const;
Q_SIGNALS:
- /**
- Emitted if a host name is set by the client. At
- this time, the server can inspect the hostName().
+ /**
+ Emitted if a host name is set by the client. At
+ this time, the server can inspect the hostName().
- You must call continueAfterStep() in order for %TLS
- processing to resume after this signal is emitted.
+ You must call continueAfterStep() in order for %TLS
+ processing to resume after this signal is emitted.
- This signal is only emitted in server mode.
+ This signal is only emitted in server mode.
- \sa continueAfterStep
- */
- void hostNameReceived();
+ \sa continueAfterStep
+ */
+ void hostNameReceived();
- /**
- Emitted when the server requests a certificate. At
- this time, the client can inspect the issuerList().
+ /**
+ Emitted when the server requests a certificate. At
+ this time, the client can inspect the issuerList().
- You must call continueAfterStep() in order for %TLS
- processing to resume after this signal is emitted.
+ You must call continueAfterStep() in order for %TLS
+ processing to resume after this signal is emitted.
- This signal is only emitted in client mode.
+ This signal is only emitted in client mode.
- \sa continueAfterStep
- */
- void certificateRequested();
+ \sa continueAfterStep
+ */
+ void certificateRequested();
- /**
- Emitted when a certificate is received from the peer.
- At this time, you may inspect peerIdentityResult(),
- peerCertificateValidity(), and peerCertificateChain().
+ /**
+ Emitted when a certificate is received from the peer.
+ At this time, you may inspect peerIdentityResult(),
+ peerCertificateValidity(), and peerCertificateChain().
- You must call continueAfterStep() in order for %TLS
- processing to resume after this signal is emitted.
+ You must call continueAfterStep() in order for %TLS
+ processing to resume after this signal is emitted.
- \sa continueAfterStep
- */
- void peerCertificateAvailable();
+ \sa continueAfterStep
+ */
+ void peerCertificateAvailable();
- /**
- Emitted when the protocol handshake is complete. At
- this time, all available information about the %TLS
- session can be inspected.
+ /**
+ Emitted when the protocol handshake is complete. At
+ this time, all available information about the %TLS
+ session can be inspected.
- You must call continueAfterStep() in order for %TLS
- processing to resume after this signal is emitted.
+ You must call continueAfterStep() in order for %TLS
+ processing to resume after this signal is emitted.
- \sa continueAfterStep
- \sa isHandshaken
- */
- void handshaken();
+ \sa continueAfterStep
+ \sa isHandshaken
+ */
+ void handshaken();
protected:
- /**
- Called when a connection is made to a particular signal
+ /**
+ Called when a connection is made to a particular signal
- \param signal the name of the signal that has been
- connected to.
- */
+ \param signal the name of the signal that has been
+ connected to.
+ */
#if QT_VERSION >= 0x050000
- void connectNotify(const QMetaMethod &signal);
+ void connectNotify(const QMetaMethod &signal);
#else
- void connectNotify(const char *signal);
+ void connectNotify(const char *signal);
#endif
- /**
- Called when a connection is removed from a particular signal
+ /**
+ Called when a connection is removed from a particular signal
- \param signal the name of the signal that has been
- disconnected from.
- */
+ \param signal the name of the signal that has been
+ disconnected from.
+ */
#if QT_VERSION >= 0x050000
- void disconnectNotify(const QMetaMethod &signal);
+ void disconnectNotify(const QMetaMethod &signal);
#else
- void disconnectNotify(const char *signal);
+ void disconnectNotify(const char *signal);
#endif
private:
- Q_DISABLE_COPY(TLS)
+ Q_DISABLE_COPY(TLS)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class SASL qca_securelayer.h QtCrypto
Simple Authentication and Security Layer protocol implementation
This class implements the Simple Authenication and Security Layer protocol,
which is described in RFC2222 - see
<a href="http://www.ietf.org/rfc/rfc2222.txt">http://www.ietf.org/rfc/rfc2222.txt</a>.
As the name suggests, %SASL provides authentication (eg, a "login" of some
form), for a connection oriented protocol, and can also provide protection
for the subsequent connection.
The %SASL protocol is designed to be extensible, through a range of
"mechanisms", where a mechanism is the actual authentication method.
Example mechanisms include Anonymous, LOGIN, Kerberos V4, and GSSAPI.
Mechanisms can be added (potentially without restarting the server
application) by the system administrator.
It is important to understand that %SASL is neither "network aware" nor
"protocol aware". That means that %SASL does not understand how the client
connects to the server, and %SASL does not understand the actual
application protocol.
\ingroup UserAPI
*/
class QCA_EXPORT SASL : public SecureLayer, public Algorithm
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Possible errors that may occur when using %SASL
- */
- enum Error
- {
- ErrorInit, ///< problem starting up %SASL
- ErrorHandshake, ///< problem during the authentication process
- ErrorCrypt ///< problem at anytime after
- };
-
- /**
- Possible authentication error states
- */
- enum AuthCondition
- {
- AuthFail, ///< Generic authentication failure
- NoMechanism, ///< No compatible/appropriate authentication mechanism
- BadProtocol, ///< Bad protocol or cancelled
- BadServer, ///< Server failed mutual authentication (client side only)
- BadAuth, ///< Authentication failure (server side only)
- NoAuthzid, ///< Authorization failure (server side only)
- TooWeak, ///< Mechanism too weak for this user (server side only)
- NeedEncrypt, ///< Encryption is needed in order to use mechanism (server side only)
- Expired, ///< Passphrase expired, has to be reset (server side only)
- Disabled, ///< Account is disabled (server side only)
- NoUser, ///< User not found (server side only)
- RemoteUnavailable ///< Remote service needed for auth is gone (server side only)
- };
-
- /**
- Authentication requirement flag values
- */
- enum AuthFlags
- {
- AuthFlagsNone = 0x00,
- AllowPlain = 0x01,
- AllowAnonymous = 0x02,
- RequireForwardSecrecy = 0x04,
- RequirePassCredentials = 0x08,
- RequireMutualAuth = 0x10,
- RequireAuthzidSupport = 0x20 // server-only
- };
-
- /**
- Mode options for client side sending
- */
- enum ClientSendMode
- {
- AllowClientSendFirst,
- DisableClientSendFirst
- };
-
- /**
- Mode options for server side sending
- */
- enum ServerSendMode
- {
- AllowServerSendLast,
- DisableServerSendLast
- };
-
- /**
- \class Params qca_securelayer.h QtCrypto
-
- Parameter flags for the %SASL authentication
-
- This is used to indicate which parameters are needed by %SASL
- in order to complete the authentication process.
-
- \ingroup UserAPI
- */
- class QCA_EXPORT Params
- {
- public:
- Params();
-
- /**
- Standard constructor.
-
- The concept behind this is that you set each of the
- flags depending on which parameters are needed.
-
- \param user the username is required
- \param authzid the authorization identity is required
- \param pass the password is required
- \param realm the realm is required
- */
- Params(bool user, bool authzid, bool pass, bool realm);
-
- /**
- Standard copy constructor
-
- \param from the Params object to copy
- */
- Params(const Params &from);
- ~Params();
-
- /**
- Standard assignment operator
-
- \param from the Params object to assign from
- */
- Params & operator=(const Params &from);
-
- /**
- User is needed
- */
- bool needUsername() const;
-
- /**
- An Authorization ID can be sent if desired
- */
- bool canSendAuthzid() const;
-
- /**
- Password is needed
- */
- bool needPassword() const;
-
- /**
- A Realm can be sent if desired
- */
- bool canSendRealm() const;
-
- private:
- class Private;
- Private *d;
- };
-
- /**
- Standard constructor
-
- \param parent the parent object for this %SASL connection
- \param provider if specified, the provider to use. If not
- specified, or specified as empty, then any provider is
- acceptable.
- */
- explicit SASL(QObject *parent = 0, const QString &provider = QString());
-
- ~SASL();
-
- /**
- Reset the %SASL mechanism
- */
- void reset();
-
- /**
- Specify connection constraints
-
- %SASL supports a range of authentication requirements, and
- a range of security levels. This method allows you to
- specify the requirements for your connection.
-
- \param f the authentication requirements, which you typically
- build using a binary OR function (eg AllowPlain | AllowAnonymous)
- \param s the security level of the encryption, if used. See
- SecurityLevel for details of what each level provides.
- */
- void setConstraints(AuthFlags f, SecurityLevel s = SL_None);
-
- /**
- \overload
-
- Unless you have a specific reason for directly specifying a
- strength factor, you probably should use the method above.
-
- \param f the authentication requirements, which you typically
- build using a binary OR function (eg AllowPlain | AllowAnonymous)
- \param minSSF the minimum security strength factor that is required
- \param maxSSF the maximum security strength factor that is required
-
- \note Security strength factors are a rough approximation to key
- length in the encryption function (eg if you are securing with
- plain DES, the security strength factor would be 56).
- */
- void setConstraints(AuthFlags f, int minSSF, int maxSSF);
-
- /**
- Specify the local address.
-
- \param addr the address of the local part of the connection
- \param port the port number of the local part of the connection
- */
- void setLocalAddress(const QString &addr, quint16 port);
-
- /**
- Specify the peer address.
-
- \param addr the address of the peer side of the connection
- \param port the port number of the peer side of the connection
- */
- void setRemoteAddress(const QString &addr, quint16 port);
-
- /**
- Specify the id of the externally secured connection
-
- \param authid the id of the connection
- */
- void setExternalAuthId(const QString &authid);
-
- /**
- Specify a security strength factor for an externally secured
- connection
-
- \param strength the security strength factor of the connection
- */
- void setExternalSSF(int strength);
-
- /**
- Initialise the client side of the connection
-
- startClient must be called on the client side of the connection.
- clientStarted will be emitted when the operation is completed.
-
- \param service the name of the service
- \param host the client side host name
- \param mechlist the list of mechanisms which can be used
- \param mode the mode to use on the client side
- */
- void startClient(const QString &service, const QString &host, const QStringList &mechlist, ClientSendMode mode = AllowClientSendFirst);
-
- /**
- Initialise the server side of the connection
-
- startServer must be called on the server side of the connection.
- serverStarted will be emitted when the operation is completed.
-
- \param service the name of the service
- \param host the server side host name
- \param realm the realm to use
- \param mode which mode to use on the server side
- */
- void startServer(const QString &service, const QString &host, const QString &realm, ServerSendMode mode = DisableServerSendLast);
-
- /**
- Process the first step in server mode (server)
-
- Call this with the mechanism selected by the client. If there
- is initial client data, call the other version of this function
- instead.
-
- \param mech the mechanism to be used.
- */
- void putServerFirstStep(const QString &mech);
-
- /**
- Process the first step in server mode (server)
-
- Call this with the mechanism selected by the client, and initial
- client data. If there is no initial client data, call the other
- version of this function instead.
-
- \param mech the mechanism to be used
- \param clientInit the initial data provided by the client side
- */
- void putServerFirstStep(const QString &mech, const QByteArray &clientInit);
-
- /**
- Process an authentication step
-
- Call this with authentication data received from the network.
- The only exception is the first step in server mode, in which
- case putServerFirstStep must be called.
-
- \param stepData the authentication data from the network
- */
- void putStep(const QByteArray &stepData);
-
- /**
- Return the mechanism selected (client)
- */
- QString mechanism() const;
-
- /**
- Return the mechanism list (server)
- */
- QStringList mechanismList() const;
-
- /**
- Return the realm list, if available (client)
- */
- QStringList realmList() const;
-
- /**
- Return the security strength factor of the connection
- */
- int ssf() const;
-
- /**
- Return the error code
- */
- Error errorCode() const;
-
- /**
- Return the reason for authentication failure
- */
- AuthCondition authCondition() const;
-
- /**
- Specify the username to use in authentication
-
- \param user the username to use
- */
- void setUsername(const QString &user);
-
- /**
- Specify the authorization identity to use in authentication
-
- \param auth the authorization identity to use
- */
- void setAuthzid(const QString &auth);
-
- /**
- Specify the password to use in authentication
-
- \param pass the password to use
- */
- void setPassword(const SecureArray &pass);
-
- /**
- Specify the realm to use in authentication
-
- \param realm the realm to use
- */
- void setRealm(const QString &realm);
-
- /**
- Continue negotiation after parameters have been set (client)
- */
- void continueAfterParams();
-
- /**
- Continue negotiation after auth ids have been checked (server)
- */
- void continueAfterAuthCheck();
-
- // reimplemented
- virtual int bytesAvailable() const;
- virtual int bytesOutgoingAvailable() const;
- virtual void write(const QByteArray &a);
- virtual QByteArray read();
- virtual void writeIncoming(const QByteArray &a);
- virtual QByteArray readOutgoing(int *plainBytes = 0);
- virtual int convertBytesWritten(qint64 encryptedBytes);
+ /**
+ Possible errors that may occur when using %SASL
+ */
+ enum Error {
+ ErrorInit, ///< problem starting up %SASL
+ ErrorHandshake, ///< problem during the authentication process
+ ErrorCrypt ///< problem at anytime after
+ };
+
+ /**
+ Possible authentication error states
+ */
+ enum AuthCondition {
+ AuthFail, ///< Generic authentication failure
+ NoMechanism, ///< No compatible/appropriate authentication mechanism
+ BadProtocol, ///< Bad protocol or cancelled
+ BadServer, ///< Server failed mutual authentication (client side only)
+ BadAuth, ///< Authentication failure (server side only)
+ NoAuthzid, ///< Authorization failure (server side only)
+ TooWeak, ///< Mechanism too weak for this user (server side only)
+ NeedEncrypt, ///< Encryption is needed in order to use mechanism (server side only)
+ Expired, ///< Passphrase expired, has to be reset (server side only)
+ Disabled, ///< Account is disabled (server side only)
+ NoUser, ///< User not found (server side only)
+ RemoteUnavailable ///< Remote service needed for auth is gone (server side only)
+ };
+
+ /**
+ Authentication requirement flag values
+ */
+ enum AuthFlags {
+ AuthFlagsNone = 0x00,
+ AllowPlain = 0x01,
+ AllowAnonymous = 0x02,
+ RequireForwardSecrecy = 0x04,
+ RequirePassCredentials = 0x08,
+ RequireMutualAuth = 0x10,
+ RequireAuthzidSupport = 0x20 // server-only
+ };
+
+ /**
+ Mode options for client side sending
+ */
+ enum ClientSendMode {
+ AllowClientSendFirst,
+ DisableClientSendFirst
+ };
+
+ /**
+ Mode options for server side sending
+ */
+ enum ServerSendMode {
+ AllowServerSendLast,
+ DisableServerSendLast
+ };
+
+ /**
+ \class Params qca_securelayer.h QtCrypto
+
+ Parameter flags for the %SASL authentication
+
+ This is used to indicate which parameters are needed by %SASL
+ in order to complete the authentication process.
+
+ \ingroup UserAPI
+ */
+ class QCA_EXPORT Params
+ {
+ public:
+ Params();
+
+ /**
+ Standard constructor.
+
+ The concept behind this is that you set each of the
+ flags depending on which parameters are needed.
+
+ \param user the username is required
+ \param authzid the authorization identity is required
+ \param pass the password is required
+ \param realm the realm is required
+ */
+ Params(bool user, bool authzid, bool pass, bool realm);
+
+ /**
+ Standard copy constructor
+
+ \param from the Params object to copy
+ */
+ Params(const Params &from);
+ ~Params();
+
+ /**
+ Standard assignment operator
+
+ \param from the Params object to assign from
+ */
+ Params &operator=(const Params &from);
+
+ /**
+ User is needed
+ */
+ bool needUsername() const;
+
+ /**
+ An Authorization ID can be sent if desired
+ */
+ bool canSendAuthzid() const;
+
+ /**
+ Password is needed
+ */
+ bool needPassword() const;
+
+ /**
+ A Realm can be sent if desired
+ */
+ bool canSendRealm() const;
+
+ private:
+ class Private;
+ Private *d;
+ };
+
+ /**
+ Standard constructor
+
+ \param parent the parent object for this %SASL connection
+ \param provider if specified, the provider to use. If not
+ specified, or specified as empty, then any provider is
+ acceptable.
+ */
+ explicit SASL(QObject *parent = 0, const QString &provider = QString());
+
+ ~SASL();
+
+ /**
+ Reset the %SASL mechanism
+ */
+ void reset();
+
+ /**
+ Specify connection constraints
+
+ %SASL supports a range of authentication requirements, and
+ a range of security levels. This method allows you to
+ specify the requirements for your connection.
+
+ \param f the authentication requirements, which you typically
+ build using a binary OR function (eg AllowPlain | AllowAnonymous)
+ \param s the security level of the encryption, if used. See
+ SecurityLevel for details of what each level provides.
+ */
+ void setConstraints(AuthFlags f, SecurityLevel s = SL_None);
+
+ /**
+ \overload
+
+ Unless you have a specific reason for directly specifying a
+ strength factor, you probably should use the method above.
+
+ \param f the authentication requirements, which you typically
+ build using a binary OR function (eg AllowPlain | AllowAnonymous)
+ \param minSSF the minimum security strength factor that is required
+ \param maxSSF the maximum security strength factor that is required
+
+ \note Security strength factors are a rough approximation to key
+ length in the encryption function (eg if you are securing with
+ plain DES, the security strength factor would be 56).
+ */
+ void setConstraints(AuthFlags f, int minSSF, int maxSSF);
+
+ /**
+ Specify the local address.
+
+ \param addr the address of the local part of the connection
+ \param port the port number of the local part of the connection
+ */
+ void setLocalAddress(const QString &addr, quint16 port);
+
+ /**
+ Specify the peer address.
+
+ \param addr the address of the peer side of the connection
+ \param port the port number of the peer side of the connection
+ */
+ void setRemoteAddress(const QString &addr, quint16 port);
+
+ /**
+ Specify the id of the externally secured connection
+
+ \param authid the id of the connection
+ */
+ void setExternalAuthId(const QString &authid);
+
+ /**
+ Specify a security strength factor for an externally secured
+ connection
+
+ \param strength the security strength factor of the connection
+ */
+ void setExternalSSF(int strength);
+
+ /**
+ Initialise the client side of the connection
+
+ startClient must be called on the client side of the connection.
+ clientStarted will be emitted when the operation is completed.
+
+ \param service the name of the service
+ \param host the client side host name
+ \param mechlist the list of mechanisms which can be used
+ \param mode the mode to use on the client side
+ */
+ void startClient(const QString &service, const QString &host, const QStringList &mechlist, ClientSendMode mode = AllowClientSendFirst);
+
+ /**
+ Initialise the server side of the connection
+
+ startServer must be called on the server side of the connection.
+ serverStarted will be emitted when the operation is completed.
+
+ \param service the name of the service
+ \param host the server side host name
+ \param realm the realm to use
+ \param mode which mode to use on the server side
+ */
+ void startServer(const QString &service, const QString &host, const QString &realm, ServerSendMode mode = DisableServerSendLast);
+
+ /**
+ Process the first step in server mode (server)
+
+ Call this with the mechanism selected by the client. If there
+ is initial client data, call the other version of this function
+ instead.
+
+ \param mech the mechanism to be used.
+ */
+ void putServerFirstStep(const QString &mech);
+
+ /**
+ Process the first step in server mode (server)
+
+ Call this with the mechanism selected by the client, and initial
+ client data. If there is no initial client data, call the other
+ version of this function instead.
+
+ \param mech the mechanism to be used
+ \param clientInit the initial data provided by the client side
+ */
+ void putServerFirstStep(const QString &mech, const QByteArray &clientInit);
+
+ /**
+ Process an authentication step
+
+ Call this with authentication data received from the network.
+ The only exception is the first step in server mode, in which
+ case putServerFirstStep must be called.
+
+ \param stepData the authentication data from the network
+ */
+ void putStep(const QByteArray &stepData);
+
+ /**
+ Return the mechanism selected (client)
+ */
+ QString mechanism() const;
+
+ /**
+ Return the mechanism list (server)
+ */
+ QStringList mechanismList() const;
+
+ /**
+ Return the realm list, if available (client)
+ */
+ QStringList realmList() const;
+
+ /**
+ Return the security strength factor of the connection
+ */
+ int ssf() const;
+
+ /**
+ Return the error code
+ */
+ Error errorCode() const;
+
+ /**
+ Return the reason for authentication failure
+ */
+ AuthCondition authCondition() const;
+
+ /**
+ Specify the username to use in authentication
+
+ \param user the username to use
+ */
+ void setUsername(const QString &user);
+
+ /**
+ Specify the authorization identity to use in authentication
+
+ \param auth the authorization identity to use
+ */
+ void setAuthzid(const QString &auth);
+
+ /**
+ Specify the password to use in authentication
+
+ \param pass the password to use
+ */
+ void setPassword(const SecureArray &pass);
+
+ /**
+ Specify the realm to use in authentication
+
+ \param realm the realm to use
+ */
+ void setRealm(const QString &realm);
+
+ /**
+ Continue negotiation after parameters have been set (client)
+ */
+ void continueAfterParams();
+
+ /**
+ Continue negotiation after auth ids have been checked (server)
+ */
+ void continueAfterAuthCheck();
+
+ // reimplemented
+ virtual int bytesAvailable() const;
+ virtual int bytesOutgoingAvailable() const;
+ virtual void write(const QByteArray &a);
+ virtual QByteArray read();
+ virtual void writeIncoming(const QByteArray &a);
+ virtual QByteArray readOutgoing(int *plainBytes = 0);
+ virtual int convertBytesWritten(qint64 encryptedBytes);
Q_SIGNALS:
- /**
- This signal is emitted when the client has been successfully
- started
-
- \param clientInit true if the client should send an initial
- response to the server
- \param clientInitData the initial response to send to the server.
- Do note that there is a difference in SASL between an empty initial
- response and no initial response, and so even if clientInitData is
- an empty array, you still need to send an initial response if
- clientInit is true.
- */
- void clientStarted(bool clientInit, const QByteArray &clientInitData);
-
- /**
- This signal is emitted after the server has been
- successfully started
- */
- void serverStarted();
-
- /**
- This signal is emitted when there is data required
- to be sent over the network to complete the next
- step in the authentication process.
-
- \param stepData the data to send over the network
- */
- void nextStep(const QByteArray &stepData);
-
- /**
- This signal is emitted when the client needs
- additional parameters
-
- After receiving this signal, the application should set
- the required parameter values appropriately and then call
- continueAfterParams().
-
- \param params the parameters that are required by the client
- */
- void needParams(const QCA::SASL::Params &params);
-
- /**
- This signal is emitted when the server needs to
- perform the authentication check
-
- If the user and authzid are valid, call continueAfterAuthCheck().
-
- \param user the user identification name
- \param authzid the user authorization name
- */
- void authCheck(const QString &user, const QString &authzid);
-
- /**
- This signal is emitted when authentication is complete.
- */
- void authenticated();
+ /**
+ This signal is emitted when the client has been successfully
+ started
+
+ \param clientInit true if the client should send an initial
+ response to the server
+ \param clientInitData the initial response to send to the server.
+ Do note that there is a difference in SASL between an empty initial
+ response and no initial response, and so even if clientInitData is
+ an empty array, you still need to send an initial response if
+ clientInit is true.
+ */
+ void clientStarted(bool clientInit, const QByteArray &clientInitData);
+
+ /**
+ This signal is emitted after the server has been
+ successfully started
+ */
+ void serverStarted();
+
+ /**
+ This signal is emitted when there is data required
+ to be sent over the network to complete the next
+ step in the authentication process.
+
+ \param stepData the data to send over the network
+ */
+ void nextStep(const QByteArray &stepData);
+
+ /**
+ This signal is emitted when the client needs
+ additional parameters
+
+ After receiving this signal, the application should set
+ the required parameter values appropriately and then call
+ continueAfterParams().
+
+ \param params the parameters that are required by the client
+ */
+ void needParams(const QCA::SASL::Params &params);
+
+ /**
+ This signal is emitted when the server needs to
+ perform the authentication check
+
+ If the user and authzid are valid, call continueAfterAuthCheck().
+
+ \param user the user identification name
+ \param authzid the user authorization name
+ */
+ void authCheck(const QString &user, const QString &authzid);
+
+ /**
+ This signal is emitted when authentication is complete.
+ */
+ void authenticated();
private:
- Q_DISABLE_COPY(SASL)
+ Q_DISABLE_COPY(SASL)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
}
#endif
diff --git a/include/QtCrypto/qca_securemessage.h b/include/QtCrypto/qca_securemessage.h
index f8bbe3d9..4cb6b3b5 100644
--- a/include/QtCrypto/qca_securemessage.h
+++ b/include/QtCrypto/qca_securemessage.h
@@ -1,958 +1,952 @@
/*
* qca_securemessage.h - Qt Cryptographic Architecture
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_securemessage.h
Header file for secure message (PGP, CMS) classes
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_SECUREMESSAGE_H
#define QCA_SECUREMESSAGE_H
#include <QObject>
#include "qca_core.h"
#include "qca_publickey.h"
#include "qca_cert.h"
class QDateTime;
-namespace QCA {
+namespace QCA
+{
class SecureMessageSystem;
/**
\class SecureMessageKey qca_securemessage.h QtCrypto
Key for SecureMessage system
\ingroup UserAPI
*/
class QCA_EXPORT SecureMessageKey
{
public:
- /**
- The key type
- */
- enum Type
- {
- None, ///< no key
- PGP, ///< Pretty Good Privacy key
- X509 ///< X.509 CMS key
- };
+ /**
+ The key type
+ */
+ enum Type {
+ None, ///< no key
+ PGP, ///< Pretty Good Privacy key
+ X509 ///< X.509 CMS key
+ };
- /**
- Construct an empty key
- */
- SecureMessageKey();
+ /**
+ Construct an empty key
+ */
+ SecureMessageKey();
- /**
- Standard copy constructor
+ /**
+ Standard copy constructor
- \param from the source key
- */
- SecureMessageKey(const SecureMessageKey &from);
+ \param from the source key
+ */
+ SecureMessageKey(const SecureMessageKey &from);
- ~SecureMessageKey();
+ ~SecureMessageKey();
- /**
- Standard assignment operator
+ /**
+ Standard assignment operator
- \param from the source key
- */
- SecureMessageKey & operator=(const SecureMessageKey &from);
+ \param from the source key
+ */
+ SecureMessageKey &operator=(const SecureMessageKey &from);
- /**
- Returns true for null object
- */
- bool isNull() const;
+ /**
+ Returns true for null object
+ */
+ bool isNull() const;
- /**
- The key type
- */
- Type type() const;
+ /**
+ The key type
+ */
+ Type type() const;
- /**
- Public key part of a PGP key
- */
- PGPKey pgpPublicKey() const;
+ /**
+ Public key part of a PGP key
+ */
+ PGPKey pgpPublicKey() const;
- /**
- Private key part of a PGP key
- */
- PGPKey pgpSecretKey() const;
+ /**
+ Private key part of a PGP key
+ */
+ PGPKey pgpSecretKey() const;
- /**
- Set the public key part of a PGP key
+ /**
+ Set the public key part of a PGP key
- \param pub the PGP public key
- */
- void setPGPPublicKey(const PGPKey &pub);
+ \param pub the PGP public key
+ */
+ void setPGPPublicKey(const PGPKey &pub);
- /**
- Set the private key part of a PGP key
+ /**
+ Set the private key part of a PGP key
- \param sec the PGP secretkey
- */
- void setPGPSecretKey(const PGPKey &sec);
+ \param sec the PGP secretkey
+ */
+ void setPGPSecretKey(const PGPKey &sec);
- /**
- The X.509 certificate chain (public part) for this key
- */
- CertificateChain x509CertificateChain() const;
+ /**
+ The X.509 certificate chain (public part) for this key
+ */
+ CertificateChain x509CertificateChain() const;
- /**
- The X.509 private key part of this key
- */
- PrivateKey x509PrivateKey() const;
+ /**
+ The X.509 private key part of this key
+ */
+ PrivateKey x509PrivateKey() const;
- /**
- Set the public key part of this X.509 key.
+ /**
+ Set the public key part of this X.509 key.
- \param c the Certificate chain containing the public keys
- */
- void setX509CertificateChain(const CertificateChain &c);
+ \param c the Certificate chain containing the public keys
+ */
+ void setX509CertificateChain(const CertificateChain &c);
- /**
- Set the private key part of this X.509 key.
+ /**
+ Set the private key part of this X.509 key.
- \param k the private key
- */
- void setX509PrivateKey(const PrivateKey &k);
+ \param k the private key
+ */
+ void setX509PrivateKey(const PrivateKey &k);
- /**
- Set the public and private part of this X.509 key with KeyBundle.
+ /**
+ Set the public and private part of this X.509 key with KeyBundle.
- \param kb the public and private key bundle
- */
- void setX509KeyBundle(const KeyBundle &kb);
+ \param kb the public and private key bundle
+ */
+ void setX509KeyBundle(const KeyBundle &kb);
- /**
- Test if this key contains a private key part
- */
- bool havePrivate() const;
+ /**
+ Test if this key contains a private key part
+ */
+ bool havePrivate() const;
- /**
- The name associated with this key
+ /**
+ The name associated with this key
- For a PGP key, this is the primary user ID
+ For a PGP key, this is the primary user ID
- For an X.509 key, this is the Common Name
- */
- QString name() const;
+ For an X.509 key, this is the Common Name
+ */
+ QString name() const;
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
A list of message keys
*/
typedef QList<SecureMessageKey> SecureMessageKeyList;
/**
\class SecureMessageSignature qca_securemessage.h QtCrypto
SecureMessage signature
\ingroup UserAPI
*/
class QCA_EXPORT SecureMessageSignature
{
public:
- /**
- The result of identity verification
- */
- enum IdentityResult
- {
- Valid, ///< indentity is verified, matches signature
- InvalidSignature, ///< valid key provided, but signature failed
- InvalidKey, ///< invalid key provided
- NoKey ///< identity unknown
- };
-
- /**
- Create an empty signature check object.
-
- User applications don't normally need to create signature checks. You normally
- get the object back as a result of a SecureMessage operation.
- */
- SecureMessageSignature();
-
- /**
- Create a signature check object
-
- User applications don't normally need to create signature checks. You normally
- get the object back as a result of a SecureMessage operation.
-
- \param r the result of the check
- \param v the Validity of the key validation check
- \param key the key associated with the signature
- \param ts the timestamp associated with the signature
- */
- SecureMessageSignature(IdentityResult r, Validity v, const SecureMessageKey &key, const QDateTime &ts);
-
- /**
- Standard copy constructor
-
- \param from the source signature object
- */
- SecureMessageSignature(const SecureMessageSignature &from);
-
- ~SecureMessageSignature();
-
- /**
- Standard assignment operator
-
- \param from the source signature object
- */
- SecureMessageSignature & operator=(const SecureMessageSignature &from);
-
- /**
- get the results of the identity check on this signature
- */
- IdentityResult identityResult() const;
-
- /**
- get the results of the key validation check on this signature
- */
- Validity keyValidity() const;
-
- /**
- get the key associated with this signature
- */
- SecureMessageKey key() const;
-
- /**
- get the timestamp associated with this signature
- */
- QDateTime timestamp() const;
+ /**
+ The result of identity verification
+ */
+ enum IdentityResult {
+ Valid, ///< indentity is verified, matches signature
+ InvalidSignature, ///< valid key provided, but signature failed
+ InvalidKey, ///< invalid key provided
+ NoKey ///< identity unknown
+ };
+
+ /**
+ Create an empty signature check object.
+
+ User applications don't normally need to create signature checks. You normally
+ get the object back as a result of a SecureMessage operation.
+ */
+ SecureMessageSignature();
+
+ /**
+ Create a signature check object
+
+ User applications don't normally need to create signature checks. You normally
+ get the object back as a result of a SecureMessage operation.
+
+ \param r the result of the check
+ \param v the Validity of the key validation check
+ \param key the key associated with the signature
+ \param ts the timestamp associated with the signature
+ */
+ SecureMessageSignature(IdentityResult r, Validity v, const SecureMessageKey &key, const QDateTime &ts);
+
+ /**
+ Standard copy constructor
+
+ \param from the source signature object
+ */
+ SecureMessageSignature(const SecureMessageSignature &from);
+
+ ~SecureMessageSignature();
+
+ /**
+ Standard assignment operator
+
+ \param from the source signature object
+ */
+ SecureMessageSignature &operator=(const SecureMessageSignature &from);
+
+ /**
+ get the results of the identity check on this signature
+ */
+ IdentityResult identityResult() const;
+
+ /**
+ get the results of the key validation check on this signature
+ */
+ Validity keyValidity() const;
+
+ /**
+ get the key associated with this signature
+ */
+ SecureMessageKey key() const;
+
+ /**
+ get the timestamp associated with this signature
+ */
+ QDateTime timestamp() const;
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
A list of signatures
*/
typedef QList<SecureMessageSignature> SecureMessageSignatureList;
-
/**
\class SecureMessage qca_securemessage.h QtCrypto
Class representing a secure message
SecureMessage presents a unified interface for working with both
OpenPGP and CMS (S/MIME) messages. Prepare the object by calling
setFormat(), setRecipient(), and setSigner() as necessary, and then
begin the operation by calling an appropriate 'start' function, such
as startSign().
Here is an example of how to perform a Clearsign operation using PGP:
\code
// first make the SecureMessageKey
PGPKey myPGPKey = getSecretKeyFromSomewhere();
SecureMessageKey key;
key.setPGPSecretKey(myPGPKey);
// our data to sign
QByteArray plain = "Hello, world";
// let's do it
OpenPGP pgp;
SecureMessage msg(&pgp);
msg.setSigner(key);
msg.startSign(SecureMessage::Clearsign);
msg.update(plain);
msg.end();
msg.waitForFinished(-1);
if(msg.success())
{
- QByteArray result = msg.read();
- // result now contains the clearsign text data
+ QByteArray result = msg.read();
+ // result now contains the clearsign text data
}
else
{
- // error
- ...
+ // error
+ ...
}
\endcode
Performing a CMS sign operation is similar. Simply set up the
SecureMessageKey with a Certificate instead of a PGPKey, and operate on a
CMS object instead of an OpenPGP object.
\sa SecureMessageKey
\sa SecureMessageSignature
\sa OpenPGP
\sa CMS
\ingroup UserAPI
*/
class QCA_EXPORT SecureMessage : public QObject, public Algorithm
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The type of secure message
- */
- enum Type
- {
- OpenPGP, ///< a Pretty Good Privacy message
- CMS ///< a Cryptographic Message Syntax message
- };
-
- /**
- The type of message signature
- */
- enum SignMode
- {
- Message, ///< the message includes the signature
- Clearsign, ///< the message is clear signed
- Detached ///< the signature is detached
- };
-
- /**
- Formats for secure messages
- */
- enum Format
- {
- Binary, ///< DER/binary
- Ascii ///< PEM/ascii-armored
- };
-
- /**
- Errors for secure messages
- */
- enum Error
- {
- ErrorPassphrase, ///< passphrase was either wrong or not provided
- ErrorFormat, ///< input format was bad
- ErrorSignerExpired, ///< signing key is expired
- ErrorSignerInvalid, ///< signing key is invalid in some way
- ErrorEncryptExpired, ///< encrypting key is expired
- ErrorEncryptUntrusted, ///< encrypting key is untrusted
- ErrorEncryptInvalid, ///< encrypting key is invalid in some way
- ErrorNeedCard, ///< pgp card is missing
- ErrorCertKeyMismatch, ///< certificate and private key don't match
- ErrorUnknown, ///< other error
- ErrorSignerRevoked, ///< signing key is revoked
- ErrorSignatureExpired, ///< signature is expired
- ErrorEncryptRevoked ///< encrypting key is revoked
- };
-
- /**
- Create a new secure message
-
- This constructor uses an existing
- SecureMessageSystem object (for example, an OpenPGP
- or CMS object) to generate a specific kind of
- secure message.
-
- \param system a pre-existing and configured SecureMessageSystem
- object
- */
- SecureMessage(SecureMessageSystem *system);
- ~SecureMessage();
-
- /**
- The Type of secure message
- */
- Type type() const;
-
- /**
- Test if the message type supports multiple
- (parallel) signatures.
-
- \return true if the secure message support multiple
- parallel signatures
-
- \note PGP cannot do this - it is primarily a CMS
- feature
- */
- bool canSignMultiple() const;
-
- /**
- True if the SecureMessageSystem can clearsign
- messages.
-
- \note CMS cannot clearsign - this is normally only
- available for PGP
- */
- bool canClearsign() const;
-
- /**
- True if the SecureMessageSystem can both sign and
- encrypt (in the same operation).
-
- \note CMS cannot do an integrated sign/encrypt -
- this is normally only available for PGP. You can do
- separate signing and encrypting operations on the
- same message with CMS though.
- */
- bool canSignAndEncrypt() const;
-
- /**
- Reset the object state to that of original construction.
- Now a new operation can be performed immediately.
- */
- void reset();
-
- /**
- Returns true if bundling of the signer certificate chain is
- enabled
- */
- bool bundleSignerEnabled() const;
-
- /**
- Returns true if inclusion of S/MIME attributes is enabled
- */
- bool smimeAttributesEnabled() const;
-
- /**
- Return the format type set for this message
- */
- Format format() const;
-
- /**
- Return the recipient(s) set for this message with setRecipient() or
- setRecipients()
- */
- SecureMessageKeyList recipientKeys() const;
-
- /**
- Return the signer(s) set for this message with setSigner() or
- setSigners()
- */
- SecureMessageKeyList signerKeys() const;
-
- /**
- For CMS only, this will bundle the signer certificate chain
- into the message. This allows a message to be verified
- on its own, without the need to have obtained the signer's
- certificate in advance. Email clients using S/MIME often
- bundle the signer, greatly simplifying key management.
-
- This behavior is enabled by default.
-
- \param b whether to bundle (if true) or not (false)
- */
- void setBundleSignerEnabled(bool b);
-
- /**
- For CMS only, this will put extra attributes into the
- message related to S/MIME, such as the preferred
- type of algorithm to use in replies. The attributes
- used are decided by the provider.
-
- This behavior is enabled by default.
-
- \param b whether to embed extra attribues (if true) or not (false)
- */
- void setSMIMEAttributesEnabled(bool b);
-
- /**
- Set the Format used for messages
-
- The default is Binary.
-
- \param f whether to use Binary or Ascii
- */
- void setFormat(Format f);
-
- /**
- Set the recipient for an encrypted message
-
- \param key the recipient's key
-
- \sa setRecipients
- */
- void setRecipient(const SecureMessageKey &key);
-
- /**
- Set the list of recipients for an encrypted message.
-
- For a list with one item, this has the same effect as setRecipient.
-
- \param keys the recipients' key
-
- \sa setRecipient
- */
- void setRecipients(const SecureMessageKeyList &keys);
-
- /**
- Set the signer for a signed message.
-
- This is used for both creating signed messages as well as for
- verifying CMS messages that have no signer bundled.
-
- \param key the key associated with the signer
-
- \sa setSigners
- */
- void setSigner(const SecureMessageKey &key);
-
- /**
- Set the list of signers for a signed message.
-
- This is used for both creating signed messages as well as for
- verifying CMS messages that have no signer bundled.
-
- For a list with one item, this has the same effect as setSigner.
-
- \param keys the key associated with the signer
-
- \sa setSigner
- */
- void setSigners(const SecureMessageKeyList &keys);
-
- /**
- Start an encryption operation
-
- You will normally use this with some code along
- these lines:
- \code
-encryptingObj.startEncrypt();
-encryptingObj.update(message);
-// perhaps some more update()s
-encryptingObj.end();
- \endcode
-
- Each update() may (or may not) result in some
- encrypted data, as indicated by the readyRead()
- signal being emitted. Alternatively, you can wait
- until the whole message is available (using either
- waitForFinished(), or use the finished()
- signal. The encrypted message can then be read
- using the read() method.
- */
- void startEncrypt();
-
- /**
- Start an decryption operation
-
- You will normally use this with some code along
- these lines:
- \code
-decryptingObj.startEncrypt();
-decryptingObj.update(message);
-// perhaps some more update()s
-decryptingObj.end();
- \endcode
-
- Each update() may (or may not) result in some
- decrypted data, as indicated by the readyRead()
- signal being emitted. Alternatively, you can wait
- until the whole message is available (using either
- waitForFinished(), or the finished()
- signal). The decrypted message can then be read
- using the read() method.
-
- \note If decrypted result is also signed (not for
- CMS), then the signature will be verified during
- this operation.
- */
- void startDecrypt();
-
- /**
- Start a signing operation
-
- You will normally use this with some code along
- these lines:
- \code
-signingObj.startSign(QCA::SecureMessage::Detached)
-signingObj.update(message);
-// perhaps some more update()s
-signingObj.end();
- \endcode
-
- For Detached signatures, you won't get any results
- until the whole process is done - you either
- waitForFinished(), or use the finished() signal, to
- figure out when you can get the signature (using
- the signature() method, not using read()). For
- other formats, you can use the readyRead() signal
- to determine when there may be part of a signed
- message to read().
-
- \param m the mode that will be used to generate the
- signature
- */
- void startSign(SignMode m = Message);
-
- /**
- Start a verification operation
-
- \param detachedSig the detached signature to
- verify. Do not pass a signature for other signature
- types.
- */
- void startVerify(const QByteArray &detachedSig = QByteArray());
-
- /**
- Start a combined signing and encrypting
- operation. You use this in the same way as
- startEncrypt().
-
- \note This may not be possible (e.g. CMS
- cannot do this) - see canSignAndEncrypt() for a
- suitable test.
- */
- void startSignAndEncrypt();
-
- /**
- Process a message (or the next part of a message)
- in the current operation. You need to have already
- set up the message (startEncrypt(), startDecrypt(),
- startSign(), startSignAndEncrypt() and
- startVerify()) before calling this method.
-
- \param in the data to process
- */
- void update(const QByteArray &in);
-
- /**
- Read the available data.
-
- \note For detached signatures, you don't get
- anything back using this method. Use signature() to
- get the detached signature().
- */
- QByteArray read();
-
- /**
- The number of bytes available to be read.
- */
- int bytesAvailable() const;
-
- /**
- Complete an operation.
-
- You need to call this method after you have
- processed the message (which you pass in as the
- argument to update().
-
- \note the results of the operation are not
- available as soon as this method returns. You need
- to wait for the finished() signal, or use
- waitForFinished().
- */
- void end();
-
- /**
- Block until the operation (encryption, decryption,
- signing or verifying) completes.
-
- \param msecs the number of milliseconds to wait for
- the operation to complete. Pass -1 to wait
- indefinitely.
-
- \note You should not use this in GUI
- applications where the blocking behaviour looks
- like a hung application. Instead, connect the
- finished() signal to a slot that handles the
- results.
-
- \note This synchronous operation may require event handling, and so
- it must not be called from the same thread as an EventHandler.
- */
- bool waitForFinished(int msecs = 30000);
-
- /**
- Indicates whether or not the operation was successful
- or failed. If this function returns false, then
- the reason for failure can be obtained with errorCode().
-
- \sa errorCode
- \sa diagnosticText
- */
- bool success() const;
-
- /**
- Returns the failure code.
-
- \sa success
- \sa diagnosticText
- */
- Error errorCode() const;
-
- /**
- The signature for the message. This is only used
- for Detached signatures. For other message types,
- you get the message and signature together using
- read().
- */
- QByteArray signature() const;
-
- /**
- The name of the hash used for the signature process
- */
- QString hashName() const;
-
- /**
- Test if the message was signed.
-
- This is true for OpenPGP if the decrypted message
- was also signed.
-
- \return true if the message was signed.
- */
- bool wasSigned() const;
-
- /**
- Verify that the message signature is correct.
-
- \return true if the signature is valid for the
- message, otherwise return false
- */
- bool verifySuccess() const;
-
- /**
- Information on the signer for the message
- */
- SecureMessageSignature signer() const;
-
- /**
- Information on the signers for the message.
-
- This is only meaningful if the message type supports
- multiple signatures (see canSignMultiple() for a
- suitable test).
- */
- SecureMessageSignatureList signers() const;
-
- /**
- Returns a log of technical information about the operation,
- which may be useful for presenting to the user in an
- advanced error dialog.
- */
- QString diagnosticText() const;
+ /**
+ The type of secure message
+ */
+ enum Type {
+ OpenPGP, ///< a Pretty Good Privacy message
+ CMS ///< a Cryptographic Message Syntax message
+ };
+
+ /**
+ The type of message signature
+ */
+ enum SignMode {
+ Message, ///< the message includes the signature
+ Clearsign, ///< the message is clear signed
+ Detached ///< the signature is detached
+ };
+
+ /**
+ Formats for secure messages
+ */
+ enum Format {
+ Binary, ///< DER/binary
+ Ascii ///< PEM/ascii-armored
+ };
+
+ /**
+ Errors for secure messages
+ */
+ enum Error {
+ ErrorPassphrase, ///< passphrase was either wrong or not provided
+ ErrorFormat, ///< input format was bad
+ ErrorSignerExpired, ///< signing key is expired
+ ErrorSignerInvalid, ///< signing key is invalid in some way
+ ErrorEncryptExpired, ///< encrypting key is expired
+ ErrorEncryptUntrusted, ///< encrypting key is untrusted
+ ErrorEncryptInvalid, ///< encrypting key is invalid in some way
+ ErrorNeedCard, ///< pgp card is missing
+ ErrorCertKeyMismatch, ///< certificate and private key don't match
+ ErrorUnknown, ///< other error
+ ErrorSignerRevoked, ///< signing key is revoked
+ ErrorSignatureExpired, ///< signature is expired
+ ErrorEncryptRevoked ///< encrypting key is revoked
+ };
+
+ /**
+ Create a new secure message
+
+ This constructor uses an existing
+ SecureMessageSystem object (for example, an OpenPGP
+ or CMS object) to generate a specific kind of
+ secure message.
+
+ \param system a pre-existing and configured SecureMessageSystem
+ object
+ */
+ SecureMessage(SecureMessageSystem *system);
+ ~SecureMessage();
+
+ /**
+ The Type of secure message
+ */
+ Type type() const;
+
+ /**
+ Test if the message type supports multiple
+ (parallel) signatures.
+
+ \return true if the secure message support multiple
+ parallel signatures
+
+ \note PGP cannot do this - it is primarily a CMS
+ feature
+ */
+ bool canSignMultiple() const;
+
+ /**
+ True if the SecureMessageSystem can clearsign
+ messages.
+
+ \note CMS cannot clearsign - this is normally only
+ available for PGP
+ */
+ bool canClearsign() const;
+
+ /**
+ True if the SecureMessageSystem can both sign and
+ encrypt (in the same operation).
+
+ \note CMS cannot do an integrated sign/encrypt -
+ this is normally only available for PGP. You can do
+ separate signing and encrypting operations on the
+ same message with CMS though.
+ */
+ bool canSignAndEncrypt() const;
+
+ /**
+ Reset the object state to that of original construction.
+ Now a new operation can be performed immediately.
+ */
+ void reset();
+
+ /**
+ Returns true if bundling of the signer certificate chain is
+ enabled
+ */
+ bool bundleSignerEnabled() const;
+
+ /**
+ Returns true if inclusion of S/MIME attributes is enabled
+ */
+ bool smimeAttributesEnabled() const;
+
+ /**
+ Return the format type set for this message
+ */
+ Format format() const;
+
+ /**
+ Return the recipient(s) set for this message with setRecipient() or
+ setRecipients()
+ */
+ SecureMessageKeyList recipientKeys() const;
+
+ /**
+ Return the signer(s) set for this message with setSigner() or
+ setSigners()
+ */
+ SecureMessageKeyList signerKeys() const;
+
+ /**
+ For CMS only, this will bundle the signer certificate chain
+ into the message. This allows a message to be verified
+ on its own, without the need to have obtained the signer's
+ certificate in advance. Email clients using S/MIME often
+ bundle the signer, greatly simplifying key management.
+
+ This behavior is enabled by default.
+
+ \param b whether to bundle (if true) or not (false)
+ */
+ void setBundleSignerEnabled(bool b);
+
+ /**
+ For CMS only, this will put extra attributes into the
+ message related to S/MIME, such as the preferred
+ type of algorithm to use in replies. The attributes
+ used are decided by the provider.
+
+ This behavior is enabled by default.
+
+ \param b whether to embed extra attribues (if true) or not (false)
+ */
+ void setSMIMEAttributesEnabled(bool b);
+
+ /**
+ Set the Format used for messages
+
+ The default is Binary.
+
+ \param f whether to use Binary or Ascii
+ */
+ void setFormat(Format f);
+
+ /**
+ Set the recipient for an encrypted message
+
+ \param key the recipient's key
+
+ \sa setRecipients
+ */
+ void setRecipient(const SecureMessageKey &key);
+
+ /**
+ Set the list of recipients for an encrypted message.
+
+ For a list with one item, this has the same effect as setRecipient.
+
+ \param keys the recipients' key
+
+ \sa setRecipient
+ */
+ void setRecipients(const SecureMessageKeyList &keys);
+
+ /**
+ Set the signer for a signed message.
+
+ This is used for both creating signed messages as well as for
+ verifying CMS messages that have no signer bundled.
+
+ \param key the key associated with the signer
+
+ \sa setSigners
+ */
+ void setSigner(const SecureMessageKey &key);
+
+ /**
+ Set the list of signers for a signed message.
+
+ This is used for both creating signed messages as well as for
+ verifying CMS messages that have no signer bundled.
+
+ For a list with one item, this has the same effect as setSigner.
+
+ \param keys the key associated with the signer
+
+ \sa setSigner
+ */
+ void setSigners(const SecureMessageKeyList &keys);
+
+ /**
+ Start an encryption operation
+
+ You will normally use this with some code along
+ these lines:
+ \code
+ encryptingObj.startEncrypt();
+ encryptingObj.update(message);
+ // perhaps some more update()s
+ encryptingObj.end();
+ \endcode
+
+ Each update() may (or may not) result in some
+ encrypted data, as indicated by the readyRead()
+ signal being emitted. Alternatively, you can wait
+ until the whole message is available (using either
+ waitForFinished(), or use the finished()
+ signal. The encrypted message can then be read
+ using the read() method.
+ */
+ void startEncrypt();
+
+ /**
+ Start an decryption operation
+
+ You will normally use this with some code along
+ these lines:
+ \code
+ decryptingObj.startEncrypt();
+ decryptingObj.update(message);
+ // perhaps some more update()s
+ decryptingObj.end();
+ \endcode
+
+ Each update() may (or may not) result in some
+ decrypted data, as indicated by the readyRead()
+ signal being emitted. Alternatively, you can wait
+ until the whole message is available (using either
+ waitForFinished(), or the finished()
+ signal). The decrypted message can then be read
+ using the read() method.
+
+ \note If decrypted result is also signed (not for
+ CMS), then the signature will be verified during
+ this operation.
+ */
+ void startDecrypt();
+
+ /**
+ Start a signing operation
+
+ You will normally use this with some code along
+ these lines:
+ \code
+ signingObj.startSign(QCA::SecureMessage::Detached)
+ signingObj.update(message);
+ // perhaps some more update()s
+ signingObj.end();
+ \endcode
+
+ For Detached signatures, you won't get any results
+ until the whole process is done - you either
+ waitForFinished(), or use the finished() signal, to
+ figure out when you can get the signature (using
+ the signature() method, not using read()). For
+ other formats, you can use the readyRead() signal
+ to determine when there may be part of a signed
+ message to read().
+
+ \param m the mode that will be used to generate the
+ signature
+ */
+ void startSign(SignMode m = Message);
+
+ /**
+ Start a verification operation
+
+ \param detachedSig the detached signature to
+ verify. Do not pass a signature for other signature
+ types.
+ */
+ void startVerify(const QByteArray &detachedSig = QByteArray());
+
+ /**
+ Start a combined signing and encrypting
+ operation. You use this in the same way as
+ startEncrypt().
+
+ \note This may not be possible (e.g. CMS
+ cannot do this) - see canSignAndEncrypt() for a
+ suitable test.
+ */
+ void startSignAndEncrypt();
+
+ /**
+ Process a message (or the next part of a message)
+ in the current operation. You need to have already
+ set up the message (startEncrypt(), startDecrypt(),
+ startSign(), startSignAndEncrypt() and
+ startVerify()) before calling this method.
+
+ \param in the data to process
+ */
+ void update(const QByteArray &in);
+
+ /**
+ Read the available data.
+
+ \note For detached signatures, you don't get
+ anything back using this method. Use signature() to
+ get the detached signature().
+ */
+ QByteArray read();
+
+ /**
+ The number of bytes available to be read.
+ */
+ int bytesAvailable() const;
+
+ /**
+ Complete an operation.
+
+ You need to call this method after you have
+ processed the message (which you pass in as the
+ argument to update().
+
+ \note the results of the operation are not
+ available as soon as this method returns. You need
+ to wait for the finished() signal, or use
+ waitForFinished().
+ */
+ void end();
+
+ /**
+ Block until the operation (encryption, decryption,
+ signing or verifying) completes.
+
+ \param msecs the number of milliseconds to wait for
+ the operation to complete. Pass -1 to wait
+ indefinitely.
+
+ \note You should not use this in GUI
+ applications where the blocking behaviour looks
+ like a hung application. Instead, connect the
+ finished() signal to a slot that handles the
+ results.
+
+ \note This synchronous operation may require event handling, and so
+ it must not be called from the same thread as an EventHandler.
+ */
+ bool waitForFinished(int msecs = 30000);
+
+ /**
+ Indicates whether or not the operation was successful
+ or failed. If this function returns false, then
+ the reason for failure can be obtained with errorCode().
+
+ \sa errorCode
+ \sa diagnosticText
+ */
+ bool success() const;
+
+ /**
+ Returns the failure code.
+
+ \sa success
+ \sa diagnosticText
+ */
+ Error errorCode() const;
+
+ /**
+ The signature for the message. This is only used
+ for Detached signatures. For other message types,
+ you get the message and signature together using
+ read().
+ */
+ QByteArray signature() const;
+
+ /**
+ The name of the hash used for the signature process
+ */
+ QString hashName() const;
+
+ /**
+ Test if the message was signed.
+
+ This is true for OpenPGP if the decrypted message
+ was also signed.
+
+ \return true if the message was signed.
+ */
+ bool wasSigned() const;
+
+ /**
+ Verify that the message signature is correct.
+
+ \return true if the signature is valid for the
+ message, otherwise return false
+ */
+ bool verifySuccess() const;
+
+ /**
+ Information on the signer for the message
+ */
+ SecureMessageSignature signer() const;
+
+ /**
+ Information on the signers for the message.
+
+ This is only meaningful if the message type supports
+ multiple signatures (see canSignMultiple() for a
+ suitable test).
+ */
+ SecureMessageSignatureList signers() const;
+
+ /**
+ Returns a log of technical information about the operation,
+ which may be useful for presenting to the user in an
+ advanced error dialog.
+ */
+ QString diagnosticText() const;
Q_SIGNALS:
- /**
- This signal is emitted when there is some data to
- read. Typically you connect this signal to a slot
- that does a read() of the available data.
-
- \note This signal does not mean that the processing
- of a message is necessarily complete - see
- finished().
- */
- void readyRead();
-
- /**
- This signal is emitted when data has been accepted
- by the message processor.
-
- \param bytes the number of bytes written
- */
- void bytesWritten(int bytes);
-
- /**
- This signal is emitted when the message is fully
- processed.
- */
- void finished();
+ /**
+ This signal is emitted when there is some data to
+ read. Typically you connect this signal to a slot
+ that does a read() of the available data.
+
+ \note This signal does not mean that the processing
+ of a message is necessarily complete - see
+ finished().
+ */
+ void readyRead();
+
+ /**
+ This signal is emitted when data has been accepted
+ by the message processor.
+
+ \param bytes the number of bytes written
+ */
+ void bytesWritten(int bytes);
+
+ /**
+ This signal is emitted when the message is fully
+ processed.
+ */
+ void finished();
private:
- Q_DISABLE_COPY(SecureMessage)
+ Q_DISABLE_COPY(SecureMessage)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class SecureMessageSystem qca_securemessage.h QtCrypto
Abstract superclass for secure messaging systems
\sa SecureMessage
\sa SecureMessageKey
\ingroup UserAPI
*/
class QCA_EXPORT SecureMessageSystem : public QObject, public Algorithm
{
- Q_OBJECT
+ Q_OBJECT
public:
- ~SecureMessageSystem();
+ ~SecureMessageSystem();
protected:
- /**
- Protected constructor for SecureMessageSystem
- classes. You are meant to be using a subclass (such
- as OpenPGP or CMS) - you only need to worry about
- this class if you are creating a whole new
- SecureMessageSystem type.
-
- \param parent the parent object for this object
- \param type the name of the Type of
- SecureMessageSystem to create
- \param provider the provider to use, if a specific
- provider is required.
- */
- SecureMessageSystem(QObject *parent, const QString &type, const QString &provider);
+ /**
+ Protected constructor for SecureMessageSystem
+ classes. You are meant to be using a subclass (such
+ as OpenPGP or CMS) - you only need to worry about
+ this class if you are creating a whole new
+ SecureMessageSystem type.
+
+ \param parent the parent object for this object
+ \param type the name of the Type of
+ SecureMessageSystem to create
+ \param provider the provider to use, if a specific
+ provider is required.
+ */
+ SecureMessageSystem(QObject *parent, const QString &type, const QString &provider);
private:
- Q_DISABLE_COPY(SecureMessageSystem)
+ Q_DISABLE_COPY(SecureMessageSystem)
};
/**
\class OpenPGP qca_securemessage.h QtCrypto
Pretty Good Privacy messaging system
\sa SecureMessage
\sa SecureMessageKey
\ingroup UserAPI
*/
class QCA_EXPORT OpenPGP : public SecureMessageSystem
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param parent the parent object for this object
- \param provider the provider to use, if a specific
- provider is required
- */
- explicit OpenPGP(QObject *parent = 0, const QString &provider = QString());
- ~OpenPGP();
+ \param parent the parent object for this object
+ \param provider the provider to use, if a specific
+ provider is required
+ */
+ explicit OpenPGP(QObject *parent = 0, const QString &provider = QString());
+ ~OpenPGP();
private:
- Q_DISABLE_COPY(OpenPGP)
+ Q_DISABLE_COPY(OpenPGP)
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class CMS qca_securemessage.h QtCrypto
Cryptographic Message Syntax messaging system
Cryptographic Message Syntax (%CMS) "is used to digitally
sign, digest, authenticate, or encrypt arbitrary message
content. The %CMS describes an encapsulation syntax for
data protection. It supports digital signatures and
encryption. The syntax allows multiple encapsulations; one
encapsulation envelope can be nested inside another.
Likewise, one party can digitally sign some previously
encapsulated data. It also allows arbitrary attributes,
such as signing time, to be signed along with the message
content, and provides for other attributes such as
countersignatures to be associated with a signature." (from
<a href="http://www.ietf.org/rfc/rfc3852.txt">RFC3852</a>
"Cryptographic Message Syntax")
\sa SecureMessage
\sa SecureMessageKey
\ingroup UserAPI
*/
class QCA_EXPORT CMS : public SecureMessageSystem
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param parent the parent object for this object
- \param provider the provider to use, if a specific
- provider is required
- */
- explicit CMS(QObject *parent = 0, const QString &provider = QString());
- ~CMS();
-
- /**
- Return the trusted certificates set for this object
- */
- CertificateCollection trustedCertificates() const;
-
- /**
- Return the untrusted certificates set for this object
- */
- CertificateCollection untrustedCertificates() const;
-
- /**
- Return the private keys set for this object
- */
- SecureMessageKeyList privateKeys() const;
-
- /**
- Set the trusted certificates to use for the
- messages built using this CMS object.
-
- \param trusted the collection of trusted
- certificates to use
- */
- void setTrustedCertificates(const CertificateCollection &trusted);
-
- /**
- Set the untrusted certificates to use for the
- messages built using this CMS object.
-
- This function is useful when verifying messages that don't
- contain the certificates (or intermediate signers) within
- the CMS blob. In order to verify such messages, you'll
- have to pass the possible signer certs with this function.
-
- \param untrusted the collection of untrusted
- certificates to use
- */
- void setUntrustedCertificates(const CertificateCollection &untrusted);
-
- /**
- Set the private keys to use for the messages built
- using this CMS object.
-
- Keys are required for decrypting and signing (not
- for encrypting or verifying).
-
- \param keys the collection of keys to use
- */
- void setPrivateKeys(const SecureMessageKeyList &keys);
+ /**
+ Standard constructor
+
+ \param parent the parent object for this object
+ \param provider the provider to use, if a specific
+ provider is required
+ */
+ explicit CMS(QObject *parent = 0, const QString &provider = QString());
+ ~CMS();
+
+ /**
+ Return the trusted certificates set for this object
+ */
+ CertificateCollection trustedCertificates() const;
+
+ /**
+ Return the untrusted certificates set for this object
+ */
+ CertificateCollection untrustedCertificates() const;
+
+ /**
+ Return the private keys set for this object
+ */
+ SecureMessageKeyList privateKeys() const;
+
+ /**
+ Set the trusted certificates to use for the
+ messages built using this CMS object.
+
+ \param trusted the collection of trusted
+ certificates to use
+ */
+ void setTrustedCertificates(const CertificateCollection &trusted);
+
+ /**
+ Set the untrusted certificates to use for the
+ messages built using this CMS object.
+
+ This function is useful when verifying messages that don't
+ contain the certificates (or intermediate signers) within
+ the CMS blob. In order to verify such messages, you'll
+ have to pass the possible signer certs with this function.
+
+ \param untrusted the collection of untrusted
+ certificates to use
+ */
+ void setUntrustedCertificates(const CertificateCollection &untrusted);
+
+ /**
+ Set the private keys to use for the messages built
+ using this CMS object.
+
+ Keys are required for decrypting and signing (not
+ for encrypting or verifying).
+
+ \param keys the collection of keys to use
+ */
+ void setPrivateKeys(const SecureMessageKeyList &keys);
private:
- Q_DISABLE_COPY(CMS)
+ Q_DISABLE_COPY(CMS)
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
}
#endif
diff --git a/include/QtCrypto/qca_support.h b/include/QtCrypto/qca_support.h
index 9f5d364d..8fbdf9ec 100644
--- a/include/QtCrypto/qca_support.h
+++ b/include/QtCrypto/qca_support.h
@@ -1,1111 +1,1110 @@
/*
* qca_support.h - Qt Cryptographic Architecture
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004,2005, 2007 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_support.h
Header file for "support" classes used in %QCA
The classes in this header do not have any cryptographic
content - they are used in %QCA, and are included for convenience.
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_SUPPORT_H
#define QCA_SUPPORT_H
#include <QByteArray>
#include <QString>
#include <QObject>
#include <QVariant>
#include <QVariantList>
#include <QStringList>
#include <QList>
#include <QMetaObject>
#include <QThread>
#include "qca_export.h"
#include "qca_tools.h"
-namespace QCA {
+namespace QCA
+{
/**
Convenience method to determine the return type of a method
This function identifies the return type of a specified
method. This function can be used as shown:
\code
class TestClass : public QObject
{
Q_OBJECT
// ...
public slots:
QString qstringMethod() { return QString(); };
bool boolMethod( const QString & ) { return true; };
};
QByteArray myTypeName;
TestClass testClass;
QList<QByteArray> argsList; // empty list, since no args
myTypeName = QCA::methodReturnType( testClass.metaObject(), QByteArray( "qstringMethod" ), argsList );
// myTypeName is "QString"
myTypeName = QCA::methodReturnType( testClass.metaObject(), QByteArray( "boolMethod" ), argsList );
// myTypeName is "", because there is no method called "boolMethod" that has no arguments
argsList << "QString"; // now we have one argument
myTypeName = QCA::methodReturnType( testClass.metaObject(), QByteArray( "boolMethod" ), argsList );
// myTypeName is "bool"
\endcode
The return type name of a method returning void is an empty string, not "void"
\note This function is not normally required for use with
%QCA. It is provided for use in your code, if required.
\param obj the QMetaObject for the object
\param method the name of the method (without the arguments or brackets)
- \param argTypes the list of argument types of the method
+ \param argTypes the list of argument types of the method
\return the name of the type that this method will return with the specified
argument types.
\sa QMetaType for more information on the Qt meta type system.
\relates SyncThread
*/
QCA_EXPORT QByteArray methodReturnType(const QMetaObject *obj, const QByteArray &method, const QList<QByteArray> argTypes);
/**
Convenience method to invoke a method by name, using a variant
list of arguments.
This function can be used as shown:
\code
class TestClass : public QObject
{
Q_OBJECT
// ...
public slots:
QString qstringMethod() { return QString( "the result" ); };
bool boolMethod( const QString & ) { return true; };
};
TestClass *testClass = new TestClass;
QVariantList args;
QVariant stringRes;
// calls testClass->qstringMethod() with no arguments ( since args is an empty list)
bool ret = QCA::invokeMethodWithVariants( testClass, QByteArray( "qstringMethod" ), args, &stringRes );
// ret is true (since call succeeded), stringRes.toString() is a string - "the result"
QVariant boolResult;
QString someString( "not important" );
args << someString;
// calls testClass->boolMethod( someString ), returning result in boolResult
ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "boolMethod" ), args, &boolResult );
// ret is true (since call succeeded), boolResult.toBool() is true.
\endcode
\param obj the object to call the method on
\param method the name of the method (without the arguments or brackets)
\param args the list of arguments to use in the method call
\param ret the return value of the method (unchanged if the call fails)
\param type the type of connection to use
\return true if the call succeeded, otherwise false
\relates SyncThread
*/
QCA_EXPORT bool invokeMethodWithVariants(QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type = Qt::AutoConnection);
/**
\class SyncThread qca_support.h QtCrypto
Convenience class to run a thread and interact with it synchronously
SyncThread makes it easy to perform the common practice of starting a
thread, running some objects in that thread, and then interacting with
those objects safely. Often, there is no need to directly use threading
primitives (e.g. QMutex), resulting in very clean multi-threaded code.
\note The following is an excerpt from
http://delta.affinix.com/2006/11/13/synchronized-threads-part-3/
---<br>
With SyncThread, you can start, stop, and call a method in another thread
while the main thread sleeps. The only requirement is that the methods be
declared as slots.
Below is a contrived example, where we have an object in another thread
that increments a counter over a some interval, using the Qt event loop,
and provides a method to inspect the value.
First, the Counter object:
\code
class Counter : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private:
- int x;
- QTimer timer;
+ int x;
+ QTimer timer;
public:
- Counter() : timer(this)
- {
- x = 0;
- connect(&timer, SIGNAL(timeout()), SLOT(t_timeout()));
- }
+ Counter() : timer(this)
+ {
+ x = 0;
+ connect(&timer, SIGNAL(timeout()), SLOT(t_timeout()));
+ }
public slots:
- void start(int seconds)
- {
- timer.setInterval(seconds * 1000);
- timer.start();
- }
+ void start(int seconds)
+ {
+ timer.setInterval(seconds * 1000);
+ timer.start();
+ }
- int value() const
- {
- return x;
- }
+ int value() const
+ {
+ return x;
+ }
private slots:
- void t_timeout()
- {
- ++x;
- }
+ void t_timeout()
+ {
+ ++x;
+ }
};
\endcode
Looks like a typical object, no surprises.
Now to wrap Counter with SyncThread. We went over how to do this in the
first article, and it is very straightforward:
\code
class CounterThread : public SyncThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- Counter *counter;
-
- CounterThread(QObject *parent) : SyncThread(parent)
- {
- counter = 0;
- }
-
- ~CounterThread()
- {
- // SyncThread will stop the thread on destruct, but since our
- // atStop() function makes references to CounterThread's
- // members, we need to shutdown here, before CounterThread
- // destructs.
- stop();
- }
+ Counter *counter;
+
+ CounterThread(QObject *parent) : SyncThread(parent)
+ {
+ counter = 0;
+ }
+
+ ~CounterThread()
+ {
+ // SyncThread will stop the thread on destruct, but since our
+ // atStop() function makes references to CounterThread's
+ // members, we need to shutdown here, before CounterThread
+ // destructs.
+ stop();
+ }
protected:
- virtual void atStart()
- {
- counter = new Counter;
- }
-
- virtual void atStop()
- {
- delete counter;
- }
+ virtual void atStart()
+ {
+ counter = new Counter;
+ }
+
+ virtual void atStop()
+ {
+ delete counter;
+ }
};
\endcode
We can then use it like this:
\code
CounterThread *thread = new CounterThread;
// after this call, the thread is started and the Counter is ready
thread->start();
// let's start the counter with a 1 second interval
thread->call(thread->counter, "start", QVariantList() << 1);
...
// after some time passes, let's check on the value
int x = thread->call(thread->counter, "value").toInt();
// we're done with this thing
delete thread;
\endcode
Do you see a mutex anywhere? I didn't think so.<br>
---
Even without the call() function, SyncThread is still very useful
for preparing objects in another thread, which you can then
QObject::connect() to and use signals and slots like normal.
\ingroup UserAPI
*/
class QCA_EXPORT SyncThread : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param parent the parent object for this parent.
- */
- SyncThread(QObject *parent = 0);
-
- /**
- Calls stop() and then destructs
-
- \note Subclasses should call stop() in their own destructor
- */
- ~SyncThread();
-
- /**
- Starts the thread, begins the event loop the thread, and then
- calls atStart() in the thread. This function will block until
- atStart() has returned.
- */
- void start();
-
- /**
- Stops the event loop of the thread, calls atStop() in the thread,
- and instructs the thread to finish. This function will block
- until the thread has finished.
- */
- void stop();
-
- /**
- Calls a slot of an object in the thread. This function will block
- until the slot has returned.
-
- It is possible for the call to fail, for example if the method
- does not exist.
-
- The arguments and return value of the call use QVariant. If the
- method has no return value (returns void), then the returned
- QVariant will be null.
-
- \param obj the object to call the method on
- \param method the name of the method (without the arguments or
- brackets)
- \param args the list of arguments to use in the method call
- \param ok if not 0, true is stored here if the call succeeds,
- otherwise false is stored here.
- */
- QVariant call(QObject *obj, const QByteArray &method, const QVariantList &args = QVariantList(), bool *ok = 0);
+ /**
+ Standard constructor
+
+ \param parent the parent object for this parent.
+ */
+ SyncThread(QObject *parent = 0);
+
+ /**
+ Calls stop() and then destructs
+
+ \note Subclasses should call stop() in their own destructor
+ */
+ ~SyncThread();
+
+ /**
+ Starts the thread, begins the event loop the thread, and then
+ calls atStart() in the thread. This function will block until
+ atStart() has returned.
+ */
+ void start();
+
+ /**
+ Stops the event loop of the thread, calls atStop() in the thread,
+ and instructs the thread to finish. This function will block
+ until the thread has finished.
+ */
+ void stop();
+
+ /**
+ Calls a slot of an object in the thread. This function will block
+ until the slot has returned.
+
+ It is possible for the call to fail, for example if the method
+ does not exist.
+
+ The arguments and return value of the call use QVariant. If the
+ method has no return value (returns void), then the returned
+ QVariant will be null.
+
+ \param obj the object to call the method on
+ \param method the name of the method (without the arguments or
+ brackets)
+ \param args the list of arguments to use in the method call
+ \param ok if not 0, true is stored here if the call succeeds,
+ otherwise false is stored here.
+ */
+ QVariant call(QObject *obj, const QByteArray &method, const QVariantList &args = QVariantList(), bool *ok = 0);
protected:
- /**
- Reimplement this to perform your initialization
- */
- virtual void atStart() = 0;
+ /**
+ Reimplement this to perform your initialization
+ */
+ virtual void atStart() = 0;
- /**
- Reimplement this to perform your deinitialization
- */
- virtual void atEnd() = 0;
+ /**
+ Reimplement this to perform your deinitialization
+ */
+ virtual void atEnd() = 0;
- /**
- Starts the event loop and calls atStart and atStop as necessary
- */
- virtual void run();
+ /**
+ Starts the event loop and calls atStart and atStop as necessary
+ */
+ virtual void run();
private:
- Q_DISABLE_COPY(SyncThread)
+ Q_DISABLE_COPY(SyncThread)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class Synchronizer qca_support.h QtCrypto
Enable synchronization between two threads.
*/
class QCA_EXPORT Synchronizer : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param parent the parent object to this object
- */
- Synchronizer(QObject *parent);
- ~Synchronizer();
+ \param parent the parent object to this object
+ */
+ Synchronizer(QObject *parent);
+ ~Synchronizer();
- /**
- Call to pause execution in this thread. This function
- will block until conditionMet() is called.
+ /**
+ Call to pause execution in this thread. This function
+ will block until conditionMet() is called.
- \param msecs the time to wait before proceeding. The default
- timeout value (-1) indicates to wait indefinitely.
- */
- bool waitForCondition(int msecs = -1);
+ \param msecs the time to wait before proceeding. The default
+ timeout value (-1) indicates to wait indefinitely.
+ */
+ bool waitForCondition(int msecs = -1);
- /**
- Call to continue execution in the paused thread.
- */
- void conditionMet();
+ /**
+ Call to continue execution in the paused thread.
+ */
+ void conditionMet();
private:
- Q_DISABLE_COPY(Synchronizer)
+ Q_DISABLE_COPY(Synchronizer)
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
/**
\class DirWatch qca_support.h QtCrypto
Support class to monitor a directory for activity.
%DirWatch monitors a specified file for any changes. When
the directory changes, the changed() signal is emitted.
\note QFileSystemWatcher has very similar functionality
- to this class. You should evaluate this class and
+ to this class. You should evaluate this class and
QFileSystemWatcher to determine which better suits your
application needs.
\ingroup UserAPI
*/
class QCA_EXPORT DirWatch : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param dir the name of the directory to watch. If not
- set in the constructor, you can set it using setDirName()
- \param parent the parent object for this object
- */
- explicit DirWatch(const QString &dir = QString(), QObject *parent = 0);
- ~DirWatch();
+ \param dir the name of the directory to watch. If not
+ set in the constructor, you can set it using setDirName()
+ \param parent the parent object for this object
+ */
+ explicit DirWatch(const QString &dir = QString(), QObject *parent = 0);
+ ~DirWatch();
- /**
- The name of the directory that is being monitored
- */
- QString dirName() const;
+ /**
+ The name of the directory that is being monitored
+ */
+ QString dirName() const;
- /**
- Change the directory being monitored
+ /**
+ Change the directory being monitored
- \param dir the name of the directory to monitor
- */
- void setDirName(const QString &dir);
+ \param dir the name of the directory to monitor
+ */
+ void setDirName(const QString &dir);
Q_SIGNALS:
- /**
- The changed signal is emitted when the directory is
- changed (e.g. modified by addition or deletion of a
- file within the directory, or the deletion of the
- directory)
- */
- void changed();
+ /**
+ The changed signal is emitted when the directory is
+ changed (e.g. modified by addition or deletion of a
+ file within the directory, or the deletion of the
+ directory)
+ */
+ void changed();
private:
- Q_DISABLE_COPY(DirWatch)
+ Q_DISABLE_COPY(DirWatch)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class FileWatch qca_support.h QtCrypto
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.
\note QFileSystemWatcher has very similar functionality
- to this class. You should evaluate this class and
+ to this class. You should evaluate this class and
QFileSystemWatcher to determine which better suits your
application needs.
\ingroup UserAPI
*/
class QCA_EXPORT FileWatch : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ 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();
+ \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;
+ /**
+ The name of the file that is being monitored
+ */
+ QString fileName() const;
- /**
- Change the file being monitored
+ /**
+ Change the file being monitored
- \param file the name of the file to monitor
- */
- void setFileName(const QString &file);
+ \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();
+ /**
+ The changed signal is emitted when the file is
+ changed (e.g. modified, deleted)
+ */
+ void changed();
private:
- Q_DISABLE_COPY(FileWatch)
+ Q_DISABLE_COPY(FileWatch)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
class ConsolePrivate;
class ConsoleReferencePrivate;
class ConsoleReference;
/**
\class Console qca_support.h QtCrypto
%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 takes over either the physical console (Console::Tty
type) or stdin/stdout (Console::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.
The reason why there is a master console object 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
%Console back to standard functions (e.g. fgets() ).
\ingroup UserAPI
*/
class QCA_EXPORT Console : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The type of console object
- */
- enum Type
- {
- Tty, ///< physical console
- Stdio ///< stdin/stdout
- };
- /**
- The type of I/O to use with the console object.
- */
- enum ChannelMode
- {
- Read, ///< Read only (equivalent to stdin)
- ReadWrite ///< Read/write (equivalent to stdin and stdout)
- };
-
- /**
- The nature of the console operation
- */
- enum TerminalMode
- {
- Default, ///< use default terminal settings
- Interactive ///< char-by-char input, no echo
- };
-
- /**
- Standard constructor
-
- Note that library code should not create a new Console object
- without checking whether there is already a Console object of
- the required Type. See the main documentation for Console for the
- rationale for this.
-
- \param type the Type of Console object to create
- \param cmode the ChannelMode (I/O type) to use
- \param tmode the TerminalMode to use
- \param parent the parent object for this object
-
- \sa ttyInstance() and stdioInstance for static methods that allow
- you to test whether there is already a Console object of the
- required Type, and if there is, obtain a reference to that object.
- */
- Console(Type type, ChannelMode cmode, TerminalMode tmode, QObject *parent = 0);
- ~Console();
-
- /**
- The Type of this Console object
- */
- Type type() const;
-
- /**
- The ChannelMode of this Console object
- */
- ChannelMode channelMode() const;
-
- /**
- The TerminalMode of this Console object
- */
- TerminalMode terminalMode() const;
-
- /**
- Test whether standard input is redirected.
-
- \sa type() and channelMode()
- */
- static bool isStdinRedirected();
-
- /**
- Test whether standard output is redirected.
-
- \sa type() and channelMode()
- */
- static bool isStdoutRedirected();
-
- /**
- The current terminal-type console object
-
- \return null if there is no current Console
- of this type, otherwise the Console to use
- */
- static Console *ttyInstance();
-
- /**
- The current stdio-type console object
-
- \return null if there is no current Console
- of this type, otherwise the Console to use
- */
- static Console *stdioInstance();
-
- /**
- Release the Console
-
- This allows access to buffers containing any remaining data
- */
- void release();
-
- /**
- Obtain remaining data from the Console, awaiting
- a read operation
- */
- QByteArray bytesLeftToRead();
-
- /**
- Obtain remaining data from the Console, awaiting
- a write operation
- */
- QByteArray bytesLeftToWrite();
+ /**
+ The type of console object
+ */
+ enum Type {
+ Tty, ///< physical console
+ Stdio ///< stdin/stdout
+ };
+ /**
+ The type of I/O to use with the console object.
+ */
+ enum ChannelMode {
+ Read, ///< Read only (equivalent to stdin)
+ ReadWrite ///< Read/write (equivalent to stdin and stdout)
+ };
+
+ /**
+ The nature of the console operation
+ */
+ enum TerminalMode {
+ Default, ///< use default terminal settings
+ Interactive ///< char-by-char input, no echo
+ };
+
+ /**
+ Standard constructor
+
+ Note that library code should not create a new Console object
+ without checking whether there is already a Console object of
+ the required Type. See the main documentation for Console for the
+ rationale for this.
+
+ \param type the Type of Console object to create
+ \param cmode the ChannelMode (I/O type) to use
+ \param tmode the TerminalMode to use
+ \param parent the parent object for this object
+
+ \sa ttyInstance() and stdioInstance for static methods that allow
+ you to test whether there is already a Console object of the
+ required Type, and if there is, obtain a reference to that object.
+ */
+ Console(Type type, ChannelMode cmode, TerminalMode tmode, QObject *parent = 0);
+ ~Console();
+
+ /**
+ The Type of this Console object
+ */
+ Type type() const;
+
+ /**
+ The ChannelMode of this Console object
+ */
+ ChannelMode channelMode() const;
+
+ /**
+ The TerminalMode of this Console object
+ */
+ TerminalMode terminalMode() const;
+
+ /**
+ Test whether standard input is redirected.
+
+ \sa type() and channelMode()
+ */
+ static bool isStdinRedirected();
+
+ /**
+ Test whether standard output is redirected.
+
+ \sa type() and channelMode()
+ */
+ static bool isStdoutRedirected();
+
+ /**
+ The current terminal-type console object
+
+ \return null if there is no current Console
+ of this type, otherwise the Console to use
+ */
+ static Console *ttyInstance();
+
+ /**
+ The current stdio-type console object
+
+ \return null if there is no current Console
+ of this type, otherwise the Console to use
+ */
+ static Console *stdioInstance();
+
+ /**
+ Release the Console
+
+ This allows access to buffers containing any remaining data
+ */
+ void release();
+
+ /**
+ Obtain remaining data from the Console, awaiting
+ a read operation
+ */
+ QByteArray bytesLeftToRead();
+
+ /**
+ Obtain remaining data from the Console, awaiting
+ a write operation
+ */
+ QByteArray bytesLeftToWrite();
private:
- Q_DISABLE_COPY(Console)
+ Q_DISABLE_COPY(Console)
- friend class ConsolePrivate;
- ConsolePrivate *d;
+ friend class ConsolePrivate;
+ ConsolePrivate *d;
- friend class ConsoleReference;
+ friend class ConsoleReference;
};
/**
\class ConsoleReference qca_support.h QtCrypto
Manager for a Console
\note Only one %ConsoleReference object can be active at a time
\ingroup UserAPI
*/
class QCA_EXPORT ConsoleReference : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The security setting to use for the Console being managed.
- */
- enum SecurityMode
- {
- SecurityDisabled,
- SecurityEnabled
- };
+ /**
+ The security setting to use for the Console being managed.
+ */
+ enum SecurityMode {
+ SecurityDisabled,
+ SecurityEnabled
+ };
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param parent the parent object for this object
- */
- ConsoleReference(QObject *parent = 0);
- ~ConsoleReference();
+ \param parent the parent object for this object
+ */
+ ConsoleReference(QObject *parent = 0);
+ ~ConsoleReference();
- /**
- Set the Console object to be managed, and start processing.
+ /**
+ Set the Console object to be managed, and start processing.
- You typically want to use Console::ttyInstance() or
- Console::stdioInstance() to obtain the required Console
- reference.
+ You typically want to use Console::ttyInstance() or
+ Console::stdioInstance() to obtain the required Console
+ reference.
- \param console reference to the Console to be managed
- \param mode the SecurityMode to use for this Console.
+ \param console reference to the Console to be managed
+ \param mode the SecurityMode to use for this Console.
- \sa QCA::Console for more information on how to handle the
- console aspects of your application or library code.
- */
- bool start(Console *console, SecurityMode mode = SecurityDisabled);
+ \sa QCA::Console for more information on how to handle the
+ console aspects of your application or library code.
+ */
+ bool start(Console *console, SecurityMode mode = SecurityDisabled);
- /**
- Stop processing, and release the Console
- */
- void stop();
+ /**
+ Stop processing, and release the Console
+ */
+ void stop();
- /**
- The Console object managed by this object
+ /**
+ The Console object managed by this object
- \sa start() to set the Console to be managed
- */
- Console *console() const;
+ \sa start() to set the Console to be managed
+ */
+ Console *console() const;
- /**
- The security mode setting for the Console object
- managed by this object.
+ /**
+ The security mode setting for the Console object
+ managed by this object.
- \sa start() to set the SecurityMode
- */
- SecurityMode securityMode() const;
+ \sa start() to set the SecurityMode
+ */
+ SecurityMode securityMode() const;
- /**
- Read data from the Console.
+ /**
+ Read data from the Console.
- \param bytes the number of bytes to read. The default
- is to read all available bytes
+ \param bytes the number of bytes to read. The default
+ is to read all available bytes
- \sa readSecure() for a method suitable for reading
- sensitive data.
- */
- QByteArray read(int bytes = -1);
+ \sa readSecure() for a method suitable for reading
+ sensitive data.
+ */
+ QByteArray read(int bytes = -1);
- /**
- Write data to the Console.
+ /**
+ Write data to the Console.
- \param a the array of data to write to the Console
+ \param a the array of data to write to the Console
- \sa writeSecure() for a method suitable for writing
- sensitive data.
- */
- void write(const QByteArray &a);
+ \sa writeSecure() for a method suitable for writing
+ sensitive data.
+ */
+ void write(const QByteArray &a);
- /**
- Read secure data from the Console
+ /**
+ Read secure data from the Console
- \param bytes the number of bytes to read. The default
- is to read all available bytes
+ \param bytes the number of bytes to read. The default
+ is to read all available bytes
- \sa read() which is suitable for non-sensitive data
- */
- SecureArray readSecure(int bytes = -1);
+ \sa read() which is suitable for non-sensitive data
+ */
+ SecureArray readSecure(int bytes = -1);
- /**
- Write secure data to the Console
+ /**
+ Write secure data to the Console
- \param a the array of data to write to the Console
+ \param a the array of data to write to the Console
- \sa write() which is suitable for non-sensitive data
- */
- void writeSecure(const SecureArray &a);
+ \sa write() which is suitable for non-sensitive data
+ */
+ void writeSecure(const SecureArray &a);
- /**
- Close the write channel
+ /**
+ Close the write channel
- You only need to call this if writing is enabled
- on the Console being managed.
- */
- void closeOutput();
+ You only need to call this if writing is enabled
+ on the Console being managed.
+ */
+ void closeOutput();
- /**
- The number of bytes available to read from the
- Console being managed.
- */
- int bytesAvailable() const;
+ /**
+ The number of bytes available to read from the
+ Console being managed.
+ */
+ int bytesAvailable() const;
- /**
- The number of bytes remaining to be written
- to the Console being managed
- */
- int bytesToWrite() const;
+ /**
+ The number of bytes remaining to be written
+ to the Console being managed
+ */
+ int bytesToWrite() const;
Q_SIGNALS:
- /**
- Emitted when there are bytes available to read from
- the Console being managed
- */
- void readyRead();
+ /**
+ Emitted when there are bytes available to read from
+ the Console being managed
+ */
+ void readyRead();
- /**
- Emitted when bytes are written to the Console
+ /**
+ Emitted when bytes are written to the Console
- \param bytes the number of bytes that were written
+ \param bytes the number of bytes that were written
- \sa bytesAvailable()
- */
- void bytesWritten(int bytes);
+ \sa bytesAvailable()
+ */
+ void bytesWritten(int bytes);
- /**
- Emitted when the console input is closed
- */
- void inputClosed();
+ /**
+ Emitted when the console input is closed
+ */
+ void inputClosed();
- /**
- Emitted when the console output is closed
- */
- void outputClosed();
+ /**
+ Emitted when the console output is closed
+ */
+ void outputClosed();
private:
- Q_DISABLE_COPY(ConsoleReference)
+ Q_DISABLE_COPY(ConsoleReference)
- friend class ConsoleReferencePrivate;
- ConsoleReferencePrivate *d;
+ friend class ConsoleReferencePrivate;
+ ConsoleReferencePrivate *d;
- friend class Console;
+ friend class Console;
};
/**
\class ConsolePrompt qca_support.h QtCrypto
Console prompt handler.
This class provides a convenient way to get user input in a secure way,
as shown below:
\code
QCA::ConsolePrompt prompt;
prompt.getHidden("Passphrase");
prompt.waitForFinished();
QCA:SecureArray pass = prompt.result();
\endcode
\note It is not necessary to use waitForFinished(), because you can
just connect the finished() signal to a suitable method, however
command line (console) applications often require waitForFinished().
\ingroup UserAPI
*/
class QCA_EXPORT ConsolePrompt : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param parent the parent object for this object
- */
- ConsolePrompt(QObject *parent = 0);
- ~ConsolePrompt();
+ \param parent the parent object for this object
+ */
+ ConsolePrompt(QObject *parent = 0);
+ ~ConsolePrompt();
- /**
- Allow the user to enter data without it being echo'd to
- the terminal. This is particularly useful for entry
- of passwords, passphrases and PINs.
+ /**
+ Allow the user to enter data without it being echo'd to
+ the terminal. This is particularly useful for entry
+ of passwords, passphrases and PINs.
- \param promptStr the prompt to display to the user
+ \param promptStr the prompt to display to the user
- \sa result() for how to get the input back.
- */
- void getHidden(const QString &promptStr);
+ \sa result() for how to get the input back.
+ */
+ void getHidden(const QString &promptStr);
- /**
- Obtain one character from the user
+ /**
+ Obtain one character from the user
- \sa resultChar() for how to get the input back.
- */
- void getChar();
+ \sa resultChar() for how to get the input back.
+ */
+ void getChar();
- /**
- Block waiting for user input.
+ /**
+ Block waiting for user input.
- You may wish to use the finished() signal to
- avoid blocking.
- */
- void waitForFinished();
+ You may wish to use the finished() signal to
+ avoid blocking.
+ */
+ void waitForFinished();
- /**
- Obtain the result of the user input.
+ /**
+ Obtain the result of the user input.
- This method is usually called to obtain data
- from the user that was requested by the getHidden()
- call.
- */
- SecureArray result() const;
+ This method is usually called to obtain data
+ from the user that was requested by the getHidden()
+ call.
+ */
+ SecureArray result() const;
- /**
- Obtain the result of the user input.
+ /**
+ Obtain the result of the user input.
- This method is usually called to obtain data
- from the user that was requested by the getChar()
- call.
- */
- QChar resultChar() const;
+ This method is usually called to obtain data
+ from the user that was requested by the getChar()
+ call.
+ */
+ QChar resultChar() const;
Q_SIGNALS:
- /**
- Emitted when the user input activity has been
- completed.
+ /**
+ Emitted when the user input activity has been
+ completed.
- This corresponds to the provision of a string
- for getHidden() or a single character for getChar().
+ This corresponds to the provision of a string
+ for getHidden() or a single character for getChar().
- \sa waitForFinished
- */
- void finished();
+ \sa waitForFinished
+ */
+ void finished();
private:
- Q_DISABLE_COPY(ConsolePrompt)
+ Q_DISABLE_COPY(ConsolePrompt)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
class AbstractLogDevice;
/**
\class Logger qca_support.h QtCrypto
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).
\ingroup UserAPI
*/
class QCA_EXPORT Logger : public QObject
{
- Q_OBJECT
+ 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 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(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;
+ /**
+ 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 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(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)
+ Q_DISABLE_COPY(Logger)
- friend class Global;
+ friend class Global;
- /**
- Create a new message logger
- */
- Logger();
+ /**
+ Create a new message logger
+ */
+ Logger();
- ~Logger();
+ ~Logger();
- QStringList m_loggerNames;
- QList<AbstractLogDevice*> m_loggers;
- Severity m_logLevel;
+ QStringList m_loggerNames;
+ QList<AbstractLogDevice *> m_loggers;
+ Severity m_logLevel;
};
/**
\class AbstractLogDevice qca_support.h QtCrypto
An abstract log device
\ingroup UserAPI
*/
class QCA_EXPORT AbstractLogDevice : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The name of this log device
- */
- QString name() const;
+ /**
+ The name of this log device
+ */
+ QString name() const;
- /**
- Log a message
+ /**
+ Log a message
- The default implementation does nothing - you should
- override this method in your subclass to do whatever
- logging is required
+ The default implementation does nothing - you should
+ override this method in your subclass to do whatever
+ logging is required
- \param message the message to log
- \param severity the severity level of the message
- */
- virtual void logTextMessage(const QString &message, Logger::Severity severity);
+ \param message the message to log
+ \param severity the severity level of the message
+ */
+ virtual void logTextMessage(const QString &message, Logger::Severity severity);
- /**
- Log a binary blob
+ /**
+ Log a binary blob
- The default implementation does nothing - you should
- override this method in your subclass to do whatever
- logging is required
+ The default implementation does nothing - you should
+ override this method in your subclass to do whatever
+ logging is required
- \param blob the message (as a byte array) to log
- \param severity the severity level of the message
- */
- virtual void logBinaryMessage(const QByteArray &blob, Logger::Severity severity);
+ \param blob the message (as a byte array) to log
+ \param severity the severity level of the message
+ */
+ virtual void logBinaryMessage(const QByteArray &blob, Logger::Severity severity);
protected:
- /**
- Create a new message logger
+ /**
+ 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);
+ \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;
+ virtual ~AbstractLogDevice() = 0;
private:
- Q_DISABLE_COPY(AbstractLogDevice)
+ Q_DISABLE_COPY(AbstractLogDevice)
- class Private;
- Private *d;
+ class Private;
+ Private *d;
- QString m_name;
+ QString m_name;
};
}
#endif
diff --git a/include/QtCrypto/qca_textfilter.h b/include/QtCrypto/qca_textfilter.h
index 49dfa75c..80943f99 100644
--- a/include/QtCrypto/qca_textfilter.h
+++ b/include/QtCrypto/qca_textfilter.h
@@ -1,327 +1,328 @@
/*
* qca_textfilter.h - Qt Cryptographic Architecture
* Copyright (C) 2003-2005 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_textfilter.h
Header file for text encoding/decoding classes
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_TEXTFILTER_H
#define QCA_TEXTFILTER_H
#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
+ of an algorithm that works in two directions, and
supports operations on QString arguments.
\ingroup UserAPI
*/
class QCA_EXPORT TextFilter : public Filter
{
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param dir the Direction that this TextFilter
- should use.
- */
- TextFilter(Direction dir);
+ \param dir the Direction that this TextFilter
+ should use.
+ */
+ TextFilter(Direction dir);
- /**
- Reset the TextFilter
+ /**
+ Reset the TextFilter
- \param dir the Direction that this TextFilter
- should use.
- */
- void setup(Direction dir);
+ \param dir the Direction that this TextFilter
+ should use.
+ */
+ void setup(Direction dir);
- /**
- The direction the TextFilter is set up to use
- */
- Direction direction() const;
+ /**
+ The direction the TextFilter is set up to use
+ */
+ Direction direction() const;
- /**
- Process an array in the "forward" direction,
- returning an array
+ /**
+ 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.
+ 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
- */
- MemoryRegion encode(const MemoryRegion &a);
+ \param a the array to encode
+ */
+ MemoryRegion encode(const MemoryRegion &a);
- /**
- Process an array in the "reverse" direction,
- returning an array
+ /**
+ 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.
+ 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
- */
- MemoryRegion decode(const MemoryRegion &a);
+ \param a the array to decode
+ */
+ MemoryRegion decode(const MemoryRegion &a);
- /**
- Process an array in the "forward" direction,
- returning a QString
+ /**
+ 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.
+ 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 MemoryRegion &a);
+ \param a the array to encode
+ */
+ QString arrayToString(const MemoryRegion &a);
- /**
- Process an string in the "reverse" direction,
- returning a byte array
+ /**
+ 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.
+ This is equivalent to decode(), except
+ that it takes a QString, rather than a
+ byte array.
- \param s the array to decode
- */
- MemoryRegion stringToArray(const QString &s);
+ \param s the array to decode
+ */
+ MemoryRegion stringToArray(const QString &s);
- /**
- Process a string in the "forward" direction,
- returning a string
+ /**
+ 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.
+ 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);
+ \param s the string to encode
+ */
+ QString encodeString(const QString &s);
- /**
- Process a string in the "reverse" direction,
- returning a string
+ /**
+ 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.
+ 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);
+ \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;
+ /**
+ Internal state variable for the Direction
+ that the filter operates in
+ */
+ Direction _dir;
};
/**
\class Hex qca_textfilter.h QtCrypto
Hexadecimal encoding / decoding
\ingroup UserAPI
*/
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 MemoryRegion update(const MemoryRegion &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 MemoryRegion final();
-
- /**
- Test if an update() or final() call succeeded.
-
- \return true if the previous call succeeded
- */
- virtual bool ok() const;
+ /**
+ 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 MemoryRegion update(const MemoryRegion &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 MemoryRegion final();
+
+ /**
+ Test if an update() or final() call succeeded.
+
+ \return true if the previous call succeeded
+ */
+ virtual bool ok() const;
private:
- Q_DISABLE_COPY(Hex)
+ Q_DISABLE_COPY(Hex)
- uchar val;
- bool partial;
- bool _ok;
+ uchar val;
+ bool partial;
+ bool _ok;
};
/**
\class Base64 qca_textfilter.h QtCrypto
%Base64 encoding / decoding
\ingroup UserAPI
*/
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);
-
- /**
- Returns true if line breaks are enabled
- */
- bool lineBreaksEnabled() const;
-
- /**
- Returns the line break column
- */
- int lineBreaksColumn() const;
-
- /**
- 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.
-
- \param b whether to enable line breaks (true) or disable line breaks (false)
- */
- void setLineBreaksEnabled(bool b);
-
- /**
- Sets the column that linebreaks should be inserted at
- when encoding.
-
- \param column the column number that line breaks should be inserted at.
- */
- 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 MemoryRegion update(const MemoryRegion &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 MemoryRegion final();
-
- /**
- Test if an update() or final() call succeeded.
-
- \return true if the previous call succeeded
- */
- virtual bool ok() const;
+ /**
+ Standard constructor
+
+ \param dir the Direction that should be used.
+
+ \note The direction can be changed using
+ the setup() call.
+ */
+ Base64(Direction dir = Encode);
+
+ /**
+ Returns true if line breaks are enabled
+ */
+ bool lineBreaksEnabled() const;
+
+ /**
+ Returns the line break column
+ */
+ int lineBreaksColumn() const;
+
+ /**
+ 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.
+
+ \param b whether to enable line breaks (true) or disable line breaks (false)
+ */
+ void setLineBreaksEnabled(bool b);
+
+ /**
+ Sets the column that linebreaks should be inserted at
+ when encoding.
+
+ \param column the column number that line breaks should be inserted at.
+ */
+ 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 MemoryRegion update(const MemoryRegion &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 MemoryRegion final();
+
+ /**
+ Test if an update() or final() call succeeded.
+
+ \return true if the previous call succeeded
+ */
+ virtual bool ok() const;
private:
- Q_DISABLE_COPY(Base64)
+ Q_DISABLE_COPY(Base64)
- QByteArray partial;
- bool _ok;
- int col;
- bool _lb_enabled;
- int _lb_column;
+ QByteArray partial;
+ bool _ok;
+ int col;
+ bool _lb_enabled;
+ int _lb_column;
- class Private;
- Private *d;
+ class Private;
+ Private *d;
};
}
#endif
diff --git a/include/QtCrypto/qca_tools.h b/include/QtCrypto/qca_tools.h
index 27007b11..8f531f4c 100644
--- a/include/QtCrypto/qca_tools.h
+++ b/include/QtCrypto/qca_tools.h
@@ -1,853 +1,851 @@
/*
* qca_tools.h - Qt Cryptographic Architecture
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qca_tools.h
Header file for "tool" classes used in %QCA
These classes differ from those in qca_support.h, in that they have
some cryptographic relationship, and require secure memory.
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCA_TOOLS_H
#define QCA_TOOLS_H
#include <QSharedData>
#include <QSharedDataPointer>
#include <QMetaType>
#include "qca_export.h"
class QString;
class QByteArray;
class QTextStream;
/**
Allocate a block of memory from the secure memory pool.
This is intended to be used when working with C libraries.
\param bytes the number of bytes to allocate
*/
QCA_EXPORT void *qca_secure_alloc(int bytes);
/**
Free (de-allocate) a block of memory that has been previously
allocated from the secure memory pool.
This is intended to be used when working with C libraries.
\param p pointer to the block of memory to be free'd
*/
QCA_EXPORT void qca_secure_free(void *p);
/**
Resize (re-allocate) a block of memory that has been previously
allocated from the secure memory pool.
\param p pointer to the block of memory to be resized.
\param bytes the new size that is required.
*/
QCA_EXPORT void *qca_secure_realloc(void *p, int bytes);
-namespace QCA {
+namespace QCA
+{
/**
\class MemoryRegion qca_tools.h QtCrypto
Array of bytes that may be optionally secured
This class is mostly unusable on its own. Either use it as a SecureArray
subclass or call toByteArray() to convert to QByteArray.
Note that this class is implicitly shared (that is, copy on write).
\ingroup UserAPI
*/
class QCA_EXPORT MemoryRegion
{
public:
- MemoryRegion();
+ MemoryRegion();
+
+ /**
+ Constructs a new Memory Region from a null terminated
+ character array
+
+ \param str pointer to the array of data to copy
+ */
+ MemoryRegion(const char *str);
+
+ /**
+ Constructs a new MemoryRegion from the data in a
+ byte array
+
+ \param from the QByteArray to copy from
+ */
+ MemoryRegion(const QByteArray &from);
+
+ /**
+ Standard copy constructor
+
+ \param from the MemoryRegion to copy from
+ */
+ MemoryRegion(const MemoryRegion &from);
+ ~MemoryRegion();
+
+ /**
+ Standard assignment operator
+
+ \param from the MemoryRegion to copy from
+ */
+ MemoryRegion &operator=(const MemoryRegion &from);
+
+ /**
+ Standard assignment operator
+
+ \param from the QByteArray to copy from
+ */
+ MemoryRegion &operator=(const QByteArray &from);
+
+ /**
+ Test if the MemoryRegion is null (i.e. was created
+ as a null array, and hasn't been resized).
+
+ This is probably not what you are trying to do. If
+ you are trying to determine whether there are any
+ bytes in the array, use isEmpty() instead.
+ */
+ bool isNull() const;
+
+ /**
+ Test if the MemoryRegion is using secure memory, or not.
+
+ In this context, memory is secure if it will not be paged
+ out to disk.
+
+ \return true if the memory region is secure
+ */
+ bool isSecure() const;
- /**
- Constructs a new Memory Region from a null terminated
- character array
-
- \param str pointer to the array of data to copy
- */
- MemoryRegion(const char *str);
-
- /**
- Constructs a new MemoryRegion from the data in a
- byte array
-
- \param from the QByteArray to copy from
- */
- MemoryRegion(const QByteArray &from);
-
- /**
- Standard copy constructor
-
- \param from the MemoryRegion to copy from
- */
- MemoryRegion(const MemoryRegion &from);
- ~MemoryRegion();
-
- /**
- Standard assignment operator
-
- \param from the MemoryRegion to copy from
- */
- MemoryRegion & operator=(const MemoryRegion &from);
-
- /**
- Standard assignment operator
-
- \param from the QByteArray to copy from
- */
- MemoryRegion & operator=(const QByteArray &from);
-
- /**
- Test if the MemoryRegion is null (i.e. was created
- as a null array, and hasn't been resized).
-
- This is probably not what you are trying to do. If
- you are trying to determine whether there are any
- bytes in the array, use isEmpty() instead.
- */
- bool isNull() const;
-
- /**
- Test if the MemoryRegion is using secure memory, or not.
-
- In this context, memory is secure if it will not be paged
- out to disk.
-
- \return true if the memory region is secure
- */
- bool isSecure() const;
-
- /**
- Convert this memory region to a byte array.
-
- \note For secure data, this will make it insecure
-
- \sa data() and constData() for other ways to convert
- to an "accessible" format.
- */
- QByteArray toByteArray() const;
-
- /**
- Returns true if the size of the memory region is zero.
- */
- bool isEmpty() const;
-
- /**
- Returns the number of bytes in the memory region.
- */
- int size() const;
-
- /**
- Convert the contents of the memory region to
- a C-compatible character array. This consists
- of size() bytes, followed by a null terminator.
-
- \sa toByteArray for an alternative approach.
- \sa constData, which is equivalent to this method, but avoids
- the possibility that the compiler picks the wrong version.
- */
- const char *data() const;
-
- /**
- Convert the contents of the memory region to
- a C-compatible character array. This consists
- of size() bytes, followed by a null terminator.
-
- \sa toByteArray for an alternative approach.
- \sa data which is equivalent to this method
- */
- const char *constData() const;
-
- /**
- Obtain the value of the memory location at the specified
- position.
-
- \param index the offset into the memory region.
-
- \note The contents of a memory region are between
- 0 and size()-1. The content at position size() is
- always a null terminator.
- */
- const char & at(int index) const;
+ /**
+ Convert this memory region to a byte array.
+
+ \note For secure data, this will make it insecure
+
+ \sa data() and constData() for other ways to convert
+ to an "accessible" format.
+ */
+ QByteArray toByteArray() const;
+
+ /**
+ Returns true if the size of the memory region is zero.
+ */
+ bool isEmpty() const;
+
+ /**
+ Returns the number of bytes in the memory region.
+ */
+ int size() const;
+
+ /**
+ Convert the contents of the memory region to
+ a C-compatible character array. This consists
+ of size() bytes, followed by a null terminator.
+
+ \sa toByteArray for an alternative approach.
+ \sa constData, which is equivalent to this method, but avoids
+ the possibility that the compiler picks the wrong version.
+ */
+ const char *data() const;
+
+ /**
+ Convert the contents of the memory region to
+ a C-compatible character array. This consists
+ of size() bytes, followed by a null terminator.
+
+ \sa toByteArray for an alternative approach.
+ \sa data which is equivalent to this method
+ */
+ const char *constData() const;
+
+ /**
+ Obtain the value of the memory location at the specified
+ position.
+
+ \param index the offset into the memory region.
+
+ \note The contents of a memory region are between
+ 0 and size()-1. The content at position size() is
+ always a null terminator.
+ */
+ const char &at(int index) const;
protected:
- /**
- Create a memory region, optionally using secure
- storage.
-
- \param secure if this is true, the memory region
- will use secure storage.
-
- \note This will create a memory region without
- any content (i.e. both isNull() and isEmpty() will
- return true.
- */
- MemoryRegion(bool secure);
-
- /**
- Create a memory region, optionally using secure
- storage.
-
- \param size the number of bytes in the memory
- region.
- \param secure if this is true, the memory region
- will use secure storage.
- */
- MemoryRegion(int size, bool secure);
-
- /**
- Create a memory region, optionally using secure
- storage.
-
- This constructor variant allows you to
- initialize the memory region from an existing
- array.
-
- \param from the byte array to copy from.
- \param secure if this is true, the memory region
- will use secure storage.
- */
- MemoryRegion(const QByteArray &from, bool secure);
-
- /**
- Convert the contents of the memory region to
- a C-compatible character array. This consists
- of size() bytes, followed by a null terminator.
- */
- char *data();
-
- /**
- Obtain the value of the memory location at the specified
- position.
-
- \param index the offset into the memory region.
-
- \note The contents of a memory region are between
- 0 and size()-1. The content at position size() is
- always a null terminator.
- */
- char & at(int index);
-
- /**
- Resize the memory region to the specified size.
-
- \param size the new size of the region.
- */
- bool resize(int size);
-
- /**
- Modify the memory region to match a specified
- byte array. This resizes the memory region
- as required to match the byte array size.
-
- \param from the byte array to copy from.
- \param secure if this is true, the memory region
- will use secure storage.
- */
- void set(const QByteArray &from, bool secure);
-
- /**
- Convert the memory region to use the specified
- memory type.
-
- This may involve copying data from secure to
- insecure storage, or from insecure to secure
- storage.
-
- \param secure if true, use secure memory; otherwise
- use insecure memory.
- */
- void setSecure(bool secure);
+ /**
+ Create a memory region, optionally using secure
+ storage.
+
+ \param secure if this is true, the memory region
+ will use secure storage.
+
+ \note This will create a memory region without
+ any content (i.e. both isNull() and isEmpty() will
+ return true.
+ */
+ MemoryRegion(bool secure);
+
+ /**
+ Create a memory region, optionally using secure
+ storage.
+
+ \param size the number of bytes in the memory
+ region.
+ \param secure if this is true, the memory region
+ will use secure storage.
+ */
+ MemoryRegion(int size, bool secure);
+
+ /**
+ Create a memory region, optionally using secure
+ storage.
+
+ This constructor variant allows you to
+ initialize the memory region from an existing
+ array.
+
+ \param from the byte array to copy from.
+ \param secure if this is true, the memory region
+ will use secure storage.
+ */
+ MemoryRegion(const QByteArray &from, bool secure);
+
+ /**
+ Convert the contents of the memory region to
+ a C-compatible character array. This consists
+ of size() bytes, followed by a null terminator.
+ */
+ char *data();
+
+ /**
+ Obtain the value of the memory location at the specified
+ position.
+
+ \param index the offset into the memory region.
+
+ \note The contents of a memory region are between
+ 0 and size()-1. The content at position size() is
+ always a null terminator.
+ */
+ char &at(int index);
+
+ /**
+ Resize the memory region to the specified size.
+
+ \param size the new size of the region.
+ */
+ bool resize(int size);
+
+ /**
+ Modify the memory region to match a specified
+ byte array. This resizes the memory region
+ as required to match the byte array size.
+
+ \param from the byte array to copy from.
+ \param secure if this is true, the memory region
+ will use secure storage.
+ */
+ void set(const QByteArray &from, bool secure);
+
+ /**
+ Convert the memory region to use the specified
+ memory type.
+
+ This may involve copying data from secure to
+ insecure storage, or from insecure to secure
+ storage.
+
+ \param secure if true, use secure memory; otherwise
+ use insecure memory.
+ */
+ void setSecure(bool secure);
private:
- bool _secure;
- class Private;
- QSharedDataPointer<Private> d;
+ bool _secure;
+ class Private;
+ QSharedDataPointer<Private> d;
};
/**
\class SecureArray qca_tools.h QtCrypto
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 QByteArray or QString 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).
\ingroup UserAPI
*/
class QCA_EXPORT SecureArray : public MemoryRegion
{
public:
- /**
- Construct a secure byte array, zero length
- */
- SecureArray();
+ /**
+ Construct a secure byte array, zero length
+ */
+ SecureArray();
+
+ /**
+ Construct a secure byte array of the specified length
- /**
- 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);
- \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
- /**
- Construct a secure byte array from a string
+ Note that this copies, rather than references the source array.
- Note that this copies, rather than references the source array.
+ \param str the source of the data (as a null terminated string).
+ */
+ SecureArray(const char *str);
- \param str the source of the data (as a null terminated string).
- */
- SecureArray(const char *str);
+ /**
+ Construct a secure byte array from a QByteArray
- /**
- Construct a secure byte array from a QByteArray
+ Note that this copies, rather than references the source array.
- Note that this copies, rather than references the source array.
+ \param a the source of the data.
- \param a the source of the data.
+ \sa operator=()
+ */
+ SecureArray(const QByteArray &a);
- \sa operator=()
- */
- SecureArray(const QByteArray &a);
+ /**
+ Construct a secure byte array from a MemoryRegion
- /**
- Construct a secure byte array from a MemoryRegion
+ Note that this copies, rather than references the source array
- Note that this copies, rather than references the source array
+ \param a the source of the data.
- \param a the source of the data.
+ \sa operator=()
+ */
+ SecureArray(const MemoryRegion &a);
- \sa operator=()
- */
- SecureArray(const MemoryRegion &a);
+ /**
+ Construct a (shallow) copy of another secure byte array
- /**
- Construct a (shallow) copy of another secure byte array
+ \param from the source of the data and length.
+ */
+ SecureArray(const SecureArray &from);
- \param from the source of the data and length.
- */
- SecureArray(const SecureArray &from);
+ ~SecureArray();
- ~SecureArray();
+ /**
+ Creates a reference, rather than a deep copy.
- /**
- Creates a reference, rather than a deep copy.
+ \param from the array to reference
+ */
+ SecureArray &operator=(const SecureArray &from);
- \param from the array to reference
- */
- SecureArray & operator=(const SecureArray &from);
+ /**
+ Creates a copy, rather than references
- /**
- Creates a copy, rather than references
+ \param a the array to copy from
+ */
+ SecureArray &operator=(const QByteArray &a);
- \param a the array to copy from
- */
- SecureArray & operator=(const QByteArray &a);
+ /**
+ Clears the contents of the array and makes it empty
+ */
+ void clear();
- /**
- Clears the contents of the array and makes it empty
- */
- void clear();
+ /**
+ Returns a reference to the byte at the index position
- /**
- Returns a reference to the byte at the index position
+ \param index the zero-based offset to obtain
+ */
+ char &operator[](int index);
- \param index the zero-based offset to obtain
- */
- char & operator[](int index);
+ /**
+ Returns a reference to the byte at the index position
- /**
- Returns a reference to the byte at the index position
+ \param index the zero-based offset to obtain
+ */
+ const char &operator[](int index) const;
- \param index the zero-based offset to obtain
- */
- const char & operator[](int index) const;
+ /**
+ Pointer to the data in the secure array
- /**
- 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();
- 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
- /**
- 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;
- 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
- /**
- 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;
- 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
- /**
- Returns a reference to the byte at the index position
+ \param index the zero-based offset to obtain
+ */
+ char &at(int index);
- \param index the zero-based offset to obtain
- */
- char & at(int index);
+ /**
+ Returns a reference to the byte at the index position
- /**
- Returns a reference to the byte at the index position
+ \param index the zero-based offset to obtain
+ */
+ const char &at(int index) const;
- \param index the zero-based offset to obtain
- */
- const char & at(int index) const;
+ /**
+ Returns the number of bytes in the array
+ */
+ int size() const;
- /**
- Returns the number of bytes in the array
- */
- int size() const;
+ /**
+ Test if the array contains any bytes.
- /**
- 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)
- 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
- */
- 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
- */
- 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.
- */
- QByteArray toByteArray() const;
-
- /**
- Append a secure byte array to the end of this array
-
- \param a the array to append to this array
- */
- SecureArray & append(const SecureArray &a);
-
- /**
- Equality operator. Returns true if both arrays have the same
- data (and the same length, of course).
-
- \param other the MemoryRegion to compare to
- */
- bool operator==(const MemoryRegion &other) const;
-
- /**
- Inequality operator. Returns true if both arrays have different
- length, or the same length but different data.
-
- \param other the MemoryRegion to compare to
- */
- inline bool operator!=(const MemoryRegion &other) const
- {
- return !(*this == other);
- }
-
- /**
- Append a secure byte array to the end of this array
-
- \param a the array to append to this array
- */
- SecureArray & operator+=(const SecureArray &a);
+ \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
+ */
+ 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
+ */
+ 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.
+ */
+ QByteArray toByteArray() const;
+
+ /**
+ Append a secure byte array to the end of this array
+
+ \param a the array to append to this array
+ */
+ SecureArray &append(const SecureArray &a);
+
+ /**
+ Equality operator. Returns true if both arrays have the same
+ data (and the same length, of course).
+
+ \param other the MemoryRegion to compare to
+ */
+ bool operator==(const MemoryRegion &other) const;
+
+ /**
+ Inequality operator. Returns true if both arrays have different
+ length, or the same length but different data.
+
+ \param other the MemoryRegion to compare to
+ */
+ inline bool operator!=(const MemoryRegion &other) const
+ {
+ return !(*this == other);
+ }
+
+ /**
+ Append a secure byte array to the end of this array
+
+ \param a the array to append to this array
+ */
+ SecureArray &operator+=(const SecureArray &a);
protected:
- /**
- Assign the contents of a provided byte array to this
- object.
+ /**
+ Assign the contents of a provided byte array to this
+ object.
- \param from the byte array to copy
- */
- void set(const SecureArray &from);
+ \param from the byte array to copy
+ */
+ void set(const SecureArray &from);
- /**
- Assign the contents of a provided byte array to this
- object.
+ /**
+ Assign the contents of a provided byte array to this
+ object.
- \param from the byte array to copy
- */
- void set(const QByteArray &from);
+ \param from the byte array to copy
+ */
+ void set(const QByteArray &from);
};
/**
Returns an array that is the result of concatenating a and b
\param a the string to put at the start of the result
\param b the string to put at the end of the result
*/
QCA_EXPORT const SecureArray operator+(const SecureArray &a, const SecureArray &b);
/**
\class BigInteger qca_tools.h QtCrypto
Arbitrary precision integer
BigInteger provides arbitrary precision integers.
\code
-if ( BigInteger("3499543804349") ==
- BigInteger("38493290803248") + BigInteger( 343 ) )
+if ( BigInteger("3499543804349") ==
+ BigInteger("38493290803248") + BigInteger( 343 ) )
{
- // do something
+ // do something
}
\endcode
\ingroup UserAPI
*/
class QCA_EXPORT BigInteger
{
public:
- /**
- Constructor. Creates a new BigInteger, initialised to zero.
- */
- BigInteger();
+ /**
+ Constructor. Creates a new BigInteger, initialised to zero.
+ */
+ BigInteger();
- /**
- \overload
+ /**
+ \overload
- \param n an alternative integer initialisation value.
- */
- BigInteger(int n);
+ \param n an alternative integer initialisation value.
+ */
+ BigInteger(int n);
- /**
- \overload
+ /**
+ \overload
- \param c an alternative initialisation value, encoded as a character array
+ \param c an alternative initialisation value, encoded as a character array
- \code
-BigInteger b ( "9890343" );
- \endcode
- */
- BigInteger(const char *c);
+ \code
+ BigInteger b ( "9890343" );
+ \endcode
+ */
+ BigInteger(const char *c);
- /**
- \overload
+ /**
+ \overload
- \param s an alternative initialisation value, encoded as a string
- */
- BigInteger(const QString &s);
+ \param s an alternative initialisation value, encoded as a string
+ */
+ BigInteger(const QString &s);
- /**
- \overload
+ /**
+ \overload
- \param a an alternative initialisation value, encoded as SecureArray
- */
- BigInteger(const QCA::SecureArray &a);
+ \param a an alternative initialisation value, encoded as SecureArray
+ */
+ BigInteger(const QCA::SecureArray &a);
- /**
- \overload
+ /**
+ \overload
- \param from an alternative initialisation value, encoded as a %BigInteger
- */
- BigInteger(const BigInteger &from);
+ \param from an alternative initialisation value, encoded as a %BigInteger
+ */
+ BigInteger(const BigInteger &from);
- ~BigInteger();
+ ~BigInteger();
- /**
- Assignment operator
+ /**
+ Assignment operator
- \param from the BigInteger to copy from
+ \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);
+ \code
+ BigInteger a; // a is zero
+ BigInteger b( 500 );
+ a = b; // a is now 500
+ \endcode
+ */
+ BigInteger &operator=(const BigInteger &from);
- /**
- \overload
+ /**
+ \overload
- \param s the QString containing an integer representation
+ \param s the QString containing an integer representation
- \sa bool fromString(const QString &s)
+ \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);
+ \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
+ /**
+ Increment in place operator
- \param b the amount to increment by
+ \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);
+ \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
+ /**
+ Decrement in place operator
- \param b the amount to decrement by
+ \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);
-
- /**
- Multiply in place operator
+ \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);
+
+ /**
+ Multiply in place operator
- \param b the amount to multiply by
- */
- BigInteger & operator*=(const BigInteger &b);
+ \param b the amount to multiply by
+ */
+ BigInteger &operator*=(const BigInteger &b);
- /**
- Divide in place operator
-
- \param b the amount to divide by
- */
- BigInteger & operator/=(const BigInteger &b);
-
- /**
- Modulo in place operator
-
- \param b the amount to divide by
- */
- 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);
- */
- 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;
- */
- 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
- */
- 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)
- */
- 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
- */
- int compare(const BigInteger &n) const;
-
- /**
- Equality operator. Returns true if the two BigInteger values
- are the same, including having the same sign.
-
- \param other the BigInteger to compare to
- */
- inline bool operator==(const BigInteger &other) const
- {
- return (compare(other) == 0);
- }
-
- /**
- Inequality operator. Returns true if the two BigInteger values
- are different in magnitude, sign or both.
-
- \param other the BigInteger to compare to
- */
- inline bool operator!=(const BigInteger &other) const
- {
- return !(*this == other);
- }
-
- /**
- 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.
-
- \param other the BigInteger to compare to
- */
- inline bool operator<=(const BigInteger &other) const
- {
- return (compare(other) <= 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.
-
- \param other the BigInteger to compare to
- */
- inline bool operator>=(const BigInteger &other) const
- {
- return (compare(other) >= 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.
-
- \param other the BigInteger to compare to
- */
- inline bool operator<(const BigInteger &other) const
- {
- return (compare(other) < 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.
-
- \param other the BigInteger to compare to
- */
- inline bool operator>(const BigInteger &other) const
- {
- return (compare(other) > 0);
- }
+ /**
+ Divide in place operator
+
+ \param b the amount to divide by
+ */
+ BigInteger &operator/=(const BigInteger &b);
+
+ /**
+ Modulo in place operator
+
+ \param b the amount to divide by
+ */
+ 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);
+ */
+ 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;
+ */
+ 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
+ */
+ 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)
+ */
+ 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
+ */
+ int compare(const BigInteger &n) const;
+
+ /**
+ Equality operator. Returns true if the two BigInteger values
+ are the same, including having the same sign.
+
+ \param other the BigInteger to compare to
+ */
+ inline bool operator==(const BigInteger &other) const
+ {
+ return (compare(other) == 0);
+ }
+
+ /**
+ Inequality operator. Returns true if the two BigInteger values
+ are different in magnitude, sign or both.
+
+ \param other the BigInteger to compare to
+ */
+ inline bool operator!=(const BigInteger &other) const
+ {
+ return !(*this == other);
+ }
+
+ /**
+ 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.
+
+ \param other the BigInteger to compare to
+ */
+ inline bool operator<=(const BigInteger &other) const
+ {
+ return (compare(other) <= 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.
+
+ \param other the BigInteger to compare to
+ */
+ inline bool operator>=(const BigInteger &other) const
+ {
+ return (compare(other) >= 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.
+
+ \param other the BigInteger to compare to
+ */
+ inline bool operator<(const BigInteger &other) const
+ {
+ return (compare(other) < 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.
+
+ \param other the BigInteger to compare to
+ */
+ inline bool operator>(const BigInteger &other) const
+ {
+ return (compare(other) > 0);
+ }
private:
- class Private;
- QSharedDataPointer<Private> d;
+ class Private;
+ QSharedDataPointer<Private> d;
};
-
-
/**
Stream operator
\param stream the stream to write to
\param b the integer to write to the stream
\relates BigInteger
*/
QCA_EXPORT QTextStream &operator<<(QTextStream &stream, const BigInteger &b);
-
}
#endif
diff --git a/include/QtCrypto/qcaprovider.h b/include/QtCrypto/qcaprovider.h
index 92f20547..bc70bc95 100644
--- a/include/QtCrypto/qcaprovider.h
+++ b/include/QtCrypto/qcaprovider.h
@@ -1,3042 +1,3040 @@
/*
* qcaprovider.h - QCA Plugin API
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qcaprovider.h
Header file for provider implementation classes (plugins)
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QCAPROVIDER_H
#define QCAPROVIDER_H
#include "qca_core.h"
#include "qca_basic.h"
#include "qca_publickey.h"
#include "qca_cert.h"
#include "qca_keystore.h"
#include "qca_securelayer.h"
#include "qca_securemessage.h"
#include <limits>
#ifndef DOXYGEN_NO_PROVIDER_API
/**
\defgroup ProviderAPI QCA provider API
- This group of classes is not normally needed
+ This group of classes is not normally needed
by application writers, but can be used to extend QCA if
required
*/
/**
\class QCAPlugin qcaprovider.h QtCrypto
Provider plugin base class
QCA loads cryptographic provider plugins with QPluginLoader. The QObject
obtained when loading the plugin must implement the QCAPlugin interface.
This is done by inheriting QCAPlugin, and including
Q_INTERFACES(QCAPlugin) in your class declaration.
For example:
\code
class MyPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
- Q_INTERFACES(QCAPlugin)
+ Q_OBJECT
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { ... }
+ virtual Provider *createProvider() { ... }
};
\endcode
There is only one function to reimplement, called createProvider(). This
function should return a newly allocated Provider instance.
\ingroup ProviderAPI
*/
class QCA_EXPORT QCAPlugin
{
public:
- /**
- Destructs the object
- */
- virtual ~QCAPlugin() {}
-
- /**
- Returns a newly allocated Provider instance.
- */
- virtual QCA::Provider *createProvider() = 0;
+ /**
+ Destructs the object
+ */
+ virtual ~QCAPlugin() {}
+
+ /**
+ Returns a newly allocated Provider instance.
+ */
+ virtual QCA::Provider *createProvider() = 0;
};
Q_DECLARE_INTERFACE(QCAPlugin, "com.affinix.qca.Plugin/1.0")
-namespace QCA {
+namespace QCA
+{
/**
\class InfoContext qcaprovider.h QtCrypto
Extended provider information
\note This class is part of the provider plugin interface and should not
be used directly by applications.
\ingroup ProviderAPI
*/
class QCA_EXPORT InfoContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- */
- InfoContext(Provider *p) : BasicContext(p, QStringLiteral("info") ) {}
-
- /**
- The hash algorithms supported by the provider
- */
- virtual QStringList supportedHashTypes() const;
-
- /**
- The cipher algorithms supported by the provider
- */
- virtual QStringList supportedCipherTypes() const;
-
- /**
- The mac algorithms supported by the provider
- */
- virtual QStringList supportedMACTypes() const;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ */
+ InfoContext(Provider *p) : BasicContext(p, QStringLiteral("info")) {}
+
+ /**
+ The hash algorithms supported by the provider
+ */
+ virtual QStringList supportedHashTypes() const;
+
+ /**
+ The cipher algorithms supported by the provider
+ */
+ virtual QStringList supportedCipherTypes() const;
+
+ /**
+ The mac algorithms supported by the provider
+ */
+ virtual QStringList supportedMACTypes() const;
};
/**
\class RandomContext qcaprovider.h QtCrypto
Random provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want Random instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT RandomContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the provider associated with this context
- */
- RandomContext(Provider *p) : BasicContext(p, QStringLiteral("random")) {}
+ \param p the provider associated with this context
+ */
+ RandomContext(Provider *p) : BasicContext(p, QStringLiteral("random")) {}
- /**
- Return an array of random bytes
+ /**
+ Return an array of random bytes
- \param size the number of random bytes to return
- */
- virtual SecureArray nextBytes(int size) = 0;
+ \param size the number of random bytes to return
+ */
+ virtual SecureArray nextBytes(int size) = 0;
};
/**
\class HashContext qcaprovider.h QtCrypto
Hash provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want Hash instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT HashContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- \param type the name of the type of hash provided by this context
- */
- HashContext(Provider *p, const QString &type) : BasicContext(p, type) {}
-
- /**
- Reset the object to its initial state
- */
- virtual void clear() = 0;
-
- /**
- Process a chunk of data
-
- \param a the input data to process
- */
- virtual void update(const MemoryRegion &a) = 0;
-
- /**
- Return the computed hash
- */
- virtual MemoryRegion final() = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ \param type the name of the type of hash provided by this context
+ */
+ HashContext(Provider *p, const QString &type) : BasicContext(p, type) {}
+
+ /**
+ Reset the object to its initial state
+ */
+ virtual void clear() = 0;
+
+ /**
+ Process a chunk of data
+
+ \param a the input data to process
+ */
+ virtual void update(const MemoryRegion &a) = 0;
+
+ /**
+ Return the computed hash
+ */
+ virtual MemoryRegion final() = 0;
};
/**
\class CipherContext qcaprovider.h QtCrypto
Cipher provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want Cipher instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT CipherContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- \param type the name of the type of cipher provided by this context
-
- \note type includes the name of the cipher (e.g. "aes256"), the operating
- mode (e.g. "cbc" or "ofb") and the padding type (e.g. "pkcs7") if any.
- */
- CipherContext(Provider *p, const QString &type) : BasicContext(p, type) {}
-
- /**
- Set up the object for encrypt/decrypt
-
- \param dir the direction for the cipher (encryption/decryption)
- \param key the symmetric key to use for the cipher
- \param iv the initialization vector to use for the cipher (not used in ECB mode)
- \param tag the AuthTag to use (only for GCM and CCM modes)
- */
- virtual void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag) = 0;
-
- /**
- Returns the KeyLength for this cipher
- */
- virtual KeyLength keyLength() const = 0;
-
- /**
- Returns the block size for this cipher
- */
- virtual int blockSize() const = 0;
-
- /**
- Returns the authentication tag for this cipher
- */
- virtual AuthTag tag() const = 0;
-
- /**
- Process a chunk of data. Returns true if successful.
-
- \param in the input data to process
- \param out pointer to an array that should store the result
- */
- virtual bool update(const SecureArray &in, SecureArray *out) = 0;
-
- /**
- Finish the cipher processing. Returns true if successful.
-
- \param out pointer to an array that should store the result
- */
- virtual bool final(SecureArray *out) = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ \param type the name of the type of cipher provided by this context
+
+ \note type includes the name of the cipher (e.g. "aes256"), the operating
+ mode (e.g. "cbc" or "ofb") and the padding type (e.g. "pkcs7") if any.
+ */
+ CipherContext(Provider *p, const QString &type) : BasicContext(p, type) {}
+
+ /**
+ Set up the object for encrypt/decrypt
+
+ \param dir the direction for the cipher (encryption/decryption)
+ \param key the symmetric key to use for the cipher
+ \param iv the initialization vector to use for the cipher (not used in ECB mode)
+ \param tag the AuthTag to use (only for GCM and CCM modes)
+ */
+ virtual void setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag) = 0;
+
+ /**
+ Returns the KeyLength for this cipher
+ */
+ virtual KeyLength keyLength() const = 0;
+
+ /**
+ Returns the block size for this cipher
+ */
+ virtual int blockSize() const = 0;
+
+ /**
+ Returns the authentication tag for this cipher
+ */
+ virtual AuthTag tag() const = 0;
+
+ /**
+ Process a chunk of data. Returns true if successful.
+
+ \param in the input data to process
+ \param out pointer to an array that should store the result
+ */
+ virtual bool update(const SecureArray &in, SecureArray *out) = 0;
+
+ /**
+ Finish the cipher processing. Returns true if successful.
+
+ \param out pointer to an array that should store the result
+ */
+ virtual bool final(SecureArray *out) = 0;
};
/**
\class MACContext qcaprovider.h QtCrypto
Message authentication code provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want
MessageAuthenticationCode instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT MACContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
- \param p the provider associated with this context
- \param type the name of the type of MAC algorithm provided by this context
- */
- MACContext(Provider *p, const QString &type) : BasicContext(p, type) {}
+ /**
+ Standard constructor
+ \param p the provider associated with this context
+ \param type the name of the type of MAC algorithm provided by this context
+ */
+ MACContext(Provider *p, const QString &type) : BasicContext(p, type) {}
- /**
- Set up the object for hashing
+ /**
+ Set up the object for hashing
- \param key the key to use with the MAC.
- */
- virtual void setup(const SymmetricKey &key) = 0;
+ \param key the key to use with the MAC.
+ */
+ virtual void setup(const SymmetricKey &key) = 0;
- /**
- Returns the KeyLength for this MAC algorithm
- */
- virtual KeyLength keyLength() const = 0;
+ /**
+ Returns the KeyLength for this MAC algorithm
+ */
+ virtual KeyLength keyLength() const = 0;
- /**
- Process a chunk of data
+ /**
+ Process a chunk of data
- \param in the input data to process
- */
- virtual void update(const MemoryRegion &in) = 0;
+ \param in the input data to process
+ */
+ virtual void update(const MemoryRegion &in) = 0;
- /**
- Compute the result after processing all data
+ /**
+ Compute the result after processing all data
- \param out pointer to an array that should store the result
- */
- virtual void final(MemoryRegion *out) = 0;
+ \param out pointer to an array that should store the result
+ */
+ virtual void final(MemoryRegion *out) = 0;
protected:
- /**
- Returns a KeyLength that supports any length
- */
- KeyLength anyKeyLength() const
- {
- // this is used instead of a default implementation to make sure that
- // provider authors think about it, at least a bit.
- // See Meyers, Effective C++, Effective C++ (2nd Ed), Item 36
- return KeyLength( 0, INT_MAX, 1 );
- }
+ /**
+ Returns a KeyLength that supports any length
+ */
+ KeyLength anyKeyLength() const
+ {
+ // this is used instead of a default implementation to make sure that
+ // provider authors think about it, at least a bit.
+ // See Meyers, Effective C++, Effective C++ (2nd Ed), Item 36
+ return KeyLength(0, INT_MAX, 1);
+ }
};
/**
\class KDFContext qcaprovider.h QtCrypto
Key derivation function provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want KeyDerivationFunction
instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT KDFContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- \param type the name of the KDF provided by this context (including algorithm)
- */
- KDFContext(Provider *p, const QString &type) : BasicContext(p, type) {}
-
- /**
- Create a key and return it
-
- \param secret the secret part (typically password)
- \param salt the salt / initialization vector
- \param keyLength the length of the key to be produced
- \param iterationCount the number of iterations of the derivation algorith,
- */
- virtual SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) = 0;
-
- /**
- Create a key and return it
-
- \param secret the secret part (typically password)
- \param salt the salt / initialization vector
- \param keyLength the length of the key to be produced
- \param msecInterval the maximum time to compute the key, in milliseconds
- \param iterationCount a pointer to store the number of iterations of the derivation algorithm,
- */
- virtual SymmetricKey makeKey(const SecureArray &secret,
- const InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount) = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ \param type the name of the KDF provided by this context (including algorithm)
+ */
+ KDFContext(Provider *p, const QString &type) : BasicContext(p, type) {}
+
+ /**
+ Create a key and return it
+
+ \param secret the secret part (typically password)
+ \param salt the salt / initialization vector
+ \param keyLength the length of the key to be produced
+ \param iterationCount the number of iterations of the derivation algorith,
+ */
+ virtual SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount) = 0;
+
+ /**
+ Create a key and return it
+
+ \param secret the secret part (typically password)
+ \param salt the salt / initialization vector
+ \param keyLength the length of the key to be produced
+ \param msecInterval the maximum time to compute the key, in milliseconds
+ \param iterationCount a pointer to store the number of iterations of the derivation algorithm,
+ */
+ virtual SymmetricKey makeKey(const SecureArray &secret,
+ const InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount) = 0;
};
/**
\class HKDFContext qcaprovider.h QtCrypto
HKDF provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want HKDF instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT HKDFContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- \param type the name of the HKDF provided by this context (including algorithm)
- */
- HKDFContext(Provider *p, const QString &type) : BasicContext(p, type) {}
-
- /**
- Create a key and return it
-
- \param secret the secret part (typically password)
- \param salt the salt / initialization vector
- \param info the info / initialization vector
- \param keyLength the length of the key to be produced
- */
- virtual SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
- const InitializationVector &info, unsigned int keyLength) = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ \param type the name of the HKDF provided by this context (including algorithm)
+ */
+ HKDFContext(Provider *p, const QString &type) : BasicContext(p, type) {}
+
+ /**
+ Create a key and return it
+
+ \param secret the secret part (typically password)
+ \param salt the salt / initialization vector
+ \param info the info / initialization vector
+ \param keyLength the length of the key to be produced
+ */
+ virtual SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
+ const InitializationVector &info, unsigned int keyLength) = 0;
};
/**
\class DLGroupContext qcaprovider.h QtCrypto
Discrete logarithm provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want DLGroup instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT DLGroupContext : public Provider::Context
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the provider associated with this context
- */
- DLGroupContext(Provider *p) : Provider::Context(p, QStringLiteral("dlgroup")) {}
+ \param p the provider associated with this context
+ */
+ DLGroupContext(Provider *p) : Provider::Context(p, QStringLiteral("dlgroup")) {}
- /**
- The DLGroupSets supported by this object
- */
- virtual QList<DLGroupSet> supportedGroupSets() const = 0;
+ /**
+ The DLGroupSets supported by this object
+ */
+ virtual QList<DLGroupSet> supportedGroupSets() const = 0;
- /**
- Returns true if there is a result to obtain
- */
- virtual bool isNull() const = 0;
+ /**
+ Returns true if there is a result to obtain
+ */
+ virtual bool isNull() const = 0;
- /**
- Attempt to create P, Q, and G values from the specified group set
+ /**
+ Attempt to create P, Q, and G values from the specified group set
- If \a block is true, then this function blocks until completion.
- Otherwise, this function returns immediately and finished() is
- emitted when the operation completes.
+ If \a block is true, then this function blocks until completion.
+ Otherwise, this function returns immediately and finished() is
+ emitted when the operation completes.
- If an error occurs during generation, then the operation will
- complete and isNull() will return true.
+ If an error occurs during generation, then the operation will
+ complete and isNull() will return true.
- \param set the group set to generate the key from
- \param block whether to block (true) or not (false)
- */
- virtual void fetchGroup(DLGroupSet set, bool block) = 0;
+ \param set the group set to generate the key from
+ \param block whether to block (true) or not (false)
+ */
+ virtual void fetchGroup(DLGroupSet set, bool block) = 0;
- /**
- Obtain the result of the operation. Ensure isNull() returns false
- before calling this function.
+ /**
+ Obtain the result of the operation. Ensure isNull() returns false
+ before calling this function.
- \param p the P value
- \param q the Q value
- \param g the G value
- */
- virtual void getResult(BigInteger *p, BigInteger *q, BigInteger *g) const = 0;
+ \param p the P value
+ \param q the Q value
+ \param g the G value
+ */
+ virtual void getResult(BigInteger *p, BigInteger *q, BigInteger *g) const = 0;
Q_SIGNALS:
- /**
- Emitted when the fetchGroup() operation completes in non-blocking
- mode.
- */
- void finished();
+ /**
+ Emitted when the fetchGroup() operation completes in non-blocking
+ mode.
+ */
+ void finished();
};
/**
\class PKeyBase qcaprovider.h QtCrypto
Public key implementation provider base
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want PKey, PublicKey, or
PrivateKey instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT PKeyBase : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the Provider associated with this context
- \param type type of key provided by this context
- */
- PKeyBase(Provider *p, const QString &type);
-
- /**
- Returns true if this object is not valid. This is the default
- state, and the object may also become this state if a conversion
- or generation function fails.
- */
- virtual bool isNull() const = 0;
-
- /**
- Returns the type of public key
- */
- virtual PKey::Type type() const = 0;
-
- /**
- Returns true if this is a private key, otherwise false
- */
- virtual bool isPrivate() const = 0;
-
- /**
- Returns true if the components of this key are accessible and
- whether it can be serialized into an output format. Private keys
- from a smart card device will often not be exportable.
- */
- virtual bool canExport() const = 0;
-
- /**
- If the key is a private key, this function will convert it into a
- public key (all private key data includes the public data as well,
- which is why this is possible). If the key is already a public
- key, then this function has no effect.
- */
- virtual void convertToPublic() = 0;
-
- /**
- Returns the number of bits in the key
- */
- virtual int bits() const = 0;
-
- /**
- Returns the maximum number of bytes that can be encrypted by this
- key
-
- \param alg the algorithm to be used for encryption
- */
- virtual int maximumEncryptSize(EncryptionAlgorithm alg) const;
-
- /**
- Encrypt data
-
- \param in the input data to encrypt
- \param alg the encryption algorithm to use
- */
- virtual SecureArray encrypt(const SecureArray &in, EncryptionAlgorithm alg);
-
- /**
- Decrypt data
-
- \param in the input data to decrypt
- \param out pointer to an array to store the plaintext result
- \param alg the encryption algorithm used to generate the input
- data
- */
- virtual bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg);
-
- /**
- Begin a signing operation
-
- \param alg the signature algorithm to use
- \param format the signature format to use
- */
- virtual void startSign(SignatureAlgorithm alg, SignatureFormat format);
-
- /**
- Begin a verify operation
-
- \param alg the signature algorithm used by the input signature
- \param format the signature format used by the input signature
- */
- virtual void startVerify(SignatureAlgorithm alg, SignatureFormat format);
-
- /**
- Process the plaintext input data for either signing or verifying,
- whichever operation is active.
-
- \param in the input data to process
- */
- virtual void update(const MemoryRegion &in);
-
- /**
- Complete a signing operation, and return the signature value
-
- If there is an error signing, an empty array is returned.
- */
- virtual QByteArray endSign();
-
- /**
- Complete a verify operation, and return true if successful
-
- If there is an error verifying, this function returns false.
-
- \param sig the signature to verify with the input data
- */
- virtual bool endVerify(const QByteArray &sig);
-
- /**
- Compute a symmetric key based on this private key and some other
- public key
+ /**
+ Standard constructor
+
+ \param p the Provider associated with this context
+ \param type type of key provided by this context
+ */
+ PKeyBase(Provider *p, const QString &type);
+
+ /**
+ Returns true if this object is not valid. This is the default
+ state, and the object may also become this state if a conversion
+ or generation function fails.
+ */
+ virtual bool isNull() const = 0;
+
+ /**
+ Returns the type of public key
+ */
+ virtual PKey::Type type() const = 0;
+
+ /**
+ Returns true if this is a private key, otherwise false
+ */
+ virtual bool isPrivate() const = 0;
+
+ /**
+ Returns true if the components of this key are accessible and
+ whether it can be serialized into an output format. Private keys
+ from a smart card device will often not be exportable.
+ */
+ virtual bool canExport() const = 0;
+
+ /**
+ If the key is a private key, this function will convert it into a
+ public key (all private key data includes the public data as well,
+ which is why this is possible). If the key is already a public
+ key, then this function has no effect.
+ */
+ virtual void convertToPublic() = 0;
+
+ /**
+ Returns the number of bits in the key
+ */
+ virtual int bits() const = 0;
+
+ /**
+ Returns the maximum number of bytes that can be encrypted by this
+ key
+
+ \param alg the algorithm to be used for encryption
+ */
+ virtual int maximumEncryptSize(EncryptionAlgorithm alg) const;
+
+ /**
+ Encrypt data
+
+ \param in the input data to encrypt
+ \param alg the encryption algorithm to use
+ */
+ virtual SecureArray encrypt(const SecureArray &in, EncryptionAlgorithm alg);
+
+ /**
+ Decrypt data
+
+ \param in the input data to decrypt
+ \param out pointer to an array to store the plaintext result
+ \param alg the encryption algorithm used to generate the input
+ data
+ */
+ virtual bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg);
+
+ /**
+ Begin a signing operation
+
+ \param alg the signature algorithm to use
+ \param format the signature format to use
+ */
+ virtual void startSign(SignatureAlgorithm alg, SignatureFormat format);
+
+ /**
+ Begin a verify operation
+
+ \param alg the signature algorithm used by the input signature
+ \param format the signature format used by the input signature
+ */
+ virtual void startVerify(SignatureAlgorithm alg, SignatureFormat format);
+
+ /**
+ Process the plaintext input data for either signing or verifying,
+ whichever operation is active.
+
+ \param in the input data to process
+ */
+ virtual void update(const MemoryRegion &in);
+
+ /**
+ Complete a signing operation, and return the signature value
+
+ If there is an error signing, an empty array is returned.
+ */
+ virtual QByteArray endSign();
+
+ /**
+ Complete a verify operation, and return true if successful
+
+ If there is an error verifying, this function returns false.
+
+ \param sig the signature to verify with the input data
+ */
+ virtual bool endVerify(const QByteArray &sig);
+
+ /**
+ Compute a symmetric key based on this private key and some other
+ public key
- Essentially for Diffie-Hellman only.
-
- \param theirs the other side (public key) to be used for key generation.
- */
- virtual SymmetricKey deriveKey(const PKeyBase &theirs);
+ Essentially for Diffie-Hellman only.
+
+ \param theirs the other side (public key) to be used for key generation.
+ */
+ virtual SymmetricKey deriveKey(const PKeyBase &theirs);
Q_SIGNALS:
- /**
- Emitted when an asynchronous operation completes on this key.
- Such operations will be documented that they emit this signal.
- */
- void finished();
+ /**
+ Emitted when an asynchronous operation completes on this key.
+ Such operations will be documented that they emit this signal.
+ */
+ void finished();
};
/**
\class RSAContext qcaprovider.h QtCrypto
RSA provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want RSAPublicKey or
RSAPrivateKey instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT RSAContext : public PKeyBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- */
- RSAContext(Provider *p) : PKeyBase(p, QStringLiteral("rsa")) {}
-
- /**
- Generate an RSA private key
-
- If \a block is true, then this function blocks until completion.
- Otherwise, this function returns immediately and finished() is
- emitted when the operation completes.
-
- If an error occurs during generation, then the operation will
- complete and isNull() will return true.
-
- \param bits the length of the key to generate, in bits
- \param exp the exponent to use for generation
- \param block whether to use blocking mode
- */
- virtual void createPrivate(int bits, int exp, bool block) = 0;
-
- /**
- Create an RSA private key based on the five components
-
- \param n the N parameter
- \param e the public exponent
- \param p the P parameter
- \param q the Q parameter
- \param d the D parameter
- */
- virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d) = 0;
-
- /**
- Create an RSA public key based on the two public components
-
- \param n the N parameter
- \param e the public exponent
- */
- virtual void createPublic(const BigInteger &n, const BigInteger &e) = 0;
-
- /**
- Returns the public N component of this RSA key
- */
- virtual BigInteger n() const = 0;
-
- /**
- Returns the public E component of this RSA key
- */
- virtual BigInteger e() const = 0;
-
- /**
- Returns the private P component of this RSA key
- */
- virtual BigInteger p() const = 0;
-
- /**
- Returns the private Q component of this RSA key
- */
- virtual BigInteger q() const = 0;
-
- /**
- Returns the private D component of this RSA key
- */
- virtual BigInteger d() const = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ */
+ RSAContext(Provider *p) : PKeyBase(p, QStringLiteral("rsa")) {}
+
+ /**
+ Generate an RSA private key
+
+ If \a block is true, then this function blocks until completion.
+ Otherwise, this function returns immediately and finished() is
+ emitted when the operation completes.
+
+ If an error occurs during generation, then the operation will
+ complete and isNull() will return true.
+
+ \param bits the length of the key to generate, in bits
+ \param exp the exponent to use for generation
+ \param block whether to use blocking mode
+ */
+ virtual void createPrivate(int bits, int exp, bool block) = 0;
+
+ /**
+ Create an RSA private key based on the five components
+
+ \param n the N parameter
+ \param e the public exponent
+ \param p the P parameter
+ \param q the Q parameter
+ \param d the D parameter
+ */
+ virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d) = 0;
+
+ /**
+ Create an RSA public key based on the two public components
+
+ \param n the N parameter
+ \param e the public exponent
+ */
+ virtual void createPublic(const BigInteger &n, const BigInteger &e) = 0;
+
+ /**
+ Returns the public N component of this RSA key
+ */
+ virtual BigInteger n() const = 0;
+
+ /**
+ Returns the public E component of this RSA key
+ */
+ virtual BigInteger e() const = 0;
+
+ /**
+ Returns the private P component of this RSA key
+ */
+ virtual BigInteger p() const = 0;
+
+ /**
+ Returns the private Q component of this RSA key
+ */
+ virtual BigInteger q() const = 0;
+
+ /**
+ Returns the private D component of this RSA key
+ */
+ virtual BigInteger d() const = 0;
};
/**
\class DSAContext qcaprovider.h QtCrypto
DSA provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want DSAPublicKey or
DSAPrivateKey instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT DSAContext : public PKeyBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- */
- DSAContext(Provider *p) : PKeyBase(p, QStringLiteral("dsa")) {}
-
- /**
- Generate a DSA private key
-
- If \a block is true, then this function blocks until completion.
- Otherwise, this function returns immediately and finished() is
- emitted when the operation completes.
-
- If an error occurs during generation, then the operation will
- complete and isNull() will return true.
-
- \param domain the domain values to use for generation
- \param block whether to use blocking mode
- */
- virtual void createPrivate(const DLGroup &domain, bool block) = 0;
-
- /**
- Create a DSA private key based on its numeric components
-
- \param domain the domain values to use for generation
- \param y the public Y component
- \param x the private X component
- */
- virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) = 0;
-
- /**
- Create a DSA public key based on its numeric components
-
- \param domain the domain values to use for generation
- \param y the public Y component
- */
- virtual void createPublic(const DLGroup &domain, const BigInteger &y) = 0;
-
- /**
- Returns the public domain component of this DSA key
- */
- virtual DLGroup domain() const = 0;
-
- /**
- Returns the public Y component of this DSA key
- */
- virtual BigInteger y() const = 0;
-
- /**
- Returns the private X component of this DSA key
- */
- virtual BigInteger x() const = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ */
+ DSAContext(Provider *p) : PKeyBase(p, QStringLiteral("dsa")) {}
+
+ /**
+ Generate a DSA private key
+
+ If \a block is true, then this function blocks until completion.
+ Otherwise, this function returns immediately and finished() is
+ emitted when the operation completes.
+
+ If an error occurs during generation, then the operation will
+ complete and isNull() will return true.
+
+ \param domain the domain values to use for generation
+ \param block whether to use blocking mode
+ */
+ virtual void createPrivate(const DLGroup &domain, bool block) = 0;
+
+ /**
+ Create a DSA private key based on its numeric components
+
+ \param domain the domain values to use for generation
+ \param y the public Y component
+ \param x the private X component
+ */
+ virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) = 0;
+
+ /**
+ Create a DSA public key based on its numeric components
+
+ \param domain the domain values to use for generation
+ \param y the public Y component
+ */
+ virtual void createPublic(const DLGroup &domain, const BigInteger &y) = 0;
+
+ /**
+ Returns the public domain component of this DSA key
+ */
+ virtual DLGroup domain() const = 0;
+
+ /**
+ Returns the public Y component of this DSA key
+ */
+ virtual BigInteger y() const = 0;
+
+ /**
+ Returns the private X component of this DSA key
+ */
+ virtual BigInteger x() const = 0;
};
/**
\class DHContext qcaprovider.h QtCrypto
Diffie-Hellman provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want DHPublicKey or
DHPrivateKey instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT DHContext : public PKeyBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- */
- DHContext(Provider *p) : PKeyBase(p, QStringLiteral("dh")) {}
-
- /**
- Generate a Diffie-Hellman private key
-
- If \a block is true, then this function blocks until completion.
- Otherwise, this function returns immediately and finished() is
- emitted when the operation completes.
-
- If an error occurs during generation, then the operation will
- complete and isNull() will return true.
-
- \param domain the domain values to use for generation
- \param block whether to use blocking mode
- */
- virtual void createPrivate(const DLGroup &domain, bool block) = 0;
-
- /**
- Create a Diffie-Hellman private key based on its numeric
- components
-
- \param domain the domain values to use for generation
- \param y the public Y component
- \param x the private X component
- */
- virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) = 0;
-
- /**
- Create a Diffie-Hellman public key based on its numeric
- components
-
- \param domain the domain values to use for generation
- \param y the public Y component
- */
- virtual void createPublic(const DLGroup &domain, const BigInteger &y) = 0;
-
- /**
- Returns the public domain component of this Diffie-Hellman key
- */
- virtual DLGroup domain() const = 0;
-
- /**
- Returns the public Y component of this Diffie-Hellman key
- */
- virtual BigInteger y() const = 0;
-
- /**
- Returns the private X component of this Diffie-Hellman key
- */
- virtual BigInteger x() const = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ */
+ DHContext(Provider *p) : PKeyBase(p, QStringLiteral("dh")) {}
+
+ /**
+ Generate a Diffie-Hellman private key
+
+ If \a block is true, then this function blocks until completion.
+ Otherwise, this function returns immediately and finished() is
+ emitted when the operation completes.
+
+ If an error occurs during generation, then the operation will
+ complete and isNull() will return true.
+
+ \param domain the domain values to use for generation
+ \param block whether to use blocking mode
+ */
+ virtual void createPrivate(const DLGroup &domain, bool block) = 0;
+
+ /**
+ Create a Diffie-Hellman private key based on its numeric
+ components
+
+ \param domain the domain values to use for generation
+ \param y the public Y component
+ \param x the private X component
+ */
+ virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x) = 0;
+
+ /**
+ Create a Diffie-Hellman public key based on its numeric
+ components
+
+ \param domain the domain values to use for generation
+ \param y the public Y component
+ */
+ virtual void createPublic(const DLGroup &domain, const BigInteger &y) = 0;
+
+ /**
+ Returns the public domain component of this Diffie-Hellman key
+ */
+ virtual DLGroup domain() const = 0;
+
+ /**
+ Returns the public Y component of this Diffie-Hellman key
+ */
+ virtual BigInteger y() const = 0;
+
+ /**
+ Returns the private X component of this Diffie-Hellman key
+ */
+ virtual BigInteger x() const = 0;
};
/**
\class PKeyContext qcaprovider.h QtCrypto
Public key container provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want PKey, PublicKey, or
PrivateKey instead.
This object "holds" a public key object. By default it contains no key
(key() returns 0), but you can put a key into it with setKey(), or you
can call an import function such as publicFromDER().
\ingroup ProviderAPI
*/
class QCA_EXPORT PKeyContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the provider associated with this context
- */
- PKeyContext(Provider *p) : BasicContext(p, QStringLiteral("pkey")) {}
+ \param p the provider associated with this context
+ */
+ PKeyContext(Provider *p) : BasicContext(p, QStringLiteral("pkey")) {}
- /**
- Returns a list of supported public key types
- */
- virtual QList<PKey::Type> supportedTypes() const = 0;
+ /**
+ Returns a list of supported public key types
+ */
+ virtual QList<PKey::Type> supportedTypes() const = 0;
- /**
- Returns a list of public key types that can be serialized and
- deserialized into DER and PEM format
- */
- virtual QList<PKey::Type> supportedIOTypes() const = 0;
+ /**
+ Returns a list of public key types that can be serialized and
+ deserialized into DER and PEM format
+ */
+ virtual QList<PKey::Type> supportedIOTypes() const = 0;
- /**
- Returns a list of password-based encryption algorithms that are
- supported for private key serialization and deserialization
- */
- virtual QList<PBEAlgorithm> supportedPBEAlgorithms() const = 0;
+ /**
+ Returns a list of password-based encryption algorithms that are
+ supported for private key serialization and deserialization
+ */
+ virtual QList<PBEAlgorithm> supportedPBEAlgorithms() const = 0;
- /**
- Returns the key held by this object, or 0 if there is no key
- */
- virtual PKeyBase *key() = 0;
+ /**
+ Returns the key held by this object, or 0 if there is no key
+ */
+ virtual PKeyBase *key() = 0;
- /**
- Returns the key held by this object, or 0 if there is no key
- */
- virtual const PKeyBase *key() const = 0;
+ /**
+ Returns the key held by this object, or 0 if there is no key
+ */
+ virtual const PKeyBase *key() const = 0;
- /**
- Sets the key for this object. If this object already had a key,
- then the old one is destructed. This object takes ownership of
- the key.
+ /**
+ Sets the key for this object. If this object already had a key,
+ then the old one is destructed. This object takes ownership of
+ the key.
- \param key the key to be set for this object
- */
- virtual void setKey(PKeyBase *key) = 0;
+ \param key the key to be set for this object
+ */
+ virtual void setKey(PKeyBase *key) = 0;
- /**
- Attempt to import a key from another provider. Returns true if
- successful, otherwise false.
+ /**
+ Attempt to import a key from another provider. Returns true if
+ successful, otherwise false.
- Generally this function is used if the specified key's provider
- does not support serialization, but your provider does. The call
- to this function would then be followed by an export function,
- such as publicToDER().
+ Generally this function is used if the specified key's provider
+ does not support serialization, but your provider does. The call
+ to this function would then be followed by an export function,
+ such as publicToDER().
- \param key the key to be imported
- */
- virtual bool importKey(const PKeyBase *key) = 0;
+ \param key the key to be imported
+ */
+ virtual bool importKey(const PKeyBase *key) = 0;
- /**
- Convert a public key to DER format, and return the value
+ /**
+ Convert a public key to DER format, and return the value
- Returns an empty array on error.
- */
- virtual QByteArray publicToDER() const;
+ Returns an empty array on error.
+ */
+ virtual QByteArray publicToDER() const;
- /**
- Convert a public key to PEM format, and return the value
+ /**
+ Convert a public key to PEM format, and return the value
- Returns an empty string on error.
- */
- virtual QString publicToPEM() const;
+ Returns an empty string on error.
+ */
+ virtual QString publicToPEM() const;
- /**
- Read DER-formatted input and convert it into a public key
+ /**
+ Read DER-formatted input and convert it into a public key
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param a the input data
- */
- virtual ConvertResult publicFromDER(const QByteArray &a);
+ \param a the input data
+ */
+ virtual ConvertResult publicFromDER(const QByteArray &a);
- /**
- Read PEM-formatted input and convert it into a public key
+ /**
+ Read PEM-formatted input and convert it into a public key
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param s the input data
- */
- virtual ConvertResult publicFromPEM(const QString &s);
+ \param s the input data
+ */
+ virtual ConvertResult publicFromPEM(const QString &s);
- /**
- Convert a private key to DER format, and return the value
+ /**
+ Convert a private key to DER format, and return the value
- Returns an empty array on error.
+ Returns an empty array on error.
- \param passphrase the passphrase to encode the result with, or an
- empty array if no encryption is desired
- \param pbe the encryption algorithm to use, if applicable
- */
- virtual SecureArray privateToDER(const SecureArray &passphrase, PBEAlgorithm pbe) const;
+ \param passphrase the passphrase to encode the result with, or an
+ empty array if no encryption is desired
+ \param pbe the encryption algorithm to use, if applicable
+ */
+ virtual SecureArray privateToDER(const SecureArray &passphrase, PBEAlgorithm pbe) const;
- /**
- Convert a private key to PEM format, and return the value
+ /**
+ Convert a private key to PEM format, and return the value
- Returns an empty string on error.
+ Returns an empty string on error.
- \param passphrase the passphrase to encode the result with, or an
- empty array if no encryption is desired
- \param pbe the encryption algorithm to use, if applicable
- */
- virtual QString privateToPEM(const SecureArray &passphrase, PBEAlgorithm pbe) const;
+ \param passphrase the passphrase to encode the result with, or an
+ empty array if no encryption is desired
+ \param pbe the encryption algorithm to use, if applicable
+ */
+ virtual QString privateToPEM(const SecureArray &passphrase, PBEAlgorithm pbe) const;
- /**
- Read DER-formatted input and convert it into a private key
+ /**
+ Read DER-formatted input and convert it into a private key
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param a the input data
- \param passphrase the passphrase needed to decrypt, if applicable
- */
- virtual ConvertResult privateFromDER(const SecureArray &a, const SecureArray &passphrase);
+ \param a the input data
+ \param passphrase the passphrase needed to decrypt, if applicable
+ */
+ virtual ConvertResult privateFromDER(const SecureArray &a, const SecureArray &passphrase);
- /**
- Read PEM-formatted input and convert it into a private key
+ /**
+ Read PEM-formatted input and convert it into a private key
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param s the input data
- \param passphrase the passphrase needed to decrypt, if applicable
- */
- virtual ConvertResult privateFromPEM(const QString &s, const SecureArray &passphrase);
+ \param s the input data
+ \param passphrase the passphrase needed to decrypt, if applicable
+ */
+ virtual ConvertResult privateFromPEM(const QString &s, const SecureArray &passphrase);
};
/**
\class CertBase qcaprovider.h QtCrypto
X.509 certificate and certificate request provider base
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want Certificate,
CertificateRequest, or CRL instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT CertBase : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the provider associated with this context
- \param type the type of certificate-like object provided by this context
- */
- CertBase(Provider *p, const QString &type) : BasicContext(p, type) {}
+ \param p the provider associated with this context
+ \param type the type of certificate-like object provided by this context
+ */
+ CertBase(Provider *p, const QString &type) : BasicContext(p, type) {}
- /**
- Convert this object to DER format, and return the value
+ /**
+ Convert this object to DER format, and return the value
- Returns an empty array on error.
- */
- virtual QByteArray toDER() const = 0;
+ Returns an empty array on error.
+ */
+ virtual QByteArray toDER() const = 0;
- /**
- Convert this object to PEM format, and return the value
+ /**
+ Convert this object to PEM format, and return the value
- Returns an empty string on error.
- */
- virtual QString toPEM() const = 0;
+ Returns an empty string on error.
+ */
+ virtual QString toPEM() const = 0;
- /**
- Read DER-formatted input and convert it into this object
+ /**
+ Read DER-formatted input and convert it into this object
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param a the input data
- */
- virtual ConvertResult fromDER(const QByteArray &a) = 0;
+ \param a the input data
+ */
+ virtual ConvertResult fromDER(const QByteArray &a) = 0;
- /**
- Read PEM-formatted input and convert it into this object
+ /**
+ Read PEM-formatted input and convert it into this object
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param s the input data
- */
- virtual ConvertResult fromPEM(const QString &s) = 0;
+ \param s the input data
+ */
+ virtual ConvertResult fromPEM(const QString &s) = 0;
};
/**
\class CertContextProps qcaprovider.h QtCrypto
X.509 certificate or certificate request properties
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want Certificate or
CertificateRequest instead.
Some fields are only for certificates or only for certificate requests,
and these fields are noted.
\ingroup ProviderAPI
*/
class QCA_EXPORT CertContextProps
{
public:
- /**
- The X.509 certificate version, usually 3
+ /**
+ The X.509 certificate version, usually 3
- This field is for certificates only.
- */
- int version;
+ This field is for certificates only.
+ */
+ int version;
- /**
- The time the certificate becomes valid (often the time of create)
+ /**
+ The time the certificate becomes valid (often the time of create)
- This field is for certificates only.
- */
- QDateTime start;
+ This field is for certificates only.
+ */
+ QDateTime start;
- /**
- The time the certificate expires
+ /**
+ The time the certificate expires
- This field is for certificates only.
- */
- QDateTime end;
+ This field is for certificates only.
+ */
+ QDateTime end;
- /**
- The subject information
- */
- CertificateInfoOrdered subject;
+ /**
+ The subject information
+ */
+ CertificateInfoOrdered subject;
- /**
- The issuer information
+ /**
+ The issuer information
- This field is for certificates only.
- */
- CertificateInfoOrdered issuer;
+ This field is for certificates only.
+ */
+ CertificateInfoOrdered issuer;
- /**
- The constraints
- */
- Constraints constraints;
+ /**
+ The constraints
+ */
+ Constraints constraints;
- /**
- The policies
- */
- QStringList policies;
+ /**
+ The policies
+ */
+ QStringList policies;
- /**
- A list of URIs for CRLs
+ /**
+ A list of URIs for CRLs
- This field is for certificates only.
- */
- QStringList crlLocations;
+ This field is for certificates only.
+ */
+ QStringList crlLocations;
- /**
- A list of URIs for issuer certificates
+ /**
+ A list of URIs for issuer certificates
- This field is for certificates only.
- */
- QStringList issuerLocations;
+ This field is for certificates only.
+ */
+ QStringList issuerLocations;
- /**
- A list of URIs for OCSP services
+ /**
+ A list of URIs for OCSP services
- This field is for certificates only.
- */
- QStringList ocspLocations;
+ This field is for certificates only.
+ */
+ QStringList ocspLocations;
- /**
- The certificate serial number
+ /**
+ The certificate serial number
- This field is for certificates only.
- */
- BigInteger serial;
+ This field is for certificates only.
+ */
+ BigInteger serial;
- /**
- True if the certificate is a CA or the certificate request is
- requesting to be a CA, otherwise false
- */
- bool isCA;
+ /**
+ True if the certificate is a CA or the certificate request is
+ requesting to be a CA, otherwise false
+ */
+ bool isCA;
- /**
- True if the certificate is self-signed
+ /**
+ True if the certificate is self-signed
- This field is for certificates only.
- */
- bool isSelfSigned;
+ This field is for certificates only.
+ */
+ bool isSelfSigned;
- /**
- The path limit
- */
- int pathLimit;
+ /**
+ The path limit
+ */
+ int pathLimit;
- /**
- The signature data
- */
- QByteArray sig;
+ /**
+ The signature data
+ */
+ QByteArray sig;
- /**
- The signature algorithm used to create the signature
- */
- SignatureAlgorithm sigalgo;
+ /**
+ The signature algorithm used to create the signature
+ */
+ SignatureAlgorithm sigalgo;
- /**
- The subject id
+ /**
+ The subject id
- This field is for certificates only.
- */
- QByteArray subjectId;
+ This field is for certificates only.
+ */
+ QByteArray subjectId;
- /**
- The issuer id
+ /**
+ The issuer id
- This field is for certificates only.
- */
- QByteArray issuerId;
+ This field is for certificates only.
+ */
+ QByteArray issuerId;
- /**
- The SPKAC challenge value
+ /**
+ The SPKAC challenge value
- This field is for certificate requests only.
- */
- QString challenge;
+ This field is for certificate requests only.
+ */
+ QString challenge;
- /**
- The format used for the certificate request
+ /**
+ The format used for the certificate request
- This field is for certificate requests only.
- */
- CertificateRequestFormat format;
+ This field is for certificate requests only.
+ */
+ CertificateRequestFormat format;
};
/**
\class CRLContextProps qcaprovider.h QtCrypto
X.509 certificate revocation list properties
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want CRL instead.
For efficiency and simplicity, the members are directly accessed.
\ingroup ProviderAPI
*/
class QCA_EXPORT CRLContextProps
{
public:
- /**
- The issuer information of the CRL
- */
- CertificateInfoOrdered issuer;
-
- /**
- The CRL number, which increases at each update
- */
- int number;
-
- /**
- The time this CRL was created
- */
- QDateTime thisUpdate;
-
- /**
- The time this CRL expires, and the next CRL should be fetched
- */
- QDateTime nextUpdate;
-
- /**
- The revoked entries
- */
- QList<CRLEntry> revoked;
-
- /**
- The signature data of the CRL
- */
- QByteArray sig;
-
- /**
- The signature algorithm used by the issuer to sign the CRL
- */
- SignatureAlgorithm sigalgo;
-
- /**
- The issuer id
- */
- QByteArray issuerId;
+ /**
+ The issuer information of the CRL
+ */
+ CertificateInfoOrdered issuer;
+
+ /**
+ The CRL number, which increases at each update
+ */
+ int number;
+
+ /**
+ The time this CRL was created
+ */
+ QDateTime thisUpdate;
+
+ /**
+ The time this CRL expires, and the next CRL should be fetched
+ */
+ QDateTime nextUpdate;
+
+ /**
+ The revoked entries
+ */
+ QList<CRLEntry> revoked;
+
+ /**
+ The signature data of the CRL
+ */
+ QByteArray sig;
+
+ /**
+ The signature algorithm used by the issuer to sign the CRL
+ */
+ SignatureAlgorithm sigalgo;
+
+ /**
+ The issuer id
+ */
+ QByteArray issuerId;
};
class CRLContext;
/**
\class CertContext qcaprovider.h QtCrypto
X.509 certificate provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want Certificate instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT CertContext : public CertBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- */
- CertContext(Provider *p) : CertBase(p, QStringLiteral("cert")) {}
-
- /**
- Create a self-signed certificate based on the given options and
- private key. Returns true if successful, otherwise false.
-
- If successful, this object becomes the self-signed certificate.
- If unsuccessful, this object is considered to be in an
- uninitialized state.
-
- \param opts the options to set on the certificate
- \param priv the key to be used to sign the certificate
- */
- virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv) = 0;
-
- /**
- Returns a pointer to the properties of this certificate
- */
- virtual const CertContextProps *props() const = 0;
-
- /**
- Returns true if this certificate is equal to another certificate,
- otherwise false
-
- \param other the certificate to compare with
- */
- virtual bool compare(const CertContext *other) const = 0;
-
- /**
- Returns a copy of this certificate's public key. The caller is
- responsible for deleting it.
- */
- virtual PKeyContext *subjectPublicKey() const = 0;
-
- /**
- Returns true if this certificate is an issuer of another
- certificate, otherwise false
-
- \param other the issued certificate to check
- */
- virtual bool isIssuerOf(const CertContext *other) const = 0;
-
- /**
- Validate this certificate
-
- This function is blocking.
-
- \param trusted list of trusted certificates
- \param untrusted list of untrusted certificates (can be empty)
- \param crls list of CRLs (can be empty)
- \param u the desired usage for this certificate
- \param vf validation options
- */
- virtual Validity validate(const QList<CertContext*> &trusted, const QList<CertContext*> &untrusted, const QList<CRLContext*> &crls, UsageMode u, ValidateFlags vf) const = 0;
-
- /**
- Validate a certificate chain. This function makes no use of the
- certificate represented by this object, and it can be used even
- if this object is in an uninitialized state.
-
- This function is blocking.
-
- \param chain list of certificates in the chain, starting with the
- user certificate. It is not necessary for the chain to contain
- the final root certificate.
- \param trusted list of trusted certificates
- \param crls list of CRLs (can be empty)
- \param u the desired usage for the user certificate in the chain
- \param vf validation options
- */
- virtual Validity validate_chain(const QList<CertContext*> &chain, const QList<CertContext*> &trusted, const QList<CRLContext*> &crls, UsageMode u, ValidateFlags vf) const = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ */
+ CertContext(Provider *p) : CertBase(p, QStringLiteral("cert")) {}
+
+ /**
+ Create a self-signed certificate based on the given options and
+ private key. Returns true if successful, otherwise false.
+
+ If successful, this object becomes the self-signed certificate.
+ If unsuccessful, this object is considered to be in an
+ uninitialized state.
+
+ \param opts the options to set on the certificate
+ \param priv the key to be used to sign the certificate
+ */
+ virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv) = 0;
+
+ /**
+ Returns a pointer to the properties of this certificate
+ */
+ virtual const CertContextProps *props() const = 0;
+
+ /**
+ Returns true if this certificate is equal to another certificate,
+ otherwise false
+
+ \param other the certificate to compare with
+ */
+ virtual bool compare(const CertContext *other) const = 0;
+
+ /**
+ Returns a copy of this certificate's public key. The caller is
+ responsible for deleting it.
+ */
+ virtual PKeyContext *subjectPublicKey() const = 0;
+
+ /**
+ Returns true if this certificate is an issuer of another
+ certificate, otherwise false
+
+ \param other the issued certificate to check
+ */
+ virtual bool isIssuerOf(const CertContext *other) const = 0;
+
+ /**
+ Validate this certificate
+
+ This function is blocking.
+
+ \param trusted list of trusted certificates
+ \param untrusted list of untrusted certificates (can be empty)
+ \param crls list of CRLs (can be empty)
+ \param u the desired usage for this certificate
+ \param vf validation options
+ */
+ virtual Validity validate(const QList<CertContext *> &trusted, const QList<CertContext *> &untrusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const = 0;
+
+ /**
+ Validate a certificate chain. This function makes no use of the
+ certificate represented by this object, and it can be used even
+ if this object is in an uninitialized state.
+
+ This function is blocking.
+
+ \param chain list of certificates in the chain, starting with the
+ user certificate. It is not necessary for the chain to contain
+ the final root certificate.
+ \param trusted list of trusted certificates
+ \param crls list of CRLs (can be empty)
+ \param u the desired usage for the user certificate in the chain
+ \param vf validation options
+ */
+ virtual Validity validate_chain(const QList<CertContext *> &chain, const QList<CertContext *> &trusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const = 0;
};
/**
\class CSRContext qcaprovider.h QtCrypto
X.509 certificate request provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want CertificateRequest
instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT CSRContext : public CertBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the provider associated with this context
- */
- CSRContext(Provider *p) : CertBase(p, QStringLiteral("csr")) {}
-
- /**
- Returns true if the provider of this object supports the specified
- format, otherwise false
-
- \param f the format to test for support for.
- */
- virtual bool canUseFormat(CertificateRequestFormat f) const = 0;
-
- /**
- Create a certificate request based on the given options and
- private key. Returns true if successful, otherwise false.
-
- If successful, this object becomes the certificate request.
- If unsuccessful, this object is considered to be in an
- uninitialized state.
-
- \param opts the options to set on the certificate
- \param priv the key to be used to sign the certificate
- */
- virtual bool createRequest(const CertificateOptions &opts, const PKeyContext &priv) = 0;
-
- /**
- Returns a pointer to the properties of this certificate request
- */
- virtual const CertContextProps *props() const = 0;
-
- /**
- Returns true if this certificate request is equal to another
- certificate request, otherwise false
-
- \param other the certificate request to compare with
- */
- virtual bool compare(const CSRContext *other) const = 0;
-
- /**
- Returns a copy of this certificate request's public key. The
- caller is responsible for deleting it.
- */
- virtual PKeyContext *subjectPublicKey() const = 0;
-
- /**
- Convert this certificate request to Netscape SPKAC format, and
- return the value
-
- Returns an empty string on error.
- */
- virtual QString toSPKAC() const = 0;
-
- /**
- Read Netscape SPKAC input and convert it into a certificate
- request
-
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
-
- \param s the input data
- */
- virtual ConvertResult fromSPKAC(const QString &s) = 0;
+ /**
+ Standard constructor
+
+ \param p the provider associated with this context
+ */
+ CSRContext(Provider *p) : CertBase(p, QStringLiteral("csr")) {}
+
+ /**
+ Returns true if the provider of this object supports the specified
+ format, otherwise false
+
+ \param f the format to test for support for.
+ */
+ virtual bool canUseFormat(CertificateRequestFormat f) const = 0;
+
+ /**
+ Create a certificate request based on the given options and
+ private key. Returns true if successful, otherwise false.
+
+ If successful, this object becomes the certificate request.
+ If unsuccessful, this object is considered to be in an
+ uninitialized state.
+
+ \param opts the options to set on the certificate
+ \param priv the key to be used to sign the certificate
+ */
+ virtual bool createRequest(const CertificateOptions &opts, const PKeyContext &priv) = 0;
+
+ /**
+ Returns a pointer to the properties of this certificate request
+ */
+ virtual const CertContextProps *props() const = 0;
+
+ /**
+ Returns true if this certificate request is equal to another
+ certificate request, otherwise false
+
+ \param other the certificate request to compare with
+ */
+ virtual bool compare(const CSRContext *other) const = 0;
+
+ /**
+ Returns a copy of this certificate request's public key. The
+ caller is responsible for deleting it.
+ */
+ virtual PKeyContext *subjectPublicKey() const = 0;
+
+ /**
+ Convert this certificate request to Netscape SPKAC format, and
+ return the value
+
+ Returns an empty string on error.
+ */
+ virtual QString toSPKAC() const = 0;
+
+ /**
+ Read Netscape SPKAC input and convert it into a certificate
+ request
+
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
+
+ \param s the input data
+ */
+ virtual ConvertResult fromSPKAC(const QString &s) = 0;
};
/**
\class CRLContext qcaprovider.h QtCrypto
X.509 certificate revocation list provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want CRL instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT CRLContext : public CertBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the provider associated with this context
- */
- CRLContext(Provider *p) : CertBase(p, QStringLiteral("crl")) {}
+ \param p the provider associated with this context
+ */
+ CRLContext(Provider *p) : CertBase(p, QStringLiteral("crl")) {}
- /**
- Returns a pointer to the properties of this CRL
- */
- virtual const CRLContextProps *props() const = 0;
+ /**
+ Returns a pointer to the properties of this CRL
+ */
+ virtual const CRLContextProps *props() const = 0;
- /**
- Returns true if this CRL is equal to another CRL, otherwise false
+ /**
+ Returns true if this CRL is equal to another CRL, otherwise false
- \param other the CRL to compare with
- */
- virtual bool compare(const CRLContext *other) const = 0;
+ \param other the CRL to compare with
+ */
+ virtual bool compare(const CRLContext *other) const = 0;
};
/**
\class CertCollectionContext qcaprovider.h QtCrypto
X.509 certificate collection provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want CertificateCollection
instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT CertCollectionContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the provider associated with this context
- */
- CertCollectionContext(Provider *p) : BasicContext(p, QStringLiteral("certcollection")) {}
+ \param p the provider associated with this context
+ */
+ CertCollectionContext(Provider *p) : BasicContext(p, QStringLiteral("certcollection")) {}
- /**
- Create PKCS#7 DER output based on the input certificates and CRLs
+ /**
+ Create PKCS#7 DER output based on the input certificates and CRLs
- Returns an empty array on error.
+ Returns an empty array on error.
- \param certs list of certificates to store in the output
- \param crls list of CRLs to store in the output
- */
- virtual QByteArray toPKCS7(const QList<CertContext*> &certs, const QList<CRLContext*> &crls) const = 0;
+ \param certs list of certificates to store in the output
+ \param crls list of CRLs to store in the output
+ */
+ virtual QByteArray toPKCS7(const QList<CertContext *> &certs, const QList<CRLContext *> &crls) const = 0;
- /**
- Read PKCS#7 DER input and convert it into a list of certificates
- and CRLs
+ /**
+ Read PKCS#7 DER input and convert it into a list of certificates
+ and CRLs
- The caller is responsible for deleting the returned items.
+ The caller is responsible for deleting the returned items.
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param a the input data
- \param certs the destination list for the certificates
- \param crls the destination list for the CRLs
- */
- virtual ConvertResult fromPKCS7(const QByteArray &a, QList<CertContext*> *certs, QList<CRLContext*> *crls) const = 0;
+ \param a the input data
+ \param certs the destination list for the certificates
+ \param crls the destination list for the CRLs
+ */
+ virtual ConvertResult fromPKCS7(const QByteArray &a, QList<CertContext *> *certs, QList<CRLContext *> *crls) const = 0;
};
/**
\class CAContext qcaprovider.h QtCrypto
X.509 certificate authority provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want CertificateAuthority
instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT CAContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the Provider associated with this context
- */
- CAContext(Provider *p) : BasicContext(p, QStringLiteral("ca")) {}
-
- /**
- Prepare the object for usage
-
- This must be called before any CA operations are performed.
-
- \param cert the certificate of the CA
- \param priv the private key of the CA
- */
- virtual void setup(const CertContext &cert, const PKeyContext &priv) = 0;
-
- /**
- Returns a copy of the CA's certificate. The caller is responsible
- for deleting it.
- */
- virtual CertContext *certificate() const = 0;
-
- /**
- Issue a certificate based on a certificate request, and return
- the certificate. The caller is responsible for deleting it.
-
- \param req the certificate request
- \param notValidAfter the expiration date
- */
- virtual CertContext *signRequest(const CSRContext &req, const QDateTime &notValidAfter) const = 0;
-
- /**
- Issue a certificate based on a public key and options, and return
- the certificate. The caller is responsible for deleting it.
-
- \param pub the public key of the certificate
- \param opts the options to use for generation
- */
- virtual CertContext *createCertificate(const PKeyContext &pub, const CertificateOptions &opts) const = 0;
-
- /**
- Create a new CRL and return it. The caller is responsible for
- deleting it.
-
- The CRL has no entries in it.
-
- \param nextUpdate the expiration date of the CRL
- */
- virtual CRLContext *createCRL(const QDateTime &nextUpdate) const = 0;
-
- /**
- Update an existing CRL, by examining an old one and creating a new
- one based on it. The new CRL is returned, and the caller is
- responsible for deleting it.
-
- \param crl an existing CRL issued by this CA
- \param entries the list of revoked entries
- \param nextUpdate the expiration date of the new CRL
- */
- virtual CRLContext *updateCRL(const CRLContext &crl, const QList<CRLEntry> &entries, const QDateTime &nextUpdate) const = 0;
+ /**
+ Standard constructor
+
+ \param p the Provider associated with this context
+ */
+ CAContext(Provider *p) : BasicContext(p, QStringLiteral("ca")) {}
+
+ /**
+ Prepare the object for usage
+
+ This must be called before any CA operations are performed.
+
+ \param cert the certificate of the CA
+ \param priv the private key of the CA
+ */
+ virtual void setup(const CertContext &cert, const PKeyContext &priv) = 0;
+
+ /**
+ Returns a copy of the CA's certificate. The caller is responsible
+ for deleting it.
+ */
+ virtual CertContext *certificate() const = 0;
+
+ /**
+ Issue a certificate based on a certificate request, and return
+ the certificate. The caller is responsible for deleting it.
+
+ \param req the certificate request
+ \param notValidAfter the expiration date
+ */
+ virtual CertContext *signRequest(const CSRContext &req, const QDateTime &notValidAfter) const = 0;
+
+ /**
+ Issue a certificate based on a public key and options, and return
+ the certificate. The caller is responsible for deleting it.
+
+ \param pub the public key of the certificate
+ \param opts the options to use for generation
+ */
+ virtual CertContext *createCertificate(const PKeyContext &pub, const CertificateOptions &opts) const = 0;
+
+ /**
+ Create a new CRL and return it. The caller is responsible for
+ deleting it.
+
+ The CRL has no entries in it.
+
+ \param nextUpdate the expiration date of the CRL
+ */
+ virtual CRLContext *createCRL(const QDateTime &nextUpdate) const = 0;
+
+ /**
+ Update an existing CRL, by examining an old one and creating a new
+ one based on it. The new CRL is returned, and the caller is
+ responsible for deleting it.
+
+ \param crl an existing CRL issued by this CA
+ \param entries the list of revoked entries
+ \param nextUpdate the expiration date of the new CRL
+ */
+ virtual CRLContext *updateCRL(const CRLContext &crl, const QList<CRLEntry> &entries, const QDateTime &nextUpdate) const = 0;
};
/**
\class PKCS12Context qcaprovider.h QtCrypto
PKCS#12 provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want KeyBundle instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT PKCS12Context : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the Provider associated with this context
- */
- PKCS12Context(Provider *p) : BasicContext(p, QStringLiteral("pkcs12")) {}
+ \param p the Provider associated with this context
+ */
+ PKCS12Context(Provider *p) : BasicContext(p, QStringLiteral("pkcs12")) {}
- /**
- Create PKCS#12 DER output based on a set of input items
+ /**
+ Create PKCS#12 DER output based on a set of input items
- Returns an empty array on error.
+ Returns an empty array on error.
- \param name the friendly name of the data
- \param chain the certificate chain to store
- \param priv the private key to store
- \param passphrase the passphrase to encrypt the PKCS#12 data with
- */
- virtual QByteArray toPKCS12(const QString &name, const QList<const CertContext*> &chain, const PKeyContext &priv, const SecureArray &passphrase) const = 0;
+ \param name the friendly name of the data
+ \param chain the certificate chain to store
+ \param priv the private key to store
+ \param passphrase the passphrase to encrypt the PKCS#12 data with
+ */
+ virtual QByteArray toPKCS12(const QString &name, const QList<const CertContext *> &chain, const PKeyContext &priv, const SecureArray &passphrase) const = 0;
- /**
- Read PKCS#12 DER input and convert it into a set of output items
+ /**
+ Read PKCS#12 DER input and convert it into a set of output items
- The caller is responsible for deleting the returned items.
+ The caller is responsible for deleting the returned items.
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param in the input data
- \param passphrase the passphrase needed to decrypt the input data
- \param name the destination string for the friendly name
- \param chain the destination list for the certificate chain
- \param priv address of a pointer to accept the private key
- */
- virtual ConvertResult fromPKCS12(const QByteArray &in, const SecureArray &passphrase, QString *name, QList<CertContext*> *chain, PKeyContext **priv) const = 0;
+ \param in the input data
+ \param passphrase the passphrase needed to decrypt the input data
+ \param name the destination string for the friendly name
+ \param chain the destination list for the certificate chain
+ \param priv address of a pointer to accept the private key
+ */
+ virtual ConvertResult fromPKCS12(const QByteArray &in, const SecureArray &passphrase, QString *name, QList<CertContext *> *chain, PKeyContext **priv) const = 0;
};
/**
\class PGPKeyContextProps qcaprovider.h QtCrypto
OpenPGP key properties
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want PGPKey instead.
For efficiency and simplicity, the members are directly accessed.
\ingroup ProviderAPI
*/
class QCA_EXPORT PGPKeyContextProps
{
public:
- /**
- The key id
- */
- QString keyId;
-
- /**
- List of user id strings for the key, the first one being the
- primary user id
- */
- QStringList userIds;
-
- /**
- True if this key is a secret key, otherwise false
- */
- bool isSecret;
-
- /**
- The time the key was created
- */
- QDateTime creationDate;
-
- /**
- The time the key expires
- */
- QDateTime expirationDate;
-
- /**
- The hex fingerprint of the key
-
- The format is all lowercase with no spaces.
- */
- QString fingerprint;
-
- /**
- True if this key is in a keyring (and thus usable), otherwise
- false
- */
- bool inKeyring;
-
- /**
- True if this key is trusted (e.g. signed by the keyring owner or
- via some web-of-trust), otherwise false
- */
- bool isTrusted;
+ /**
+ The key id
+ */
+ QString keyId;
+
+ /**
+ List of user id strings for the key, the first one being the
+ primary user id
+ */
+ QStringList userIds;
+
+ /**
+ True if this key is a secret key, otherwise false
+ */
+ bool isSecret;
+
+ /**
+ The time the key was created
+ */
+ QDateTime creationDate;
+
+ /**
+ The time the key expires
+ */
+ QDateTime expirationDate;
+
+ /**
+ The hex fingerprint of the key
+
+ The format is all lowercase with no spaces.
+ */
+ QString fingerprint;
+
+ /**
+ True if this key is in a keyring (and thus usable), otherwise
+ false
+ */
+ bool inKeyring;
+
+ /**
+ True if this key is trusted (e.g. signed by the keyring owner or
+ via some web-of-trust), otherwise false
+ */
+ bool isTrusted;
};
/**
\class PGPKeyContext qcaprovider.h QtCrypto
OpenPGP key provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want PGPKey instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT PGPKeyContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the Provider associated with this context
- */
- PGPKeyContext(Provider *p) : BasicContext(p, QStringLiteral("pgpkey")) {}
+ \param p the Provider associated with this context
+ */
+ PGPKeyContext(Provider *p) : BasicContext(p, QStringLiteral("pgpkey")) {}
- /**
- Returns a pointer to the properties of this key
- */
- virtual const PGPKeyContextProps *props() const = 0;
+ /**
+ Returns a pointer to the properties of this key
+ */
+ virtual const PGPKeyContextProps *props() const = 0;
- /**
- Convert the key to binary format, and return the value
- */
- virtual QByteArray toBinary() const = 0;
+ /**
+ Convert the key to binary format, and return the value
+ */
+ virtual QByteArray toBinary() const = 0;
- /**
- Convert the key to ascii-armored format, and return the value
- */
- virtual QString toAscii() const = 0;
+ /**
+ Convert the key to ascii-armored format, and return the value
+ */
+ virtual QString toAscii() const = 0;
- /**
- Read binary input and convert it into a key
+ /**
+ Read binary input and convert it into a key
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param a the input data
- */
- virtual ConvertResult fromBinary(const QByteArray &a) = 0;
+ \param a the input data
+ */
+ virtual ConvertResult fromBinary(const QByteArray &a) = 0;
- /**
- Read ascii-armored input and convert it into a key
+ /**
+ Read ascii-armored input and convert it into a key
- Returns QCA::ConvertGood if successful, otherwise some error
- value.
+ Returns QCA::ConvertGood if successful, otherwise some error
+ value.
- \param s the input data
- */
- virtual ConvertResult fromAscii(const QString &s) = 0;
+ \param s the input data
+ */
+ virtual ConvertResult fromAscii(const QString &s) = 0;
};
/**
\class KeyStoreEntryContext qcaprovider.h QtCrypto
KeyStoreEntry provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want KeyStoreEntry
instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT KeyStoreEntryContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
-
- \param p the Provider associated with this context
- */
- KeyStoreEntryContext(Provider *p) : BasicContext(p, QStringLiteral("keystoreentry")) {}
-
- /**
- Returns the entry type
- */
- virtual KeyStoreEntry::Type type() const = 0;
-
- /**
- Returns the entry id
-
- This id must be unique among all other entries in the same store.
- */
- virtual QString id() const = 0;
-
- /**
- Returns the name of this entry
- */
- virtual QString name() const = 0;
-
- /**
- Returns the id of the store that contains this entry
- */
- virtual QString storeId() const = 0;
-
- /**
- Returns the name of the store that contains this entry
- */
- virtual QString storeName() const = 0;
-
- /**
- Returns true if the private key of this entry is present for use
- */
- virtual bool isAvailable() const;
-
- /**
- Serialize the information about this entry
-
- This allows the entry object to be restored later, even if the
- store that contains it is not present.
-
- \sa KeyStoreListContext::entryPassive()
- */
- virtual QString serialize() const = 0;
-
- /**
- If this entry is of type KeyStoreEntry::TypeKeyBundle, this
- function returns the KeyBundle of the entry
- */
- virtual KeyBundle keyBundle() const;
-
- /**
- If this entry is of type KeyStoreEntry::TypeCertificate, this
- function returns the Certificate of the entry
- */
- virtual Certificate certificate() const;
-
- /**
- If this entry is of type KeyStoreEntry::TypeCRL, this function
- returns the CRL of the entry
- */
- virtual CRL crl() const;
-
- /**
- If this entry is of type KeyStoreEntry::TypePGPSecretKey, this
- function returns the secret PGPKey of the entry
- */
- virtual PGPKey pgpSecretKey() const;
-
- /**
- If this entry is of type KeyStoreEntry::TypePGPPublicKey or
- KeyStoreEntry::TypePGPSecretKey, this function returns the public
- PGPKey of the entry
- */
- virtual PGPKey pgpPublicKey() const;
-
- /**
- Attempt to ensure the private key of this entry is usable and
- accessible, potentially prompting the user and/or performing a
- login to a token device. Returns true if the entry is now
- accessible, or false if the entry cannot be made accessible.
-
- This function is blocking.
- */
- virtual bool ensureAccess();
+ /**
+ Standard constructor
+
+ \param p the Provider associated with this context
+ */
+ KeyStoreEntryContext(Provider *p) : BasicContext(p, QStringLiteral("keystoreentry")) {}
+
+ /**
+ Returns the entry type
+ */
+ virtual KeyStoreEntry::Type type() const = 0;
+
+ /**
+ Returns the entry id
+
+ This id must be unique among all other entries in the same store.
+ */
+ virtual QString id() const = 0;
+
+ /**
+ Returns the name of this entry
+ */
+ virtual QString name() const = 0;
+
+ /**
+ Returns the id of the store that contains this entry
+ */
+ virtual QString storeId() const = 0;
+
+ /**
+ Returns the name of the store that contains this entry
+ */
+ virtual QString storeName() const = 0;
+
+ /**
+ Returns true if the private key of this entry is present for use
+ */
+ virtual bool isAvailable() const;
+
+ /**
+ Serialize the information about this entry
+
+ This allows the entry object to be restored later, even if the
+ store that contains it is not present.
+
+ \sa KeyStoreListContext::entryPassive()
+ */
+ virtual QString serialize() const = 0;
+
+ /**
+ If this entry is of type KeyStoreEntry::TypeKeyBundle, this
+ function returns the KeyBundle of the entry
+ */
+ virtual KeyBundle keyBundle() const;
+
+ /**
+ If this entry is of type KeyStoreEntry::TypeCertificate, this
+ function returns the Certificate of the entry
+ */
+ virtual Certificate certificate() const;
+
+ /**
+ If this entry is of type KeyStoreEntry::TypeCRL, this function
+ returns the CRL of the entry
+ */
+ virtual CRL crl() const;
+
+ /**
+ If this entry is of type KeyStoreEntry::TypePGPSecretKey, this
+ function returns the secret PGPKey of the entry
+ */
+ virtual PGPKey pgpSecretKey() const;
+
+ /**
+ If this entry is of type KeyStoreEntry::TypePGPPublicKey or
+ KeyStoreEntry::TypePGPSecretKey, this function returns the public
+ PGPKey of the entry
+ */
+ virtual PGPKey pgpPublicKey() const;
+
+ /**
+ Attempt to ensure the private key of this entry is usable and
+ accessible, potentially prompting the user and/or performing a
+ login to a token device. Returns true if the entry is now
+ accessible, or false if the entry cannot be made accessible.
+
+ This function is blocking.
+ */
+ virtual bool ensureAccess();
};
/**
\class KeyStoreListContext qcaprovider.h QtCrypto
KeyStore provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want KeyStore instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT KeyStoreListContext : public Provider::Context
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the Provider associated with this context
- */
- KeyStoreListContext(Provider *p) : Provider::Context(p, QStringLiteral("keystorelist")) {}
+ \param p the Provider associated with this context
+ */
+ KeyStoreListContext(Provider *p) : Provider::Context(p, QStringLiteral("keystorelist")) {}
- /**
- Starts the keystore provider
- */
- virtual void start();
+ /**
+ Starts the keystore provider
+ */
+ virtual void start();
- /**
- Enables or disables update events
+ /**
+ Enables or disables update events
- The updated() and storeUpdated() signals might not be emitted if
- updates are not enabled.
+ The updated() and storeUpdated() signals might not be emitted if
+ updates are not enabled.
- \param enabled whether update notifications are enabled (true) or disabled (false)
- */
- virtual void setUpdatesEnabled(bool enabled);
+ \param enabled whether update notifications are enabled (true) or disabled (false)
+ */
+ virtual void setUpdatesEnabled(bool enabled);
- /**
- Returns a list of integer context ids, each representing a
- keystore instance
+ /**
+ Returns a list of integer context ids, each representing a
+ keystore instance
- If a keystore becomes unavailable and then later becomes
- available again (for example, if a smart card is removed and
- then the same one is inserted again), the integer context id
- must be different than last time.
- */
- virtual QList<int> keyStores() = 0;
+ If a keystore becomes unavailable and then later becomes
+ available again (for example, if a smart card is removed and
+ then the same one is inserted again), the integer context id
+ must be different than last time.
+ */
+ virtual QList<int> keyStores() = 0;
- /**
- Returns the type of the specified store, or -1 if the integer
- context id is invalid
+ /**
+ Returns the type of the specified store, or -1 if the integer
+ context id is invalid
- \param id the id for the store context
- */
- virtual KeyStore::Type type(int id) const = 0;
+ \param id the id for the store context
+ */
+ virtual KeyStore::Type type(int id) const = 0;
- /**
- Returns the string id of the store, or an empty string if the
- integer context id is invalid
+ /**
+ Returns the string id of the store, or an empty string if the
+ integer context id is invalid
- The string id of the store should be unique to a single store, and
- it should persist between availability/unavailability. For
- example, a smart card that is removed and inserted again should
- have the same string id (despite having a new integer context id).
+ The string id of the store should be unique to a single store, and
+ it should persist between availability/unavailability. For
+ example, a smart card that is removed and inserted again should
+ have the same string id (despite having a new integer context id).
- \param id the id for the store context
- */
- virtual QString storeId(int id) const = 0;
+ \param id the id for the store context
+ */
+ virtual QString storeId(int id) const = 0;
- /**
- Returns the friendly name of the store, or an empty string if the
- integer context id is invalid
+ /**
+ Returns the friendly name of the store, or an empty string if the
+ integer context id is invalid
- \param id the id for the store context
- */
- virtual QString name(int id) const = 0;
+ \param id the id for the store context
+ */
+ virtual QString name(int id) const = 0;
- /**
- Returns true if the store is read-only
+ /**
+ Returns true if the store is read-only
- If the integer context id is invalid, this function should return
- true.
+ If the integer context id is invalid, this function should return
+ true.
- \param id the id for the store context
- */
- virtual bool isReadOnly(int id) const;
+ \param id the id for the store context
+ */
+ virtual bool isReadOnly(int id) const;
- /**
- Returns the types supported by the store, or an empty list if the
- integer context id is invalid
+ /**
+ Returns the types supported by the store, or an empty list if the
+ integer context id is invalid
- This function should return all supported types, even if the store
- doesn't actually contain entries for all of the types.
+ This function should return all supported types, even if the store
+ doesn't actually contain entries for all of the types.
- \param id the id for the store context
- */
- virtual QList<KeyStoreEntry::Type> entryTypes(int id) const = 0;
+ \param id the id for the store context
+ */
+ virtual QList<KeyStoreEntry::Type> entryTypes(int id) const = 0;
- /**
- Returns the entries of the store, or an empty list if the integer
- context id is invalid
+ /**
+ Returns the entries of the store, or an empty list if the integer
+ context id is invalid
- The caller is responsible for deleting the returned entry objects.
+ The caller is responsible for deleting the returned entry objects.
- \param id the id for the store context
- */
- virtual QList<KeyStoreEntryContext*> entryList(int id) = 0;
+ \param id the id for the store context
+ */
+ virtual QList<KeyStoreEntryContext *> entryList(int id) = 0;
- /**
- Returns a single entry in the store, if the entry id is already
- known. If the entry does not exist, the function returns 0.
+ /**
+ Returns a single entry in the store, if the entry id is already
+ known. If the entry does not exist, the function returns 0.
- The caller is responsible for deleting the returned entry object.
+ The caller is responsible for deleting the returned entry object.
- \param id the id for the store context
- \param entryId the entry to retrieve
- */
- virtual KeyStoreEntryContext *entry(int id, const QString &entryId);
+ \param id the id for the store context
+ \param entryId the entry to retrieve
+ */
+ virtual KeyStoreEntryContext *entry(int id, const QString &entryId);
- /**
- Returns a single entry, created from the serialization string of
- a previous entry (using KeyStoreEntryContext::serialize()). If
- the serialization string cannot be parsed by this provider, or the
- entry cannot otherwise be created, the function returns 0.
+ /**
+ Returns a single entry, created from the serialization string of
+ a previous entry (using KeyStoreEntryContext::serialize()). If
+ the serialization string cannot be parsed by this provider, or the
+ entry cannot otherwise be created, the function returns 0.
- The caller is responsible for deleting the returned entry object.
+ The caller is responsible for deleting the returned entry object.
- This function must be thread-safe.
+ This function must be thread-safe.
- \param serialized the serialized data to create the entry from
- */
- virtual KeyStoreEntryContext *entryPassive(const QString &serialized);
+ \param serialized the serialized data to create the entry from
+ */
+ virtual KeyStoreEntryContext *entryPassive(const QString &serialized);
- /**
- Write a KeyBundle to the store
+ /**
+ Write a KeyBundle to the store
- Returns the entry id of the new item, or an empty string if there
- was an error writing the item.
+ Returns the entry id of the new item, or an empty string if there
+ was an error writing the item.
- \param id the id for the store context
- \param kb the key bundle to add to the store
- */
- virtual QString writeEntry(int id, const KeyBundle &kb);
+ \param id the id for the store context
+ \param kb the key bundle to add to the store
+ */
+ virtual QString writeEntry(int id, const KeyBundle &kb);
- /**
- Write a Certificate to the store
+ /**
+ Write a Certificate to the store
- Returns the entry id of the new item, or an empty string if there
- was an error writing the item.
+ Returns the entry id of the new item, or an empty string if there
+ was an error writing the item.
- \param id the id for the store context
- \param cert the certificate to add to the store
- */
- virtual QString writeEntry(int id, const Certificate &cert);
+ \param id the id for the store context
+ \param cert the certificate to add to the store
+ */
+ virtual QString writeEntry(int id, const Certificate &cert);
- /**
- Write a CRL to the store
+ /**
+ Write a CRL to the store
- Returns the entry id of the new item, or an empty string if there
- was an error writing the item.
+ Returns the entry id of the new item, or an empty string if there
+ was an error writing the item.
- \param id the id for the store context
- \param crl the revocation list to add to the store
- */
- virtual QString writeEntry(int id, const CRL &crl);
+ \param id the id for the store context
+ \param crl the revocation list to add to the store
+ */
+ virtual QString writeEntry(int id, const CRL &crl);
- /**
- Write a PGPKey to the store
+ /**
+ Write a PGPKey to the store
- Returns the entry id of the new item, or an empty string if there
- was an error writing the item.
+ Returns the entry id of the new item, or an empty string if there
+ was an error writing the item.
- \param id the id for the store context
- \param key the PGP key to add to the store
- */
- virtual QString writeEntry(int id, const PGPKey &key);
+ \param id the id for the store context
+ \param key the PGP key to add to the store
+ */
+ virtual QString writeEntry(int id, const PGPKey &key);
- /**
- Remove an entry from the store
+ /**
+ Remove an entry from the store
- Returns true if the entry is successfully removed, otherwise
- false.
+ Returns true if the entry is successfully removed, otherwise
+ false.
- \param id the id for the store context
- \param entryId the entry to remove from the store
- */
- virtual bool removeEntry(int id, const QString &entryId);
+ \param id the id for the store context
+ \param entryId the entry to remove from the store
+ */
+ virtual bool removeEntry(int id, const QString &entryId);
Q_SIGNALS:
- /**
- Emit this when the provider is busy looking for keystores. The
- provider goes into a busy state when it has reason to believe
- there are keystores present, but it still needs to check or query
- some devices to see for sure.
-
- For example, if a smart card is inserted, then the provider may
- immediately go into a busy state upon detecting the insert.
- However, it may take some seconds before the smart card
- information can be queried and reported by the provider. Once
- the card is queried successfully, the provider would leave the
- busy state and report the new keystore.
-
- When this object is first started with start(), it is assumed to
- be in the busy state, so there is no need to emit this signal at
- the beginning.
- */
- void busyStart();
-
- /**
- Emit this to leave the busy state
-
- When this object is first started with start(), it is assumed to
- be in the busy state. You must emit busyEnd() at some point, or
- QCA will never ask you about keystores.
- */
- void busyEnd();
-
- /**
- Indicates the list of keystores has changed, and that QCA should
- call keyStores() to obtain the latest list
- */
- void updated();
-
- /**
- Emitted when there is diagnostic text to report
-
- \param str the diagnostic text
- */
- void diagnosticText(const QString &str);
-
- /**
- Indicates that the entry list of a keystore has changed (entries
- added, removed, or modified)
-
- \param id the id of the key store that has changed
- */
- void storeUpdated(int id);
+ /**
+ Emit this when the provider is busy looking for keystores. The
+ provider goes into a busy state when it has reason to believe
+ there are keystores present, but it still needs to check or query
+ some devices to see for sure.
+
+ For example, if a smart card is inserted, then the provider may
+ immediately go into a busy state upon detecting the insert.
+ However, it may take some seconds before the smart card
+ information can be queried and reported by the provider. Once
+ the card is queried successfully, the provider would leave the
+ busy state and report the new keystore.
+
+ When this object is first started with start(), it is assumed to
+ be in the busy state, so there is no need to emit this signal at
+ the beginning.
+ */
+ void busyStart();
+
+ /**
+ Emit this to leave the busy state
+
+ When this object is first started with start(), it is assumed to
+ be in the busy state. You must emit busyEnd() at some point, or
+ QCA will never ask you about keystores.
+ */
+ void busyEnd();
+
+ /**
+ Indicates the list of keystores has changed, and that QCA should
+ call keyStores() to obtain the latest list
+ */
+ void updated();
+
+ /**
+ Emitted when there is diagnostic text to report
+
+ \param str the diagnostic text
+ */
+ void diagnosticText(const QString &str);
+
+ /**
+ Indicates that the entry list of a keystore has changed (entries
+ added, removed, or modified)
+
+ \param id the id of the key store that has changed
+ */
+ void storeUpdated(int id);
};
/**
\class TLSSessionContext qcaprovider.h QtCrypto
TLS "session" provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want TLSSession instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT TLSSessionContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the Provider associated with this context
- */
- TLSSessionContext(Provider *p) : BasicContext(p, QStringLiteral("tlssession")) {}
+ \param p the Provider associated with this context
+ */
+ TLSSessionContext(Provider *p) : BasicContext(p, QStringLiteral("tlssession")) {}
};
/**
\class TLSContext qcaprovider.h QtCrypto
TLS provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want TLS instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT TLSContext : public Provider::Context
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- \class QCA::TLSContext::SessionInfo qcaprovider.h QtCrypto
-
- Information about an active TLS connection
-
- For efficiency and simplicity, the members are directly accessed.
-
- \ingroup ProviderAPI
- */
- class SessionInfo
- {
- public:
- /**
- True if the TLS connection is compressed, otherwise false
- */
- bool isCompressed;
-
- /**
- The TLS protocol version being used for this connection
- */
- TLS::Version version;
-
- /**
- The cipher suite being used for this connection
-
- \sa TLSContext::supportedCipherSuites()
- */
- QString cipherSuite;
-
- /**
- The bit size of the cipher used for this connection
- */
- int cipherBits;
-
- /**
- The maximum bit size possible of the cipher used for this
- connection
- */
- int cipherMaxBits;
-
- /**
- Pointer to the id of this TLS session, for use with
- resuming
- */
- TLSSessionContext *id;
- };
+ /**
+ \class QCA::TLSContext::SessionInfo qcaprovider.h QtCrypto
+
+ Information about an active TLS connection
+
+ For efficiency and simplicity, the members are directly accessed.
+
+ \ingroup ProviderAPI
+ */
+ class SessionInfo
+ {
+ public:
+ /**
+ True if the TLS connection is compressed, otherwise false
+ */
+ bool isCompressed;
+
+ /**
+ The TLS protocol version being used for this connection
+ */
+ TLS::Version version;
+
+ /**
+ The cipher suite being used for this connection
+
+ \sa TLSContext::supportedCipherSuites()
+ */
+ QString cipherSuite;
+
+ /**
+ The bit size of the cipher used for this connection
+ */
+ int cipherBits;
+
+ /**
+ The maximum bit size possible of the cipher used for this
+ connection
+ */
+ int cipherMaxBits;
+
+ /**
+ Pointer to the id of this TLS session, for use with
+ resuming
+ */
+ TLSSessionContext *id;
+ };
- /**
- Result of a TLS operation
- */
- enum Result
- {
- Success, ///< Operation completed
- Error, ///< Operation failed
- Continue ///< More data needed to complete operation
- };
+ /**
+ Result of a TLS operation
+ */
+ enum Result {
+ Success, ///< Operation completed
+ Error, ///< Operation failed
+ Continue ///< More data needed to complete operation
+ };
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the Provider associated with this context
- \param type the name of the type of feature that supported by this context
- */
- TLSContext(Provider *p, const QString &type) : Provider::Context(p, type) {}
+ \param p the Provider associated with this context
+ \param type the name of the type of feature that supported by this context
+ */
+ TLSContext(Provider *p, const QString &type) : Provider::Context(p, type) {}
- /**
- Reset the object to its initial state
- */
- virtual void reset() = 0;
+ /**
+ Reset the object to its initial state
+ */
+ virtual void reset() = 0;
- /**
- Returns a list of supported cipher suites for the specified
- SSL/TLS version. The cipher suites are specified as strings, for
- example: "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" (without quotes).
+ /**
+ Returns a list of supported cipher suites for the specified
+ SSL/TLS version. The cipher suites are specified as strings, for
+ example: "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA" (without quotes).
- \param version the version of TLS to search for
- */
- virtual QStringList supportedCipherSuites(const TLS::Version &version) const = 0;
+ \param version the version of TLS to search for
+ */
+ virtual QStringList supportedCipherSuites(const TLS::Version &version) const = 0;
- /**
- Returns true if the provider supports compression
- */
- virtual bool canCompress() const = 0;
+ /**
+ Returns true if the provider supports compression
+ */
+ virtual bool canCompress() const = 0;
- /**
- Returns true if the provider supports server name indication
- */
- virtual bool canSetHostName() const = 0;
+ /**
+ Returns true if the provider supports server name indication
+ */
+ virtual bool canSetHostName() const = 0;
- /**
- Returns the maximum SSF supported by this provider
- */
- virtual int maxSSF() const = 0;
+ /**
+ Returns the maximum SSF supported by this provider
+ */
+ virtual int maxSSF() const = 0;
- /**
- Configure a new session
+ /**
+ Configure a new session
- This function will be called before any other configuration
- functions.
+ This function will be called before any other configuration
+ functions.
- \param serverMode whether to operate as a server (true) or client (false)
- \param hostName the hostname to use
- \param compress whether to compress (true) or not (false)
- */
- virtual void setup(bool serverMode, const QString &hostName, bool compress) = 0;
+ \param serverMode whether to operate as a server (true) or client (false)
+ \param hostName the hostname to use
+ \param compress whether to compress (true) or not (false)
+ */
+ virtual void setup(bool serverMode, const QString &hostName, bool compress) = 0;
- /**
- Set the constraints of the session using SSF values
+ /**
+ Set the constraints of the session using SSF values
- This function will be called before start().
+ This function will be called before start().
- \param minSSF the minimum strength factor that is acceptable
- \param maxSSF the maximum strength factor that is acceptable
- */
- virtual void setConstraints(int minSSF, int maxSSF) = 0;
+ \param minSSF the minimum strength factor that is acceptable
+ \param maxSSF the maximum strength factor that is acceptable
+ */
+ virtual void setConstraints(int minSSF, int maxSSF) = 0;
- /**
- \overload
+ /**
+ \overload
- Set the constraints of the session using a cipher suite list
+ Set the constraints of the session using a cipher suite list
- This function will be called before start().
+ This function will be called before start().
- \param cipherSuiteList the list of cipher suites that may be used for
- this session.
+ \param cipherSuiteList the list of cipher suites that may be used for
+ this session.
- \sa supportedCipherSuites
- */
- virtual void setConstraints(const QStringList &cipherSuiteList) = 0;
+ \sa supportedCipherSuites
+ */
+ virtual void setConstraints(const QStringList &cipherSuiteList) = 0;
- /**
- Set the list of trusted certificates
+ /**
+ Set the list of trusted certificates
- This function may be called at any time.
+ This function may be called at any time.
- \param trusted the trusted certificates and CRLs to be used.
- */
- virtual void setTrustedCertificates(const CertificateCollection &trusted) = 0;
+ \param trusted the trusted certificates and CRLs to be used.
+ */
+ virtual void setTrustedCertificates(const CertificateCollection &trusted) = 0;
- /**
- Set the list of acceptable issuers
+ /**
+ Set the list of acceptable issuers
- This function may be called at any time.
+ This function may be called at any time.
- This function is for server mode only.
+ This function is for server mode only.
- \param issuerList the list of issuers that may be used
- */
- virtual void setIssuerList(const QList<CertificateInfoOrdered> &issuerList) = 0;
+ \param issuerList the list of issuers that may be used
+ */
+ virtual void setIssuerList(const QList<CertificateInfoOrdered> &issuerList) = 0;
- /**
- Set the local certificate
+ /**
+ Set the local certificate
- This function may be called at any time.
+ This function may be called at any time.
- \param cert the certificate and associated trust chain
- \param key the private key for the local certificate
- */
- virtual void setCertificate(const CertificateChain &cert, const PrivateKey &key) = 0;
+ \param cert the certificate and associated trust chain
+ \param key the private key for the local certificate
+ */
+ virtual void setCertificate(const CertificateChain &cert, const PrivateKey &key) = 0;
- /**
- Set the TLS session id, for session resuming
+ /**
+ Set the TLS session id, for session resuming
- This function will be called before start().
+ This function will be called before start().
- \param id the session identification
- */
- virtual void setSessionId(const TLSSessionContext &id) = 0;
+ \param id the session identification
+ */
+ virtual void setSessionId(const TLSSessionContext &id) = 0;
- /**
- Sets the session to the shutdown state.
+ /**
+ Sets the session to the shutdown state.
- The actual shutdown operation will happen at a future call to
- update().
+ The actual shutdown operation will happen at a future call to
+ update().
- This function is for normal TLS only (not DTLS).
- */
- virtual void shutdown() = 0;
+ This function is for normal TLS only (not DTLS).
+ */
+ virtual void shutdown() = 0;
- /**
- Set the maximum transmission unit size
+ /**
+ Set the maximum transmission unit size
- This function is for DTLS only.
+ This function is for DTLS only.
- \param size the maximum number of bytes in a datagram
- */
- virtual void setMTU(int size);
+ \param size the maximum number of bytes in a datagram
+ */
+ virtual void setMTU(int size);
- /**
- Begins the session, starting with the handshake
+ /**
+ Begins the session, starting with the handshake
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
- On completion, the result() function will return Success if the
- TLS session is able to begin, or Error if there is a failure to
- initialize the TLS subsystem. If successful, the session is now
- in the handshake state, and update() will be called repeatedly
- until the session ends.
- */
- virtual void start() = 0;
+ On completion, the result() function will return Success if the
+ TLS session is able to begin, or Error if there is a failure to
+ initialize the TLS subsystem. If successful, the session is now
+ in the handshake state, and update() will be called repeatedly
+ until the session ends.
+ */
+ virtual void start() = 0;
- /**
- Performs one iteration of the TLS session processing
+ /**
+ Performs one iteration of the TLS session processing
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
- If the session is in a handshake state, result() and to_net() will
- be valid. If result() is Success, then the session is now in the
- connected state.
+ If the session is in a handshake state, result() and to_net() will
+ be valid. If result() is Success, then the session is now in the
+ connected state.
- If the session is in a shutdown state, result() and to_net() will
- be valid. If result() is Success, then the session has ended.
+ If the session is in a shutdown state, result() and to_net() will
+ be valid. If result() is Success, then the session has ended.
- If the session is in a connected state, result(), to_net(),
- encoded(), to_app(), and eof() are valid. The result() function
- will return Success or Error. Note that eof() does not apply
- to DTLS.
+ If the session is in a connected state, result(), to_net(),
+ encoded(), to_app(), and eof() are valid. The result() function
+ will return Success or Error. Note that eof() does not apply
+ to DTLS.
- For DTLS, this function operates with single packets. Many
- update() operations must be performed repeatedly to exchange
- multiple packets.
+ For DTLS, this function operates with single packets. Many
+ update() operations must be performed repeatedly to exchange
+ multiple packets.
- \param from_net the data from the "other side" of the connection
- \param from_app the data from the application of the protocol
- */
- virtual void update(const QByteArray &from_net, const QByteArray &from_app) = 0;
+ \param from_net the data from the "other side" of the connection
+ \param from_app the data from the application of the protocol
+ */
+ virtual void update(const QByteArray &from_net, const QByteArray &from_app) = 0;
- /**
- Waits for a start() or update() operation to complete. In this
- case, the resultsReady() signal is not emitted. Returns true if
- the operation completed or false if this function times out.
+ /**
+ Waits for a start() or update() operation to complete. In this
+ case, the resultsReady() signal is not emitted. Returns true if
+ the operation completed or false if this function times out.
- This function is blocking.
+ This function is blocking.
- \param msecs number of milliseconds to wait (-1 to wait forever)
- */
- virtual bool waitForResultsReady(int msecs) = 0;
+ \param msecs number of milliseconds to wait (-1 to wait forever)
+ */
+ virtual bool waitForResultsReady(int msecs) = 0;
- /**
- Returns the result code of an operation
- */
- virtual Result result() const = 0;
+ /**
+ Returns the result code of an operation
+ */
+ virtual Result result() const = 0;
- /**
- Returns data that should be sent across the network
- */
- virtual QByteArray to_net() = 0;
+ /**
+ Returns data that should be sent across the network
+ */
+ virtual QByteArray to_net() = 0;
- /**
- Returns the number of bytes of plaintext data that is encoded
- inside of to_net()
- */
- virtual int encoded() const = 0;
+ /**
+ Returns the number of bytes of plaintext data that is encoded
+ inside of to_net()
+ */
+ virtual int encoded() const = 0;
- /**
- Returns data that is decoded from the network and should be
- processed by the application
- */
- virtual QByteArray to_app() = 0;
+ /**
+ Returns data that is decoded from the network and should be
+ processed by the application
+ */
+ virtual QByteArray to_app() = 0;
- /**
- Returns true if the peer has closed the stream
- */
- virtual bool eof() const = 0;
+ /**
+ Returns true if the peer has closed the stream
+ */
+ virtual bool eof() const = 0;
- /**
- Returns true if the TLS client hello has been received
+ /**
+ Returns true if the TLS client hello has been received
- This is only valid if a handshake is in progress or
- completed.
- */
- virtual bool clientHelloReceived() const = 0;
+ This is only valid if a handshake is in progress or
+ completed.
+ */
+ virtual bool clientHelloReceived() const = 0;
- /**
- Returns true if the TLS server hello has been received
+ /**
+ Returns true if the TLS server hello has been received
- This is only valid if a handshake is in progress or completed.
- */
- virtual bool serverHelloReceived() const = 0;
+ This is only valid if a handshake is in progress or completed.
+ */
+ virtual bool serverHelloReceived() const = 0;
- /**
- Returns the host name sent by the client using server name
- indication (server mode only)
+ /**
+ Returns the host name sent by the client using server name
+ indication (server mode only)
- This is only valid if a handshake is in progress or completed.
- */
- virtual QString hostName() const = 0;
+ This is only valid if a handshake is in progress or completed.
+ */
+ virtual QString hostName() const = 0;
- /**
- Returns true if the peer is requesting a certificate
+ /**
+ Returns true if the peer is requesting a certificate
- This is only valid if a handshake is in progress or completed.
- */
- virtual bool certificateRequested() const = 0;
+ This is only valid if a handshake is in progress or completed.
+ */
+ virtual bool certificateRequested() const = 0;
- /**
- Returns the issuer list sent by the server (client mode only)
+ /**
+ Returns the issuer list sent by the server (client mode only)
- This is only valid if a handshake is in progress or completed.
- */
- virtual QList<CertificateInfoOrdered> issuerList() const = 0;
+ This is only valid if a handshake is in progress or completed.
+ */
+ virtual QList<CertificateInfoOrdered> issuerList() const = 0;
- /**
- Returns the QCA::Validity of the peer certificate
+ /**
+ Returns the QCA::Validity of the peer certificate
- This is only valid if a handshake is completed.
- */
- virtual Validity peerCertificateValidity() const = 0;
+ This is only valid if a handshake is completed.
+ */
+ virtual Validity peerCertificateValidity() const = 0;
- /**
- Returns the peer certificate chain
+ /**
+ Returns the peer certificate chain
- This is only valid if a handshake is completed.
- */
- virtual CertificateChain peerCertificateChain() const = 0;
+ This is only valid if a handshake is completed.
+ */
+ virtual CertificateChain peerCertificateChain() const = 0;
- /**
- Returns information about the active TLS session
+ /**
+ Returns information about the active TLS session
- This is only valid if a handshake is completed.
- */
- virtual SessionInfo sessionInfo() const = 0;
+ This is only valid if a handshake is completed.
+ */
+ virtual SessionInfo sessionInfo() const = 0;
- /**
- Returns any unprocessed network input data
+ /**
+ Returns any unprocessed network input data
- This is only valid after a successful shutdown.
- */
- virtual QByteArray unprocessed() = 0;
+ This is only valid after a successful shutdown.
+ */
+ virtual QByteArray unprocessed() = 0;
Q_SIGNALS:
- /**
- Emit this when a start() or update() operation has completed.
- */
- void resultsReady();
-
- /**
- Emit this to force the application to call update(), even with
- empty arguments.
- */
- void dtlsTimeout();
+ /**
+ Emit this when a start() or update() operation has completed.
+ */
+ void resultsReady();
+
+ /**
+ Emit this to force the application to call update(), even with
+ empty arguments.
+ */
+ void dtlsTimeout();
};
/**
\class SASLContext qcaprovider.h QtCrypto
SASL provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want SASL instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT SASLContext : public Provider::Context
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- \class QCA::SASLContext::HostPort qcaprovider.h QtCrypto
-
- Convenience class to hold an IP address and an associated port
-
- For efficiency and simplicity, the members are directly accessed.
-
- \ingroup ProviderAPI
- */
- class HostPort
- {
- public:
- /**
- The IP address
- */
- QString addr;
-
- /**
- The port
- */
- quint16 port;
- };
-
- /**
- Result of a SASL operation
- */
- enum Result
- {
- Success, ///< Operation completed
- Error, ///< Operation failed
- Params, ///< Parameters are needed to complete authentication
- AuthCheck, ///< Client login can be inspected (server only)
- Continue ///< More steps needed to complete authentication
- };
-
- /**
- Standard constructor
-
- \param p the Provider associated with this context
- */
- SASLContext(Provider *p) : Provider::Context(p, QStringLiteral("sasl")) {}
-
- /**
- Reset the object to its initial state
- */
- virtual void reset() = 0;
-
- /**
- Configure a new session
-
- This function will be called before any other configuration
- functions.
-
- \param service the name of the network service being provided by
- this application, which can be used by the SASL system for policy
- control. Examples: "imap", "xmpp"
- \param host the hostname that the application is interacting with
- or as
- \param local pointer to a HostPort representing the local end of a
- network socket, or 0 if this information is unknown or not
- available
- \param remote pointer to a HostPort representing the peer end of a
- network socket, or 0 if this information is unknown or not
- available
- \param ext_id the id to be used for SASL EXTERNAL (client only)
- \param ext_ssf the SSF of the external authentication channel
- (client only)
- */
- virtual void setup(const QString &service, const QString &host, const HostPort *local, const HostPort *remote, const QString &ext_id, int ext_ssf) = 0;
-
- /**
- Set the constraints of the session using SSF values
-
- This function will be called before startClient() or
- startServer().
-
- \param f the flags to use
- \param minSSF the minimum strength factor that is acceptable
- \param maxSSF the maximum strength factor that is acceptable
- */
- virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF) = 0;
-
- /**
- Begins the session in client mode, starting with the
- authentication
-
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
-
- On completion, result(), mech(), haveClientInit(), and stepData()
- will be valid. If result() is Success, then the session is now in
- the connected state.
-
- \param mechlist the list of mechanisms
- \param allowClientSendFirst whether the client sends first (true) or the server
- sends first (false)
- */
- virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst) = 0;
-
- /**
- Begins the session in server mode, starting with the
- authentication
-
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
-
- On completion, result() and mechlist() will be valid. The
- result() function will return Success or Error. If the result is
- Success, then serverFirstStep() will be called next.
-
- \param realm the realm to authenticate in
- \param disableServerSendLast whether the client sends first (true)
- or the server sends first (false)
- */
- virtual void startServer(const QString &realm, bool disableServerSendLast) = 0;
-
- /**
- Finishes server startup
-
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
-
- On completion, result() and stepData() will be valid. If result()
- is Success, then the session is now in the connected state.
-
- \param mech the mechanism to use
- \param clientInit initial data from the client, or 0 if there is
- no such data
- */
- virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit) = 0;
-
- /**
- Perform another step of the SASL authentication
-
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
-
- On completion, result() and stepData() will be valid.
-
- \param from_net the data from the "other side" of the protocol
- to be used for the next step.
- */
- virtual void nextStep(const QByteArray &from_net) = 0;
-
- /**
- Attempt the most recent operation again. This is used if the
- result() of an operation is Params or AuthCheck.
-
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
-
- On completion, result() and stepData() will be valid.
- */
- virtual void tryAgain() = 0;
-
- /**
- Performs one iteration of the SASL security layer processing
-
- This function returns immediately, and completion is signaled with
- the resultsReady() signal.
-
- On completion, result(), to_net(), encoded(), and to_app() will be
- valid. The result() function will return Success or Error.
-
- \param from_net the data from the "other side" of the protocol
- \param from_app the data from the application of the protocol
- */
- virtual void update(const QByteArray &from_net, const QByteArray &from_app) = 0;
-
- /**
- Waits for a startClient(), startServer(), serverFirstStep(),
- nextStep(), tryAgain(), or update() operation to complete. In
- this case, the resultsReady() signal is not emitted. Returns true
- if the operation completed or false if this function times out.
-
- This function is blocking.
-
- \param msecs number of milliseconds to wait (-1 to wait forever)
- */
- virtual bool waitForResultsReady(int msecs) = 0;
+ /**
+ \class QCA::SASLContext::HostPort qcaprovider.h QtCrypto
+
+ Convenience class to hold an IP address and an associated port
+
+ For efficiency and simplicity, the members are directly accessed.
+
+ \ingroup ProviderAPI
+ */
+ class HostPort
+ {
+ public:
+ /**
+ The IP address
+ */
+ QString addr;
+
+ /**
+ The port
+ */
+ quint16 port;
+ };
+
+ /**
+ Result of a SASL operation
+ */
+ enum Result {
+ Success, ///< Operation completed
+ Error, ///< Operation failed
+ Params, ///< Parameters are needed to complete authentication
+ AuthCheck, ///< Client login can be inspected (server only)
+ Continue ///< More steps needed to complete authentication
+ };
+
+ /**
+ Standard constructor
+
+ \param p the Provider associated with this context
+ */
+ SASLContext(Provider *p) : Provider::Context(p, QStringLiteral("sasl")) {}
+
+ /**
+ Reset the object to its initial state
+ */
+ virtual void reset() = 0;
+
+ /**
+ Configure a new session
+
+ This function will be called before any other configuration
+ functions.
+
+ \param service the name of the network service being provided by
+ this application, which can be used by the SASL system for policy
+ control. Examples: "imap", "xmpp"
+ \param host the hostname that the application is interacting with
+ or as
+ \param local pointer to a HostPort representing the local end of a
+ network socket, or 0 if this information is unknown or not
+ available
+ \param remote pointer to a HostPort representing the peer end of a
+ network socket, or 0 if this information is unknown or not
+ available
+ \param ext_id the id to be used for SASL EXTERNAL (client only)
+ \param ext_ssf the SSF of the external authentication channel
+ (client only)
+ */
+ virtual void setup(const QString &service, const QString &host, const HostPort *local, const HostPort *remote, const QString &ext_id, int ext_ssf) = 0;
+
+ /**
+ Set the constraints of the session using SSF values
+
+ This function will be called before startClient() or
+ startServer().
+
+ \param f the flags to use
+ \param minSSF the minimum strength factor that is acceptable
+ \param maxSSF the maximum strength factor that is acceptable
+ */
+ virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF) = 0;
+
+ /**
+ Begins the session in client mode, starting with the
+ authentication
+
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
+
+ On completion, result(), mech(), haveClientInit(), and stepData()
+ will be valid. If result() is Success, then the session is now in
+ the connected state.
+
+ \param mechlist the list of mechanisms
+ \param allowClientSendFirst whether the client sends first (true) or the server
+ sends first (false)
+ */
+ virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst) = 0;
+
+ /**
+ Begins the session in server mode, starting with the
+ authentication
+
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
+
+ On completion, result() and mechlist() will be valid. The
+ result() function will return Success or Error. If the result is
+ Success, then serverFirstStep() will be called next.
+
+ \param realm the realm to authenticate in
+ \param disableServerSendLast whether the client sends first (true)
+ or the server sends first (false)
+ */
+ virtual void startServer(const QString &realm, bool disableServerSendLast) = 0;
+
+ /**
+ Finishes server startup
+
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
+
+ On completion, result() and stepData() will be valid. If result()
+ is Success, then the session is now in the connected state.
+
+ \param mech the mechanism to use
+ \param clientInit initial data from the client, or 0 if there is
+ no such data
+ */
+ virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit) = 0;
+
+ /**
+ Perform another step of the SASL authentication
+
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
+
+ On completion, result() and stepData() will be valid.
+
+ \param from_net the data from the "other side" of the protocol
+ to be used for the next step.
+ */
+ virtual void nextStep(const QByteArray &from_net) = 0;
+
+ /**
+ Attempt the most recent operation again. This is used if the
+ result() of an operation is Params or AuthCheck.
+
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
+
+ On completion, result() and stepData() will be valid.
+ */
+ virtual void tryAgain() = 0;
+
+ /**
+ Performs one iteration of the SASL security layer processing
+
+ This function returns immediately, and completion is signaled with
+ the resultsReady() signal.
+
+ On completion, result(), to_net(), encoded(), and to_app() will be
+ valid. The result() function will return Success or Error.
+
+ \param from_net the data from the "other side" of the protocol
+ \param from_app the data from the application of the protocol
+ */
+ virtual void update(const QByteArray &from_net, const QByteArray &from_app) = 0;
+
+ /**
+ Waits for a startClient(), startServer(), serverFirstStep(),
+ nextStep(), tryAgain(), or update() operation to complete. In
+ this case, the resultsReady() signal is not emitted. Returns true
+ if the operation completed or false if this function times out.
+
+ This function is blocking.
+
+ \param msecs number of milliseconds to wait (-1 to wait forever)
+ */
+ virtual bool waitForResultsReady(int msecs) = 0;
- /**
- Returns the result code of an operation
- */
- virtual Result result() const = 0;
+ /**
+ Returns the result code of an operation
+ */
+ virtual Result result() const = 0;
- /**
- Returns the mechanism list (server mode only)
- */
- virtual QStringList mechlist() const = 0;
-
- /**
- Returns the mechanism selected
- */
- virtual QString mech() const = 0;
-
- /**
- Returns true if the client has initialization data
- */
- virtual bool haveClientInit() const = 0;
+ /**
+ Returns the mechanism list (server mode only)
+ */
+ virtual QStringList mechlist() const = 0;
+
+ /**
+ Returns the mechanism selected
+ */
+ virtual QString mech() const = 0;
+
+ /**
+ Returns true if the client has initialization data
+ */
+ virtual bool haveClientInit() const = 0;
- /**
- Returns an authentication payload for to be transmitted over the
- network
- */
- virtual QByteArray stepData() const = 0;
-
- /**
- Returns data that should be sent across the network (for the
- security layer)
- */
- virtual QByteArray to_net() = 0;
+ /**
+ Returns an authentication payload for to be transmitted over the
+ network
+ */
+ virtual QByteArray stepData() const = 0;
+
+ /**
+ Returns data that should be sent across the network (for the
+ security layer)
+ */
+ virtual QByteArray to_net() = 0;
- /**
- Returns the number of bytes of plaintext data that is encoded
- inside of to_net()
- */
- virtual int encoded() const = 0;
+ /**
+ Returns the number of bytes of plaintext data that is encoded
+ inside of to_net()
+ */
+ virtual int encoded() const = 0;
- /**
- Returns data that is decoded from the network and should be
- processed by the application
- */
- virtual QByteArray to_app() = 0;
+ /**
+ Returns data that is decoded from the network and should be
+ processed by the application
+ */
+ virtual QByteArray to_app() = 0;
- /**
- Returns the SSF of the active SASL session
-
- This is only valid after authentication success.
- */
- virtual int ssf() const = 0;
-
- /**
- Returns the reason for failure, if the authentication was not
- successful.
-
- This is only valid after authentication failure.
- */
- virtual SASL::AuthCondition authCondition() const = 0;
-
- /**
- Returns the needed/optional client parameters
-
- This is only valid after receiving the Params result code.
- */
- virtual SASL::Params clientParams() const = 0;
-
- /**
- Set some of the client parameters (pass 0 to not set a field)
-
- \param user the user name
- \param authzid the authorization name / role
- \param pass the password
- \param realm the realm to authenticate in
- */
- virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm) = 0;
-
- /**
- Returns the realm list (client mode only)
-
- This is only valid after receiving the Params result code and
- SASL::Params::canSendRealm is set to true.
- */
- virtual QStringList realmlist() const = 0;
-
- /**
- Returns the username attempting to authenticate (server mode only)
-
- This is only valid after receiving the AuthCheck result code.
- */
- virtual QString username() const = 0;
-
- /**
- Returns the authzid attempting to authorize (server mode only)
-
- This is only valid after receiving the AuthCheck result code.
- */
- virtual QString authzid() const = 0;
+ /**
+ Returns the SSF of the active SASL session
+
+ This is only valid after authentication success.
+ */
+ virtual int ssf() const = 0;
+
+ /**
+ Returns the reason for failure, if the authentication was not
+ successful.
+
+ This is only valid after authentication failure.
+ */
+ virtual SASL::AuthCondition authCondition() const = 0;
+
+ /**
+ Returns the needed/optional client parameters
+
+ This is only valid after receiving the Params result code.
+ */
+ virtual SASL::Params clientParams() const = 0;
+
+ /**
+ Set some of the client parameters (pass 0 to not set a field)
+
+ \param user the user name
+ \param authzid the authorization name / role
+ \param pass the password
+ \param realm the realm to authenticate in
+ */
+ virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm) = 0;
+
+ /**
+ Returns the realm list (client mode only)
+
+ This is only valid after receiving the Params result code and
+ SASL::Params::canSendRealm is set to true.
+ */
+ virtual QStringList realmlist() const = 0;
+
+ /**
+ Returns the username attempting to authenticate (server mode only)
+
+ This is only valid after receiving the AuthCheck result code.
+ */
+ virtual QString username() const = 0;
+
+ /**
+ Returns the authzid attempting to authorize (server mode only)
+
+ This is only valid after receiving the AuthCheck result code.
+ */
+ virtual QString authzid() const = 0;
Q_SIGNALS:
- /**
- Emit this when a startClient(), startServer(), serverFirstStep(),
- nextStep(), tryAgain(), or update() operation has completed.
- */
- void resultsReady();
+ /**
+ Emit this when a startClient(), startServer(), serverFirstStep(),
+ nextStep(), tryAgain(), or update() operation has completed.
+ */
+ void resultsReady();
};
/**
\class MessageContext qcaprovider.h QtCrypto
SecureMessage provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want SecureMessage
instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT MessageContext : public Provider::Context
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The type of operation being performed
- */
- enum Operation
- {
- Encrypt, ///< Encrypt operation
- Decrypt, ///< Decrypt (or Decrypt and Verify) operation
- Sign, ///< Sign operation
- Verify, ///< Verify operation
- SignAndEncrypt ///< Sign and Encrypt operation
- };
-
- /**
- Standard constructor
-
- \param p the Provider associated with this context
- \param type the name of the type of secure message to be created
- */
- MessageContext(Provider *p, const QString &type) : Provider::Context(p, type) {}
-
- /**
- Returns true if the provider supports multiple signers for
- signature creation or signature verification
- */
- virtual bool canSignMultiple() const = 0;
-
- /**
- The type of secure message (e.g. PGP or CMS)
- */
- virtual SecureMessage::Type type() const = 0;
-
- /**
- Reset the object to its initial state
- */
- virtual void reset() = 0;
-
- /**
- Configure a new encrypting operation
-
- \param keys the keys to be used for encryption.
- */
- virtual void setupEncrypt(const SecureMessageKeyList &keys) = 0;
-
- /**
- Configure a new signing operation
-
- \param keys the keys to use for signing
- \param m the mode to sign in
- \param bundleSigner whether to bundle the signing keys (true) or not (false)
- \param smime whether to use smime format (true) or not (false)
- */
- virtual void setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool bundleSigner, bool smime) = 0;
-
- /**
- Configure a new verify operation
-
- \param detachedSig the detached signature to use (if applicable) for verification
- */
- virtual void setupVerify(const QByteArray &detachedSig) = 0;
-
- /**
- Begins the secure message operation
-
- This function returns immediately.
-
- If there is input data, update() will be called (potentially
- repeatedly) afterwards. Emit updated() if there is data to
- read, if input data has been accepted, or if the operation has
- finished.
-
- \param f the format of the message to be produced
- \param op the operation to be performed
- */
- virtual void start(SecureMessage::Format f, Operation op) = 0;
-
- /**
- Provide input to the message operation
-
- \param in the data to use for the message operation
- */
- virtual void update(const QByteArray &in) = 0;
-
- /**
- Extract output from the message operation
- */
- virtual QByteArray read() = 0;
-
- /**
- Returns the number of input bytes accepted since the last call to
- update()
- */
- virtual int written() = 0;
-
- /**
- Indicates the end of input
- */
- virtual void end() = 0;
-
- /**
- Returns true if the operation has finished, otherwise false
- */
- virtual bool finished() const = 0;
-
- /**
- Waits for the secure message operation to complete. In this case,
- the updated() signal is not emitted. Returns true if the
- operation completed or false if this function times out.
-
- This function is blocking.
-
- \param msecs number of milliseconds to wait (-1 to wait forever)
- */
- virtual bool waitForFinished(int msecs) = 0;
-
- /**
- Returns true if the operation was successful
-
- This is only valid if the operation has finished.
- */
- virtual bool success() const = 0;
-
- /**
- Returns the reason for failure, if the operation was not
- successful
+ /**
+ The type of operation being performed
+ */
+ enum Operation {
+ Encrypt, ///< Encrypt operation
+ Decrypt, ///< Decrypt (or Decrypt and Verify) operation
+ Sign, ///< Sign operation
+ Verify, ///< Verify operation
+ SignAndEncrypt ///< Sign and Encrypt operation
+ };
+
+ /**
+ Standard constructor
+
+ \param p the Provider associated with this context
+ \param type the name of the type of secure message to be created
+ */
+ MessageContext(Provider *p, const QString &type) : Provider::Context(p, type) {}
+
+ /**
+ Returns true if the provider supports multiple signers for
+ signature creation or signature verification
+ */
+ virtual bool canSignMultiple() const = 0;
+
+ /**
+ The type of secure message (e.g. PGP or CMS)
+ */
+ virtual SecureMessage::Type type() const = 0;
+
+ /**
+ Reset the object to its initial state
+ */
+ virtual void reset() = 0;
+
+ /**
+ Configure a new encrypting operation
+
+ \param keys the keys to be used for encryption.
+ */
+ virtual void setupEncrypt(const SecureMessageKeyList &keys) = 0;
+
+ /**
+ Configure a new signing operation
+
+ \param keys the keys to use for signing
+ \param m the mode to sign in
+ \param bundleSigner whether to bundle the signing keys (true) or not (false)
+ \param smime whether to use smime format (true) or not (false)
+ */
+ virtual void setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool bundleSigner, bool smime) = 0;
+
+ /**
+ Configure a new verify operation
+
+ \param detachedSig the detached signature to use (if applicable) for verification
+ */
+ virtual void setupVerify(const QByteArray &detachedSig) = 0;
+
+ /**
+ Begins the secure message operation
+
+ This function returns immediately.
+
+ If there is input data, update() will be called (potentially
+ repeatedly) afterwards. Emit updated() if there is data to
+ read, if input data has been accepted, or if the operation has
+ finished.
+
+ \param f the format of the message to be produced
+ \param op the operation to be performed
+ */
+ virtual void start(SecureMessage::Format f, Operation op) = 0;
+
+ /**
+ Provide input to the message operation
+
+ \param in the data to use for the message operation
+ */
+ virtual void update(const QByteArray &in) = 0;
+
+ /**
+ Extract output from the message operation
+ */
+ virtual QByteArray read() = 0;
+
+ /**
+ Returns the number of input bytes accepted since the last call to
+ update()
+ */
+ virtual int written() = 0;
+
+ /**
+ Indicates the end of input
+ */
+ virtual void end() = 0;
+
+ /**
+ Returns true if the operation has finished, otherwise false
+ */
+ virtual bool finished() const = 0;
+
+ /**
+ Waits for the secure message operation to complete. In this case,
+ the updated() signal is not emitted. Returns true if the
+ operation completed or false if this function times out.
+
+ This function is blocking.
+
+ \param msecs number of milliseconds to wait (-1 to wait forever)
+ */
+ virtual bool waitForFinished(int msecs) = 0;
+
+ /**
+ Returns true if the operation was successful
+
+ This is only valid if the operation has finished.
+ */
+ virtual bool success() const = 0;
+
+ /**
+ Returns the reason for failure, if the operation was not
+ successful
- This is only valid if the operation has finished.
- */
- virtual SecureMessage::Error errorCode() const = 0;
+ This is only valid if the operation has finished.
+ */
+ virtual SecureMessage::Error errorCode() const = 0;
- /**
- Returns the signature, in the case of a detached signature
- operation
+ /**
+ Returns the signature, in the case of a detached signature
+ operation
- This is only valid if the operation has finished.
- */
- virtual QByteArray signature() const = 0;
+ This is only valid if the operation has finished.
+ */
+ virtual QByteArray signature() const = 0;
- /**
- Returns the name of the hash used to generate the signature, in
- the case of a signature operation
+ /**
+ Returns the name of the hash used to generate the signature, in
+ the case of a signature operation
- This is only valid if the operation has finished.
- */
- virtual QString hashName() const = 0;
+ This is only valid if the operation has finished.
+ */
+ virtual QString hashName() const = 0;
- /**
- Returns a list of signatures, in the case of a verify or decrypt
- and verify operation
+ /**
+ Returns a list of signatures, in the case of a verify or decrypt
+ and verify operation
- This is only valid if the operation has finished.
- */
- virtual SecureMessageSignatureList signers() const = 0;
+ This is only valid if the operation has finished.
+ */
+ virtual SecureMessageSignatureList signers() const = 0;
- /**
- Returns any diagnostic text for the operation, potentially useful
- to show the user in the event the operation is unsuccessful. For
- example, this could be the stderr output of gpg.
+ /**
+ Returns any diagnostic text for the operation, potentially useful
+ to show the user in the event the operation is unsuccessful. For
+ example, this could be the stderr output of gpg.
- This is only valid if the operation has finished.
- */
- virtual QString diagnosticText() const;
+ This is only valid if the operation has finished.
+ */
+ virtual QString diagnosticText() const;
Q_SIGNALS:
- /**
- Emitted when there is data to read, if input data has been
- accepted, or if the operation has finished
- */
- void updated();
+ /**
+ Emitted when there is data to read, if input data has been
+ accepted, or if the operation has finished
+ */
+ void updated();
};
/**
\class SMSContext qcaprovider.h QtCrypto
SecureMessageSystem provider
\note This class is part of the provider plugin interface and should not
be used directly by applications. You probably want SecureMessageSystem
instead.
\ingroup ProviderAPI
*/
class QCA_EXPORT SMSContext : public BasicContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param p the provider associated with this context
- \param type the name of the type of secure message system
- */
- SMSContext(Provider *p, const QString &type) : BasicContext(p, type) {}
+ \param p the provider associated with this context
+ \param type the name of the type of secure message system
+ */
+ SMSContext(Provider *p, const QString &type) : BasicContext(p, type) {}
- /**
- Set the trusted certificates and for this secure message system,
- to be used for validation
+ /**
+ Set the trusted certificates and for this secure message system,
+ to be used for validation
- The collection may also contain CRLs.
+ The collection may also contain CRLs.
- This function is only valid for CMS.
+ This function is only valid for CMS.
- \param trusted a set of trusted certificates and CRLs.
- */
- virtual void setTrustedCertificates(const CertificateCollection &trusted);
+ \param trusted a set of trusted certificates and CRLs.
+ */
+ virtual void setTrustedCertificates(const CertificateCollection &trusted);
- /**
- Set the untrusted certificates and CRLs for this secure message
- system, to be used for validation
+ /**
+ Set the untrusted certificates and CRLs for this secure message
+ system, to be used for validation
- This function is only valid for CMS.
+ This function is only valid for CMS.
- \param untrusted a set of untrusted certificates and CRLs.
- */
- virtual void setUntrustedCertificates(const CertificateCollection &untrusted);
+ \param untrusted a set of untrusted certificates and CRLs.
+ */
+ virtual void setUntrustedCertificates(const CertificateCollection &untrusted);
- /**
- Set the private keys for this secure message system, to be used
- for decryption
+ /**
+ Set the private keys for this secure message system, to be used
+ for decryption
- This function is only valid for CMS.
+ This function is only valid for CMS.
- \param keys the keys to be used for decryption
- */
- virtual void setPrivateKeys(const QList<SecureMessageKey> &keys);
+ \param keys the keys to be used for decryption
+ */
+ virtual void setPrivateKeys(const QList<SecureMessageKey> &keys);
- /**
- Create a new message object for this system. The caller is
- responsible for deleting it.
- */
- virtual MessageContext *createMessage() = 0;
+ /**
+ Create a new message object for this system. The caller is
+ responsible for deleting it.
+ */
+ virtual MessageContext *createMessage() = 0;
};
}
#endif
#endif
diff --git a/include/QtCrypto/qpipe.h b/include/QtCrypto/qpipe.h
index 1d896443..d11d1df6 100644
--- a/include/QtCrypto/qpipe.h
+++ b/include/QtCrypto/qpipe.h
@@ -1,534 +1,538 @@
/*
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
/**
\file qpipe.h
Header file for the QPipe FIFO class
\note You should not use this header directly from an
application. You should just use <tt> \#include \<QtCrypto>
</tt> instead.
*/
#ifndef QPIPE_H
#define QPIPE_H
#ifndef DOXYGEN_SHOULD_SKIP_THIS
#ifndef QPIPE_NO_SECURE
# define QPIPE_SECURE
#endif
#ifdef QPIPE_SECURE
# include "QtCrypto"
#else
# define QCA_EXPORT
#endif
// defs adapted qprocess_p.h
#ifdef Q_OS_WIN
#include <windows.h>
typedef HANDLE Q_PIPE_ID;
#define INVALID_Q_PIPE_ID INVALID_HANDLE_VALUE
#else
typedef int Q_PIPE_ID;
#define INVALID_Q_PIPE_ID -1
#endif
#endif
// Note: for Windows console, I/O must be in UTF-8. Reads are guaranteed to
// to completely decode (no partial characters). Likewise, writes must
// not contain partial characters.
-namespace QCA {
-
+namespace QCA
+{
/**
\class QPipeDevice qpipe.h QtCrypto
Unbuffered direct pipe.
This class is not usually required except for very low level operations.
You should use QPipe and QPipeEnd for most applications.
\ingroup UserAPI
*/
class QCA_EXPORT QPipeDevice : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The type of device
- */
- enum Type
- {
- Read, ///< The pipe end can be read from
- Write ///< The pipe end can be written to
- };
+ /**
+ The type of device
+ */
+ enum Type {
+ Read, ///< The pipe end can be read from
+ Write ///< The pipe end can be written to
+ };
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param parent the parent object to this object
- */
- QPipeDevice(QObject *parent = 0);
- ~QPipeDevice();
+ \param parent the parent object to this object
+ */
+ QPipeDevice(QObject *parent = 0);
+ ~QPipeDevice();
- /**
- The Type of the pipe device (that is, read or write)
- */
- Type type() const;
+ /**
+ The Type of the pipe device (that is, read or write)
+ */
+ Type type() const;
- /**
- Test whether this object corresponds to a valid pipe
- */
- bool isValid() const;
+ /**
+ Test whether this object corresponds to a valid pipe
+ */
+ bool isValid() const;
- /**
- The low level identification for this pipe.
+ /**
+ The low level identification for this pipe.
- On Windows, this is a HANDLE. On Unix, this is a file descriptor (i.e. integer).
+ On Windows, this is a HANDLE. On Unix, this is a file descriptor (i.e. integer).
- Code using this method should be carefully tested for portability.
+ Code using this method should be carefully tested for portability.
- \sa idAsInt
- */
- Q_PIPE_ID id() const;
+ \sa idAsInt
+ */
+ Q_PIPE_ID id() const;
- /**
- The low level identification for this pipe, returned as an integer.
+ /**
+ The low level identification for this pipe, returned as an integer.
- Code using this method should be carefully tested for portability.
+ Code using this method should be carefully tested for portability.
- \sa id().
- */
- int idAsInt() const;
+ \sa id().
+ */
+ int idAsInt() const;
- /**
- Take over an existing pipe id, closing the old pipe if any.
+ /**
+ Take over an existing pipe id, closing the old pipe if any.
- \param id the identification of the pipe end to take over.
- \param t the type of pipe end (read or write).
- */
- void take(Q_PIPE_ID id, Type t);
+ \param id the identification of the pipe end to take over.
+ \param t the type of pipe end (read or write).
+ */
+ void take(Q_PIPE_ID id, Type t);
- /**
- Enable the pipe for reading or writing (depending on Type)
- */
- void enable();
+ /**
+ Enable the pipe for reading or writing (depending on Type)
+ */
+ void enable();
- /**
- Close the pipe end.
- */
- void close();
+ /**
+ Close the pipe end.
+ */
+ void close();
- /**
- Release the pipe end, but do not close it.
- */
- void release();
+ /**
+ Release the pipe end, but do not close it.
+ */
+ void release();
- /**
- Set the pipe end to be inheritable
+ /**
+ Set the pipe end to be inheritable
- \note On Windows, this operation changes the pipe end id value.
+ \note On Windows, this operation changes the pipe end id value.
- \param enabled whether the pipe is inheritable (true) or not (false)
- */
- bool setInheritable(bool enabled);
+ \param enabled whether the pipe is inheritable (true) or not (false)
+ */
+ bool setInheritable(bool enabled);
- /**
- Obtain the number of bytes available to be read.
- */
- int bytesAvailable() const;
+ /**
+ Obtain the number of bytes available to be read.
+ */
+ int bytesAvailable() const;
- /**
- Read from the pipe end
+ /**
+ Read from the pipe end
- \param data where to put the data that has been read
- \param maxsize the maximum number of bytes to be read.
+ \param data where to put the data that has been read
+ \param maxsize the maximum number of bytes to be read.
- \return the actual number of bytes read, 0 on end-of-file, or -1 on error.
- */
- int read(char *data, int maxsize);
+ \return the actual number of bytes read, 0 on end-of-file, or -1 on error.
+ */
+ int read(char *data, int maxsize);
- /**
- Write to the pipe end.
+ /**
+ Write to the pipe end.
- \param data the source of the data to be written
- \param size the number of bytes in the data to be written
+ \param data the source of the data to be written
+ \param size the number of bytes in the data to be written
- \note the data source must remain valid
+ \note the data source must remain valid
- \return the number of bytes written, or -1 on error.
- */
- int write(const char *data, int size);
+ \return the number of bytes written, or -1 on error.
+ */
+ int write(const char *data, int size);
- /**
- The result of a write operation
+ /**
+ The result of a write operation
- \param written if not null, this will be set to the number of
- bytes written in the last operation.
+ \param written if not null, this will be set to the number of
+ bytes written in the last operation.
- \return 0 on success (all data written), or -1 on error
- */
- int writeResult(int *written) const;
+ \return 0 on success (all data written), or -1 on error
+ */
+ int writeResult(int *written) const;
Q_SIGNALS:
- /**
- Emitted when the pipe end can be read from or written to (depending on its Type).
- */
- void notify();
+ /**
+ Emitted when the pipe end can be read from or written to (depending on its Type).
+ */
+ void notify();
private:
- Q_DISABLE_COPY(QPipeDevice)
+ Q_DISABLE_COPY(QPipeDevice)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class QPipeEnd qpipe.h QtCrypto
A buffered higher-level pipe end
This is either the read end or write end of a QPipe.
\ingroup UserAPI
*/
class QCA_EXPORT QPipeEnd : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- /**
- The type of error
- */
- enum Error
- {
- ErrorEOF, ///< End of file error
- ErrorBroken ///< Broken pipe error
- };
+ /**
+ The type of error
+ */
+ enum Error {
+ ErrorEOF, ///< End of file error
+ ErrorBroken ///< Broken pipe error
+ };
- /**
- Standard constructor
+ /**
+ Standard constructor
- \param parent the parent object for this object
- */
- QPipeEnd(QObject *parent = 0);
+ \param parent the parent object for this object
+ */
+ QPipeEnd(QObject *parent = 0);
- ~QPipeEnd();
+ ~QPipeEnd();
- /**
- Reset the pipe end to an inactive state
- */
- void reset();
+ /**
+ Reset the pipe end to an inactive state
+ */
+ void reset();
- /**
- The type of pipe end (either read or write)
- */
- QPipeDevice::Type type() const;
+ /**
+ The type of pipe end (either read or write)
+ */
+ QPipeDevice::Type type() const;
- /**
- Determine whether the pipe end is valid.
+ /**
+ Determine whether the pipe end is valid.
- \note This does not mean the pipe is ready to be used - you
- may need to call enable() first
- */
- bool isValid() const;
+ \note This does not mean the pipe is ready to be used - you
+ may need to call enable() first
+ */
+ bool isValid() const;
- /**
- Pipe identification
- */
- Q_PIPE_ID id() const;
+ /**
+ Pipe identification
+ */
+ Q_PIPE_ID id() const;
- /**
- Pipe identification
- */
- int idAsInt() const;
+ /**
+ Pipe identification
+ */
+ int idAsInt() const;
- /**
- Take over an existing pipe handle
+ /**
+ Take over an existing pipe handle
- \param id the pipe handle
- \param t the type of the pipe (read or write)
- */
- void take(Q_PIPE_ID id, QPipeDevice::Type t);
+ \param id the pipe handle
+ \param t the type of the pipe (read or write)
+ */
+ void take(Q_PIPE_ID id, QPipeDevice::Type t);
#ifdef QPIPE_SECURE
- /**
- Sets whether the pipe uses secure memory for read/write
+ /**
+ Sets whether the pipe uses secure memory for read/write
- Enabling this may reduce performance, and it should only be used if
- sensitive data is being transmitted (such as a passphrase).
+ Enabling this may reduce performance, and it should only be used if
+ sensitive data is being transmitted (such as a passphrase).
- \param secure whether the pipe uses secure memory (true) or not (false).
- */
- void setSecurityEnabled(bool secure);
+ \param secure whether the pipe uses secure memory (true) or not (false).
+ */
+ void setSecurityEnabled(bool secure);
#endif
- /**
- Enable the endpoint for the pipe
+ /**
+ Enable the endpoint for the pipe
- When an endpoint is created, it is not
- able to be used until it is enabled.
- */
- void enable();
+ When an endpoint is created, it is not
+ able to be used until it is enabled.
+ */
+ void enable();
- /**
- Close the end of the pipe
+ /**
+ Close the end of the pipe
- \sa closed()
- */
- void close();
+ \sa closed()
+ */
+ void close();
- /**
- Let go of the active pipe handle, but don't close it
+ /**
+ Let go of the active pipe handle, but don't close it
- Use this before destructing QPipeEnd, if you don't want the pipe
- to automatically close.
- */
- void release();
+ Use this before destructing QPipeEnd, if you don't want the pipe
+ to automatically close.
+ */
+ void release();
- /**
- Sets whether the pipe should be inheritable to child processes
+ /**
+ Sets whether the pipe should be inheritable to child processes
- Returns true if inheritability was successfully changed, otherwise
- false.
+ Returns true if inheritability was successfully changed, otherwise
+ false.
- \param enabled whether the pipe is inheritable (true) or not (false).
- */
- bool setInheritable(bool enabled);
+ \param enabled whether the pipe is inheritable (true) or not (false).
+ */
+ bool setInheritable(bool enabled);
- /**
- Clear the contents of the pipe, and invalidate the pipe
- */
- void finalize();
+ /**
+ Clear the contents of the pipe, and invalidate the pipe
+ */
+ void finalize();
- /**
- Clear the contents of the pipe, and release the pipe
- */
- void finalizeAndRelease();
+ /**
+ Clear the contents of the pipe, and release the pipe
+ */
+ void finalizeAndRelease();
- /**
- Determine how many bytes are available to be read.
+ /**
+ Determine how many bytes are available to be read.
- This only makes sense at the read end of the pipe
+ This only makes sense at the read end of the pipe
- \sa readyRead() for a signal that can be used to determine
- when there are bytes available to read.
- */
- int bytesAvailable() const;
+ \sa readyRead() for a signal that can be used to determine
+ when there are bytes available to read.
+ */
+ int bytesAvailable() const;
- /**
- Returns the number of bytes pending to write
+ /**
+ Returns the number of bytes pending to write
- This only makes sense at the write end of the pipe
+ This only makes sense at the write end of the pipe
- \sa bytesWritten() for a signal that can be used to determine
- when bytes have been written
- */
- int bytesToWrite() const;
+ \sa bytesWritten() for a signal that can be used to determine
+ when bytes have been written
+ */
+ int bytesToWrite() const;
- /**
- Read bytes from the pipe.
+ /**
+ Read bytes from the pipe.
- You can only call this on the read end of the pipe
+ You can only call this on the read end of the pipe
- If the pipe is using secure memory, you should use readSecure()
+ If the pipe is using secure memory, you should use readSecure()
- \param bytes the number of bytes to read (-1 for all
- content).
- */
- QByteArray read(int bytes = -1);
+ \param bytes the number of bytes to read (-1 for all
+ content).
+ */
+ QByteArray read(int bytes = -1);
- /**
- Write bytes to the pipe.
+ /**
+ Write bytes to the pipe.
- You can only call this on the write end of the pipe.
+ You can only call this on the write end of the pipe.
- If the pipe is using secure memory, you should use writeSecure().
+ If the pipe is using secure memory, you should use writeSecure().
- \param a the array to write to the pipe
- */
- void write(const QByteArray &a);
+ \param a the array to write to the pipe
+ */
+ void write(const QByteArray &a);
#ifdef QPIPE_SECURE
- /**
- Read bytes from the pipe.
+ /**
+ Read bytes from the pipe.
- You can only call this on the read end of the pipe
+ You can only call this on the read end of the pipe
- If the pipe is using insecure memory, you should use read()
+ If the pipe is using insecure memory, you should use read()
- \param bytes the number of bytes to read (-1 for all
- content).
- */
- SecureArray readSecure(int bytes = -1);
+ \param bytes the number of bytes to read (-1 for all
+ content).
+ */
+ SecureArray readSecure(int bytes = -1);
- /**
- Write bytes to the pipe.
+ /**
+ Write bytes to the pipe.
- You can only call this on the write end of the pipe.
+ You can only call this on the write end of the pipe.
- If the pipe is using insecure memory, you should use write().
+ If the pipe is using insecure memory, you should use write().
- \param a the array to write to the pipe
- */
- void writeSecure(const SecureArray &a);
+ \param a the array to write to the pipe
+ */
+ void writeSecure(const SecureArray &a);
#endif
- /**
- Returns any unsent bytes queued for writing
+ /**
+ Returns any unsent bytes queued for writing
- If the pipe is using secure memory, you should use
- takeBytesToWriteSecure().
- */
- QByteArray takeBytesToWrite();
+ If the pipe is using secure memory, you should use
+ takeBytesToWriteSecure().
+ */
+ QByteArray takeBytesToWrite();
#ifdef QPIPE_SECURE
- /**
- Returns any unsent bytes queued for writing
+ /**
+ Returns any unsent bytes queued for writing
- If the pipe is using insecure memory, you should use
- takeBytesToWrite().
- */
- SecureArray takeBytesToWriteSecure();
+ If the pipe is using insecure memory, you should use
+ takeBytesToWrite().
+ */
+ SecureArray takeBytesToWriteSecure();
#endif
Q_SIGNALS:
- /**
- Emitted when there are bytes available to be read
- from the read end of the pipe.
+ /**
+ Emitted when there are bytes available to be read
+ from the read end of the pipe.
- \sa bytesAvailable()
- */
- void readyRead();
+ \sa bytesAvailable()
+ */
+ void readyRead();
- /**
- Emitted when bytes have been written to the
- write end of the pipe.
+ /**
+ Emitted when bytes have been written to the
+ write end of the pipe.
- \param bytes the number of bytes written
- */
- void bytesWritten(int bytes);
+ \param bytes the number of bytes written
+ */
+ void bytesWritten(int bytes);
- /**
- Emitted when this end of the pipe is closed as a result of calling
- close()
+ /**
+ Emitted when this end of the pipe is closed as a result of calling
+ close()
- If this is the write end of the pipe and there is data still
- pending to write, this signal will be emitted once all of the data
- has been written.
+ If this is the write end of the pipe and there is data still
+ pending to write, this signal will be emitted once all of the data
+ has been written.
- To be notified if the other end of the pipe has been closed, see
- error().
- */
- void closed();
+ To be notified if the other end of the pipe has been closed, see
+ error().
+ */
+ void closed();
- /**
- Emitted when the pipe encounters an error trying to read or write,
- or if the other end of the pipe has been closed
+ /**
+ Emitted when the pipe encounters an error trying to read or write,
+ or if the other end of the pipe has been closed
- \param e the reason for error
- */
- void error(QCA::QPipeEnd::Error e);
+ \param e the reason for error
+ */
+ void error(QCA::QPipeEnd::Error e);
private:
- Q_DISABLE_COPY(QPipeEnd)
+ Q_DISABLE_COPY(QPipeEnd)
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
/**
\class QPipe qpipe.h QtCrypto
A FIFO buffer (named pipe) abstraction
This class creates a full buffer, consisting of two ends
(QPipeEnd). You can obtain each end (after calling create()) using
readEnd() and writeEnd(), however you must call enable() on each end
before using the pipe.
By default, the pipe ends are not inheritable by child processes. On
Windows, the pipe is created with inheritability disabled. On Unix, the
FD_CLOEXEC flag is set on each end's file descriptor.
\ingroup UserAPI
*/
class QCA_EXPORT QPipe
{
public:
- /**
- Standard constructor
+ /**
+ Standard constructor
- \note You must call create() before using the pipe ends.
+ \note You must call create() before using the pipe ends.
- \param parent the parent object for this object
- */
- QPipe(QObject *parent = 0);
+ \param parent the parent object for this object
+ */
+ QPipe(QObject *parent = 0);
- ~QPipe();
+ ~QPipe();
- /**
- Reset the pipe.
+ /**
+ Reset the pipe.
- At this point, the readEnd() and writeEnd() calls
- will no longer be valid.
- */
- void reset();
+ At this point, the readEnd() and writeEnd() calls
+ will no longer be valid.
+ */
+ void reset();
#ifdef QPIPE_SECURE
- /**
- Create the pipe
+ /**
+ Create the pipe
- \param secure whether to use secure memory (true) or not (false)
- */
- bool create(bool secure = false);
+ \param secure whether to use secure memory (true) or not (false)
+ */
+ bool create(bool secure = false);
#else
- /**
- Create the pipe
- */
- bool create();
+ /**
+ Create the pipe
+ */
+ bool create();
#endif
- /**
- The read end of the pipe.
- */
- QPipeEnd & readEnd() { return i; }
-
- /**
- The write end of the pipe.
- */
- QPipeEnd & writeEnd() { return o; }
+ /**
+ The read end of the pipe.
+ */
+ QPipeEnd &readEnd()
+ {
+ return i;
+ }
+
+ /**
+ The write end of the pipe.
+ */
+ QPipeEnd &writeEnd()
+ {
+ return o;
+ }
private:
- Q_DISABLE_COPY(QPipe)
+ Q_DISABLE_COPY(QPipe)
- QPipeEnd i, o;
+ QPipeEnd i, o;
};
}
#endif
diff --git a/plugins/qca-botan/qca-botan.cpp b/plugins/qca-botan/qca-botan.cpp
index d6230748..6bbe99ce 100644
--- a/plugins/qca-botan/qca-botan.cpp
+++ b/plugins/qca-botan/qca-botan.cpp
@@ -1,603 +1,599 @@
/*
* Copyright (C) 2004 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <QTime>
#include <QtPlugin>
#include <qstringlist.h>
#include <botan/hmac.h>
#include <botan/version.h>
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
#include <botan/botan.h>
#include <botan/algo_factory.h>
#else
#include <botan/auto_rng.h>
#include <botan/block_cipher.h>
#include <botan/filters.h>
#include <botan/hash.h>
#include <botan/pbkdf.h>
#include <botan/hkdf.h>
#include <botan/stream_cipher.h>
#endif
#include <stdlib.h>
#include <iostream>
//-----------------------------------------------------------
class botanRandomContext : public QCA::RandomContext
{
public:
botanRandomContext(QCA::Provider *p) : RandomContext(p)
{
}
Context *clone() const
{
- return new botanRandomContext( *this );
+ return new botanRandomContext(*this);
}
QCA::SecureArray nextBytes(int size)
{
QCA::SecureArray buf(size);
- Botan::AutoSeeded_RNG rng;
- rng.randomize(reinterpret_cast<Botan::byte*>(buf.data()), buf.size());
- return buf;
+ Botan::AutoSeeded_RNG rng;
+ rng.randomize(reinterpret_cast<Botan::byte *>(buf.data()), buf.size());
+ return buf;
}
};
-
//-----------------------------------------------------------
class BotanHashContext : public QCA::HashContext
{
public:
- BotanHashContext( const QString &hashName, QCA::Provider *p, const QString &type) : QCA::HashContext(p, type)
+ BotanHashContext(const QString &hashName, QCA::Provider *p, const QString &type) : QCA::HashContext(p, type)
{
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- m_hashObj = Botan::get_hash(hashName.toStdString());
+ m_hashObj = Botan::get_hash(hashName.toStdString());
#else
- m_hashObj = Botan::HashFunction::create(hashName.toStdString()).release();
+ m_hashObj = Botan::HashFunction::create(hashName.toStdString()).release();
#endif
}
~BotanHashContext()
{
- delete m_hashObj;
+ delete m_hashObj;
}
Context *clone() const
{
- return new BotanHashContext(*this);
+ return new BotanHashContext(*this);
}
void clear()
{
- m_hashObj->clear();
+ m_hashObj->clear();
}
void update(const QCA::MemoryRegion &a)
{
- m_hashObj->update( (const Botan::byte*)a.data(), a.size() );
+ m_hashObj->update((const Botan::byte *)a.data(), a.size());
}
QCA::MemoryRegion final()
{
- QCA::SecureArray a( m_hashObj->output_length() );
- m_hashObj->final( (Botan::byte *)a.data() );
- return a;
+ QCA::SecureArray a(m_hashObj->output_length());
+ m_hashObj->final((Botan::byte *)a.data());
+ return a;
}
private:
Botan::HashFunction *m_hashObj;
};
-
//-----------------------------------------------------------
class BotanHMACContext : public QCA::MACContext
{
public:
- BotanHMACContext( const QString &hashName, QCA::Provider *p, const QString &type) : QCA::MACContext(p, type)
+ BotanHMACContext(const QString &hashName, QCA::Provider *p, const QString &type) : QCA::MACContext(p, type)
{
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- m_hashObj = new Botan::HMAC(Botan::global_state().algorithm_factory().make_hash_function(hashName.toStdString()));
+ m_hashObj = new Botan::HMAC(Botan::global_state().algorithm_factory().make_hash_function(hashName.toStdString()));
#else
- m_hashObj = new Botan::HMAC(Botan::HashFunction::create_or_throw(hashName.toStdString()).release());
+ m_hashObj = new Botan::HMAC(Botan::HashFunction::create_or_throw(hashName.toStdString()).release());
#endif
- if (0 == m_hashObj) {
- std::cout << "null context object" << std::endl;
- }
+ if (0 == m_hashObj) {
+ std::cout << "null context object" << std::endl;
+ }
}
~BotanHMACContext()
{
}
void setup(const QCA::SymmetricKey &key)
{
- // this often gets called with an empty key, because that is the default
- // in the QCA MessageAuthenticationCode constructor. Botan doesn't like
- // that happening.
- if (key.size() > 0) {
- m_hashObj->set_key( (const Botan::byte *)key.data(), key.size() );
- }
+ // this often gets called with an empty key, because that is the default
+ // in the QCA MessageAuthenticationCode constructor. Botan doesn't like
+ // that happening.
+ if (key.size() > 0) {
+ m_hashObj->set_key((const Botan::byte *)key.data(), key.size());
+ }
}
Context *clone() const
{
- return new BotanHMACContext(*this);
+ return new BotanHMACContext(*this);
}
void clear()
{
- m_hashObj->clear();
+ m_hashObj->clear();
}
QCA::KeyLength keyLength() const
{
return anyKeyLength();
}
void update(const QCA::MemoryRegion &a)
{
- m_hashObj->update( (const Botan::byte*)a.data(), a.size() );
+ m_hashObj->update((const Botan::byte *)a.data(), a.size());
}
- void final( QCA::MemoryRegion *out)
+ void final(QCA::MemoryRegion *out)
{
- QCA::SecureArray sa( m_hashObj->output_length(), 0 );
- m_hashObj->final( (Botan::byte *)sa.data() );
- *out = sa;
+ QCA::SecureArray sa(m_hashObj->output_length(), 0);
+ m_hashObj->final((Botan::byte *)sa.data());
+ *out = sa;
}
protected:
Botan::HMAC *m_hashObj;
};
-
//-----------------------------------------------------------
class BotanPBKDFContext: public QCA::KDFContext
{
public:
- BotanPBKDFContext( const QString &kdfName, QCA::Provider *p, const QString &type) : QCA::KDFContext(p, type)
+ BotanPBKDFContext(const QString &kdfName, QCA::Provider *p, const QString &type) : QCA::KDFContext(p, type)
{
- m_s2k = Botan::get_s2k(kdfName.toStdString());
+ m_s2k = Botan::get_s2k(kdfName.toStdString());
}
~BotanPBKDFContext()
{
- delete m_s2k;
+ delete m_s2k;
}
Context *clone() const
{
- return new BotanPBKDFContext( *this );
+ return new BotanPBKDFContext(*this);
}
QCA::SymmetricKey makeKey(const QCA::SecureArray &secret, const QCA::InitializationVector &salt,
- unsigned int keyLength, unsigned int iterationCount)
- {
- std::string secretString(secret.data(), secret.size() );
- Botan::OctetString key = m_s2k->derive_key(keyLength, secretString, (const Botan::byte*)salt.data(), salt.size(), iterationCount);
- QCA::SecureArray retval(QByteArray((const char*)key.begin(), key.length()));
- return QCA::SymmetricKey(retval);
- }
-
- QCA::SymmetricKey makeKey(const QCA::SecureArray &secret,
- const QCA::InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount)
- {
- Q_ASSERT(iterationCount != NULL);
- Botan::OctetString key;
- QTime timer;
- std::string secretString(secret.data(), secret.size() );
-
- *iterationCount = 0;
- timer.start();
- while (timer.elapsed() < msecInterval) {
- key = m_s2k->derive_key(keyLength,
- secretString,
- (const Botan::byte*)salt.data(),
- salt.size(),
- 1);
- ++(*iterationCount);
- }
- return makeKey(secret, salt, keyLength, *iterationCount);
- }
+ unsigned int keyLength, unsigned int iterationCount)
+ {
+ std::string secretString(secret.data(), secret.size());
+ Botan::OctetString key = m_s2k->derive_key(keyLength, secretString, (const Botan::byte *)salt.data(), salt.size(), iterationCount);
+ QCA::SecureArray retval(QByteArray((const char *)key.begin(), key.length()));
+ return QCA::SymmetricKey(retval);
+ }
+
+ QCA::SymmetricKey makeKey(const QCA::SecureArray &secret,
+ const QCA::InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount)
+ {
+ Q_ASSERT(iterationCount != NULL);
+ Botan::OctetString key;
+ QTime timer;
+ std::string secretString(secret.data(), secret.size());
+
+ *iterationCount = 0;
+ timer.start();
+ while (timer.elapsed() < msecInterval) {
+ key = m_s2k->derive_key(keyLength,
+ secretString,
+ (const Botan::byte *)salt.data(),
+ salt.size(),
+ 1);
+ ++(*iterationCount);
+ }
+ return makeKey(secret, salt, keyLength, *iterationCount);
+ }
protected:
- Botan::S2K* m_s2k;
+ Botan::S2K *m_s2k;
};
//-----------------------------------------------------------
class BotanHKDFContext: public QCA::HKDFContext
{
public:
BotanHKDFContext(const QString &hashName, QCA::Provider *p, const QString &type) : QCA::HKDFContext(p, type)
{
- Botan::HMAC *hashObj;
+ Botan::HMAC *hashObj;
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- hashObj = new Botan::HMAC(Botan::global_state().algorithm_factory().make_hash_function(hashName.toStdString()));
+ hashObj = new Botan::HMAC(Botan::global_state().algorithm_factory().make_hash_function(hashName.toStdString()));
#else
- hashObj = new Botan::HMAC(Botan::HashFunction::create_or_throw(hashName.toStdString()).release());
+ hashObj = new Botan::HMAC(Botan::HashFunction::create_or_throw(hashName.toStdString()).release());
#endif
- m_hkdf = new Botan::HKDF(hashObj);
+ m_hkdf = new Botan::HKDF(hashObj);
}
~BotanHKDFContext()
{
- delete m_hkdf;
+ delete m_hkdf;
}
Context *clone() const
{
- return new BotanHKDFContext( *this );
+ return new BotanHKDFContext(*this);
}
QCA::SymmetricKey makeKey(const QCA::SecureArray &secret, const QCA::InitializationVector &salt,
- const QCA::InitializationVector &info, unsigned int keyLength)
+ const QCA::InitializationVector &info, unsigned int keyLength)
{
- std::string secretString(secret.data(), secret.size());
- Botan::secure_vector<uint8_t> key(keyLength);
- m_hkdf->kdf(key.data(), keyLength,
- reinterpret_cast<const Botan::byte*>(secret.data()), secret.size(),
- reinterpret_cast<const Botan::byte*>(salt.data()), salt.size(),
- reinterpret_cast<const Botan::byte*>(info.data()), info.size());
- QCA::SecureArray retval(QByteArray::fromRawData(reinterpret_cast<const char*>(key.data()), key.size()));
- return QCA::SymmetricKey(retval);
+ std::string secretString(secret.data(), secret.size());
+ Botan::secure_vector<uint8_t> key(keyLength);
+ m_hkdf->kdf(key.data(), keyLength,
+ reinterpret_cast<const Botan::byte *>(secret.data()), secret.size(),
+ reinterpret_cast<const Botan::byte *>(salt.data()), salt.size(),
+ reinterpret_cast<const Botan::byte *>(info.data()), info.size());
+ QCA::SecureArray retval(QByteArray::fromRawData(reinterpret_cast<const char *>(key.data()), key.size()));
+ return QCA::SymmetricKey(retval);
}
protected:
- Botan::HKDF* m_hkdf;
+ Botan::HKDF *m_hkdf;
};
-
//-----------------------------------------------------------
class BotanCipherContext : public QCA::CipherContext
{
public:
- BotanCipherContext( const QString &algo, const QString &mode, const QString &padding,
- QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type)
+ BotanCipherContext(const QString &algo, const QString &mode, const QString &padding,
+ QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type)
{
- m_algoName = algo.toStdString();
- m_algoMode = mode.toStdString();
- m_algoPadding = padding.toStdString();
+ m_algoName = algo.toStdString();
+ m_algoMode = mode.toStdString();
+ m_algoPadding = padding.toStdString();
}
void setup(QCA::Direction dir,
const QCA::SymmetricKey &key,
const QCA::InitializationVector &iv,
const QCA::AuthTag &tag)
{
- Q_UNUSED(tag);
- try {
- m_dir = dir;
- Botan::SymmetricKey keyCopy((Botan::byte*)key.data(), key.size());
-
- if (iv.size() == 0) {
- if (QCA::Encode == dir) {
- m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding,
- keyCopy, Botan::ENCRYPTION));
- }
- else {
- m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding,
- keyCopy, Botan::DECRYPTION));
- }
- } else {
- Botan::InitializationVector ivCopy((Botan::byte*)iv.data(), iv.size());
- if (QCA::Encode == dir) {
- m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding,
- keyCopy, ivCopy, Botan::ENCRYPTION));
- }
- else {
- m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName+'/'+m_algoMode+'/'+m_algoPadding,
- keyCopy, ivCopy, Botan::DECRYPTION));
- }
- }
- m_crypter->start_msg();
- } catch (Botan::Exception& e) {
- std::cout << "caught: " << e.what() << std::endl;
- }
+ Q_UNUSED(tag);
+ try {
+ m_dir = dir;
+ Botan::SymmetricKey keyCopy((Botan::byte *)key.data(), key.size());
+
+ if (iv.size() == 0) {
+ if (QCA::Encode == dir) {
+ m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName + '/' + m_algoMode + '/' + m_algoPadding,
+ keyCopy, Botan::ENCRYPTION));
+ } else {
+ m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName + '/' + m_algoMode + '/' + m_algoPadding,
+ keyCopy, Botan::DECRYPTION));
+ }
+ } else {
+ Botan::InitializationVector ivCopy((Botan::byte *)iv.data(), iv.size());
+ if (QCA::Encode == dir) {
+ m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName + '/' + m_algoMode + '/' + m_algoPadding,
+ keyCopy, ivCopy, Botan::ENCRYPTION));
+ } else {
+ m_crypter = new Botan::Pipe(Botan::get_cipher(m_algoName + '/' + m_algoMode + '/' + m_algoPadding,
+ keyCopy, ivCopy, Botan::DECRYPTION));
+ }
+ }
+ m_crypter->start_msg();
+ } catch (Botan::Exception &e) {
+ std::cout << "caught: " << e.what() << std::endl;
+ }
}
Context *clone() const
{
- return new BotanCipherContext( *this );
+ return new BotanCipherContext(*this);
}
int blockSize() const
{
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- return Botan::block_size_of(m_algoName);
+ return Botan::block_size_of(m_algoName);
#else
- if(const std::unique_ptr<Botan::BlockCipher> bc = Botan::BlockCipher::create(m_algoName))
- return bc->block_size();
-
- throw Botan::Algorithm_Not_Found(m_algoName);
+ if (const std::unique_ptr<Botan::BlockCipher> bc = Botan::BlockCipher::create(m_algoName)) {
+ return bc->block_size();
+ }
+
+ throw Botan::Algorithm_Not_Found(m_algoName);
#endif
}
QCA::AuthTag tag() const
{
- // For future implementation
- return QCA::AuthTag();
+ // For future implementation
+ return QCA::AuthTag();
}
bool update(const QCA::SecureArray &in, QCA::SecureArray *out)
{
- m_crypter->write((Botan::byte*)in.data(), in.size());
- QCA::SecureArray result( m_crypter->remaining() );
- // Perhaps bytes_read is redundant and can be dropped
- size_t bytes_read = m_crypter->read((Botan::byte*)result.data(), result.size());
- result.resize(bytes_read);
+ m_crypter->write((Botan::byte *)in.data(), in.size());
+ QCA::SecureArray result(m_crypter->remaining());
+ // Perhaps bytes_read is redundant and can be dropped
+ size_t bytes_read = m_crypter->read((Botan::byte *)result.data(), result.size());
+ result.resize(bytes_read);
*out = result;
return true;
}
bool final(QCA::SecureArray *out)
{
- m_crypter->end_msg();
- QCA::SecureArray result( m_crypter->remaining() );
- // Perhaps bytes_read is redundant and can be dropped
- size_t bytes_read = m_crypter->read((Botan::byte*)result.data(), result.size());
- result.resize(bytes_read);
+ m_crypter->end_msg();
+ QCA::SecureArray result(m_crypter->remaining());
+ // Perhaps bytes_read is redundant and can be dropped
+ size_t bytes_read = m_crypter->read((Botan::byte *)result.data(), result.size());
+ result.resize(bytes_read);
*out = result;
return true;
}
QCA::KeyLength keyLength() const
{
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
Botan::Algorithm_Factory &af = Botan::global_state().algorithm_factory();
#endif
Botan::Key_Length_Specification kls(0);
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- if(const Botan::BlockCipher *bc = af.prototype_block_cipher(m_algoName))
+ if (const Botan::BlockCipher *bc = af.prototype_block_cipher(m_algoName))
#else
- if(const std::unique_ptr<Botan::BlockCipher> bc = Botan::BlockCipher::create(m_algoName))
+ if (const std::unique_ptr<Botan::BlockCipher> bc = Botan::BlockCipher::create(m_algoName))
#endif
kls = bc->key_spec();
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- else if(const Botan::StreamCipher *sc = af.prototype_stream_cipher(m_algoName))
+ else if (const Botan::StreamCipher *sc = af.prototype_stream_cipher(m_algoName))
#else
- else if(const std::unique_ptr<Botan::StreamCipher> sc = Botan::StreamCipher::create(m_algoName))
+ else if (const std::unique_ptr<Botan::StreamCipher> sc = Botan::StreamCipher::create(m_algoName))
#endif
kls = sc->key_spec();
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- else if(const Botan::MessageAuthenticationCode *mac = af.prototype_mac(m_algoName))
+ else if (const Botan::MessageAuthenticationCode *mac = af.prototype_mac(m_algoName))
#else
- else if(const std::unique_ptr<Botan::MessageAuthenticationCode> mac = Botan::MessageAuthenticationCode::create(m_algoName))
+ else if (const std::unique_ptr<Botan::MessageAuthenticationCode> mac = Botan::MessageAuthenticationCode::create(m_algoName))
#endif
kls = mac->key_spec();
- return QCA::KeyLength( kls.minimum_keylength(),
- kls.maximum_keylength(),
- kls.keylength_multiple() );
+ return QCA::KeyLength(kls.minimum_keylength(),
+ kls.maximum_keylength(),
+ kls.keylength_multiple());
}
-
~BotanCipherContext()
{
- delete m_crypter;
+ delete m_crypter;
}
protected:
QCA::Direction m_dir;
std::string m_algoName;
std::string m_algoMode;
std::string m_algoPadding;
Botan::Keyed_Filter *m_cipher;
Botan::Pipe *m_crypter;
};
-
-
//==========================================================
class botanProvider : public QCA::Provider
{
public:
void init()
{
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
- m_init = new Botan::LibraryInitializer;
+ m_init = new Botan::LibraryInitializer;
#endif
}
~botanProvider()
{
- // We should be cleaning up there, but
- // this causes the unit tests to segfault
- // delete m_init;
+ // We should be cleaning up there, but
+ // this causes the unit tests to segfault
+ // delete m_init;
}
int qcaVersion() const
{
return QCA_VERSION;
}
QString name() const
{
- return "qca-botan";
+ return "qca-botan";
}
QStringList features() const
{
- QStringList list;
- list += "random";
- list += "md2";
- list += "md4";
- list += "md5";
- list += "sha1";
- list += "sha256";
- list += "sha384";
- list += "sha512";
- list += "ripemd160";
- list += "hmac(md5)";
- list += "hmac(sha1)";
+ QStringList list;
+ list += "random";
+ list += "md2";
+ list += "md4";
+ list += "md5";
+ list += "sha1";
+ list += "sha256";
+ list += "sha384";
+ list += "sha512";
+ list += "ripemd160";
+ list += "hmac(md5)";
+ list += "hmac(sha1)";
// HMAC with SHA2 doesn't appear to work correctly in Botan.
- // list += "hmac(sha256)";
- // list += "hmac(sha384)";
- // list += "hmac(sha512)";
- list += "hmac(ripemd160)";
- list += "pbkdf1(sha1)";
- list += "pbkdf1(md2)";
- list += "pbkdf2(sha1)";
- list += "hkdf(sha256)";
- list += "aes128-ecb";
- list += "aes128-cbc";
- list += "aes128-cfb";
- list += "aes128-ofb";
- list += "aes192-ecb";
- list += "aes192-cbc";
- list += "aes192-cfb";
- list += "aes192-ofb";
- list += "aes256-ecb";
- list += "aes256-cbc";
- list += "aes256-cfb";
- list += "aes256-ofb";
- list += "des-ecb";
- list += "des-ecb-pkcs7";
- list += "des-cbc";
- list += "des-cbc-pkcs7";
- list += "des-cfb";
- list += "des-ofb";
- list += "tripledes-ecb";
- list += "blowfish-ecb";
- list += "blowfish-cbc";
- list += "blowfish-cbc-pkcs7";
- list += "blowfish-cfb";
- list += "blowfish-ofb";
- return list;
+ // list += "hmac(sha256)";
+ // list += "hmac(sha384)";
+ // list += "hmac(sha512)";
+ list += "hmac(ripemd160)";
+ list += "pbkdf1(sha1)";
+ list += "pbkdf1(md2)";
+ list += "pbkdf2(sha1)";
+ list += "hkdf(sha256)";
+ list += "aes128-ecb";
+ list += "aes128-cbc";
+ list += "aes128-cfb";
+ list += "aes128-ofb";
+ list += "aes192-ecb";
+ list += "aes192-cbc";
+ list += "aes192-cfb";
+ list += "aes192-ofb";
+ list += "aes256-ecb";
+ list += "aes256-cbc";
+ list += "aes256-cfb";
+ list += "aes256-ofb";
+ list += "des-ecb";
+ list += "des-ecb-pkcs7";
+ list += "des-cbc";
+ list += "des-cbc-pkcs7";
+ list += "des-cfb";
+ list += "des-ofb";
+ list += "tripledes-ecb";
+ list += "blowfish-ecb";
+ list += "blowfish-cbc";
+ list += "blowfish-cbc-pkcs7";
+ list += "blowfish-cfb";
+ list += "blowfish-ofb";
+ return list;
}
Context *createContext(const QString &type)
{
- if ( type == "random" )
- return new botanRandomContext( this );
- else if ( type == "md2" )
- return new BotanHashContext( QString("MD2"), this, type );
- else if ( type == "md4" )
- return new BotanHashContext( QString("MD4"), this, type );
- else if ( type == "md5" )
- return new BotanHashContext( QString("MD5"), this, type );
- else if ( type == "sha1" )
- return new BotanHashContext( QString("SHA-1"), this, type );
- else if ( type == "sha256" )
- return new BotanHashContext( QString("SHA-256"), this, type );
- else if ( type == "sha384" )
- return new BotanHashContext( QString("SHA-384"), this, type );
- else if ( type == "sha512" )
- return new BotanHashContext( QString("SHA-512"), this, type );
- else if ( type == "ripemd160" )
- return new BotanHashContext( QString("RIPEMD-160"), this, type );
- else if ( type == "hmac(md5)" )
- return new BotanHMACContext( QString("MD5"), this, type );
- else if ( type == "hmac(sha1)" )
- return new BotanHMACContext( QString("SHA-1"), this, type );
- else if ( type == "hmac(sha256)" )
- return new BotanHMACContext( QString("SHA-256"), this, type );
- else if ( type == "hmac(sha384)" )
- return new BotanHMACContext( QString("SHA-384"), this, type );
- else if ( type == "hmac(sha512)" )
- return new BotanHMACContext( QString("SHA-512"), this, type );
- else if ( type == "hmac(ripemd160)" )
- return new BotanHMACContext( QString("RIPEMD-160"), this, type );
- else if ( type == "pbkdf1(sha1)" )
- return new BotanPBKDFContext( QString("PBKDF1(SHA-1)"), this, type );
- else if ( type == "pbkdf1(md2)" )
- return new BotanPBKDFContext( QString("PBKDF1(MD2)"), this, type );
- else if ( type == "pbkdf2(sha1)" )
- return new BotanPBKDFContext( QString("PBKDF2(SHA-1)"), this, type );
- else if ( type == "hkdf(sha256)" )
- return new BotanHKDFContext( QString("SHA-256"), this, type );
- else if ( type == "aes128-ecb" )
- return new BotanCipherContext( QString("AES-128"), QString("ECB"), QString("NoPadding"), this, type );
- else if ( type == "aes128-cbc" )
- return new BotanCipherContext( QString("AES-128"), QString("CBC"), QString("NoPadding"), this, type );
- else if ( type == "aes128-cfb" )
- return new BotanCipherContext( QString("AES-128"), QString("CFB"), QString("NoPadding"), this, type );
- else if ( type == "aes128-ofb" )
- return new BotanCipherContext( QString("AES-128"), QString("OFB"), QString("NoPadding"), this, type );
- else if ( type == "aes192-ecb" )
- return new BotanCipherContext( QString("AES-192"), QString("ECB"), QString("NoPadding"), this, type );
- else if ( type == "aes192-cbc" )
- return new BotanCipherContext( QString("AES-192"), QString("CBC"), QString("NoPadding"), this, type );
- else if ( type == "aes192-cfb" )
- return new BotanCipherContext( QString("AES-192"), QString("CFB"), QString("NoPadding"), this, type );
- else if ( type == "aes192-ofb" )
- return new BotanCipherContext( QString("AES-192"), QString("OFB"), QString("NoPadding"), this, type );
- else if ( type == "aes256-ecb" )
- return new BotanCipherContext( QString("AES-256"), QString("ECB"), QString("NoPadding"), this, type );
- else if ( type == "aes256-cbc" )
- return new BotanCipherContext( QString("AES-256"), QString("CBC"), QString("NoPadding"), this, type );
- else if ( type == "aes256-cfb" )
- return new BotanCipherContext( QString("AES-256"), QString("CFB"), QString("NoPadding"), this, type );
- else if ( type == "aes256-ofb" )
- return new BotanCipherContext( QString("AES-256"), QString("OFB"), QString("NoPadding"), this, type );
- else if ( type == "blowfish-ecb" )
- return new BotanCipherContext( QString("Blowfish"), QString("ECB"), QString("NoPadding"), this, type );
- else if ( type == "blowfish-cbc" )
- return new BotanCipherContext( QString("Blowfish"), QString("CBC"), QString("NoPadding"), this, type );
- else if ( type == "blowfish-cbc-pkcs7" )
- return new BotanCipherContext( QString("Blowfish"), QString("CBC"), QString("PKCS7"), this, type );
- else if ( type == "blowfish-cfb" )
- return new BotanCipherContext( QString("Blowfish"), QString("CFB"), QString("NoPadding"), this, type );
- else if ( type == "blowfish-ofb" )
- return new BotanCipherContext( QString("Blowfish"), QString("OFB"), QString("NoPadding"), this, type );
- else if ( type == "des-ecb" )
- return new BotanCipherContext( QString("DES"), QString("ECB"), QString("NoPadding"), this, type );
- else if ( type == "des-ecb-pkcs7" )
- return new BotanCipherContext( QString("DES"), QString("ECB"), QString("PKCS7"), this, type );
- else if ( type == "des-cbc" )
- return new BotanCipherContext( QString("DES"), QString("CBC"), QString("NoPadding"), this, type );
- else if ( type == "des-cbc-pkcs7" )
- return new BotanCipherContext( QString("DES"), QString("CBC"), QString("PKCS7"), this, type );
- else if ( type == "des-cfb" )
- return new BotanCipherContext( QString("DES"), QString("CFB"), QString("NoPadding"), this, type );
- else if ( type == "des-ofb" )
- return new BotanCipherContext( QString("DES"), QString("OFB"), QString("NoPadding"), this, type );
- else if ( type == "tripledes-ecb" )
- return new BotanCipherContext( QString("TripleDES"), QString("ECB"), QString("NoPadding"), this, type );
- else
- return 0;
+ if (type == "random") {
+ return new botanRandomContext(this);
+ } else if (type == "md2") {
+ return new BotanHashContext(QString("MD2"), this, type);
+ } else if (type == "md4") {
+ return new BotanHashContext(QString("MD4"), this, type);
+ } else if (type == "md5") {
+ return new BotanHashContext(QString("MD5"), this, type);
+ } else if (type == "sha1") {
+ return new BotanHashContext(QString("SHA-1"), this, type);
+ } else if (type == "sha256") {
+ return new BotanHashContext(QString("SHA-256"), this, type);
+ } else if (type == "sha384") {
+ return new BotanHashContext(QString("SHA-384"), this, type);
+ } else if (type == "sha512") {
+ return new BotanHashContext(QString("SHA-512"), this, type);
+ } else if (type == "ripemd160") {
+ return new BotanHashContext(QString("RIPEMD-160"), this, type);
+ } else if (type == "hmac(md5)") {
+ return new BotanHMACContext(QString("MD5"), this, type);
+ } else if (type == "hmac(sha1)") {
+ return new BotanHMACContext(QString("SHA-1"), this, type);
+ } else if (type == "hmac(sha256)") {
+ return new BotanHMACContext(QString("SHA-256"), this, type);
+ } else if (type == "hmac(sha384)") {
+ return new BotanHMACContext(QString("SHA-384"), this, type);
+ } else if (type == "hmac(sha512)") {
+ return new BotanHMACContext(QString("SHA-512"), this, type);
+ } else if (type == "hmac(ripemd160)") {
+ return new BotanHMACContext(QString("RIPEMD-160"), this, type);
+ } else if (type == "pbkdf1(sha1)") {
+ return new BotanPBKDFContext(QString("PBKDF1(SHA-1)"), this, type);
+ } else if (type == "pbkdf1(md2)") {
+ return new BotanPBKDFContext(QString("PBKDF1(MD2)"), this, type);
+ } else if (type == "pbkdf2(sha1)") {
+ return new BotanPBKDFContext(QString("PBKDF2(SHA-1)"), this, type);
+ } else if (type == "hkdf(sha256)") {
+ return new BotanHKDFContext(QString("SHA-256"), this, type);
+ } else if (type == "aes128-ecb") {
+ return new BotanCipherContext(QString("AES-128"), QString("ECB"), QString("NoPadding"), this, type);
+ } else if (type == "aes128-cbc") {
+ return new BotanCipherContext(QString("AES-128"), QString("CBC"), QString("NoPadding"), this, type);
+ } else if (type == "aes128-cfb") {
+ return new BotanCipherContext(QString("AES-128"), QString("CFB"), QString("NoPadding"), this, type);
+ } else if (type == "aes128-ofb") {
+ return new BotanCipherContext(QString("AES-128"), QString("OFB"), QString("NoPadding"), this, type);
+ } else if (type == "aes192-ecb") {
+ return new BotanCipherContext(QString("AES-192"), QString("ECB"), QString("NoPadding"), this, type);
+ } else if (type == "aes192-cbc") {
+ return new BotanCipherContext(QString("AES-192"), QString("CBC"), QString("NoPadding"), this, type);
+ } else if (type == "aes192-cfb") {
+ return new BotanCipherContext(QString("AES-192"), QString("CFB"), QString("NoPadding"), this, type);
+ } else if (type == "aes192-ofb") {
+ return new BotanCipherContext(QString("AES-192"), QString("OFB"), QString("NoPadding"), this, type);
+ } else if (type == "aes256-ecb") {
+ return new BotanCipherContext(QString("AES-256"), QString("ECB"), QString("NoPadding"), this, type);
+ } else if (type == "aes256-cbc") {
+ return new BotanCipherContext(QString("AES-256"), QString("CBC"), QString("NoPadding"), this, type);
+ } else if (type == "aes256-cfb") {
+ return new BotanCipherContext(QString("AES-256"), QString("CFB"), QString("NoPadding"), this, type);
+ } else if (type == "aes256-ofb") {
+ return new BotanCipherContext(QString("AES-256"), QString("OFB"), QString("NoPadding"), this, type);
+ } else if (type == "blowfish-ecb") {
+ return new BotanCipherContext(QString("Blowfish"), QString("ECB"), QString("NoPadding"), this, type);
+ } else if (type == "blowfish-cbc") {
+ return new BotanCipherContext(QString("Blowfish"), QString("CBC"), QString("NoPadding"), this, type);
+ } else if (type == "blowfish-cbc-pkcs7") {
+ return new BotanCipherContext(QString("Blowfish"), QString("CBC"), QString("PKCS7"), this, type);
+ } else if (type == "blowfish-cfb") {
+ return new BotanCipherContext(QString("Blowfish"), QString("CFB"), QString("NoPadding"), this, type);
+ } else if (type == "blowfish-ofb") {
+ return new BotanCipherContext(QString("Blowfish"), QString("OFB"), QString("NoPadding"), this, type);
+ } else if (type == "des-ecb") {
+ return new BotanCipherContext(QString("DES"), QString("ECB"), QString("NoPadding"), this, type);
+ } else if (type == "des-ecb-pkcs7") {
+ return new BotanCipherContext(QString("DES"), QString("ECB"), QString("PKCS7"), this, type);
+ } else if (type == "des-cbc") {
+ return new BotanCipherContext(QString("DES"), QString("CBC"), QString("NoPadding"), this, type);
+ } else if (type == "des-cbc-pkcs7") {
+ return new BotanCipherContext(QString("DES"), QString("CBC"), QString("PKCS7"), this, type);
+ } else if (type == "des-cfb") {
+ return new BotanCipherContext(QString("DES"), QString("CFB"), QString("NoPadding"), this, type);
+ } else if (type == "des-ofb") {
+ return new BotanCipherContext(QString("DES"), QString("OFB"), QString("NoPadding"), this, type);
+ } else if (type == "tripledes-ecb") {
+ return new BotanCipherContext(QString("TripleDES"), QString("ECB"), QString("NoPadding"), this, type);
+ } else {
+ return 0;
+ }
}
private:
#if BOTAN_VERSION_CODE < BOTAN_VERSION_CODE_FOR(2,0,0)
Botan::LibraryInitializer *m_init;
#endif
};
class botanPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual QCA::Provider *createProvider() { return new botanProvider; }
+ virtual QCA::Provider *createProvider()
+ {
+ return new botanProvider;
+ }
};
#include "qca-botan.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_botan, botanPlugin);
#endif
diff --git a/plugins/qca-cyrus-sasl/qca-cyrus-sasl.cpp b/plugins/qca-cyrus-sasl/qca-cyrus-sasl.cpp
index a7cf5806..4c39cf6c 100644
--- a/plugins/qca-cyrus-sasl/qca-cyrus-sasl.cpp
+++ b/plugins/qca-cyrus-sasl/qca-cyrus-sasl.cpp
@@ -1,952 +1,998 @@
/*
* qca-sasl.cpp - SASL plugin for QCA
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2006 Michail Pishchagin <mblsha@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <qcaprovider.h>
#include <QDebug>
#include <QtPlugin>
extern "C"
{
#include <sasl/sasl.h>
}
#include <QStringList>
#include <QList>
#include <QFile>
#define SASL_BUFSIZE 8192
#define SASL_APP "qca"
using namespace QCA;
-namespace saslQCAPlugin {
+namespace saslQCAPlugin
+{
class saslProvider : public Provider
{
public:
- saslProvider();
- void init();
- ~saslProvider();
- int qcaVersion() const;
- QString name() const;
- QString credit() const;
- QStringList features() const;
- Context *createContext(const QString &type);
-
- bool client_init;
- bool server_init;
- QString appname;
+ saslProvider();
+ void init();
+ ~saslProvider();
+ int qcaVersion() const;
+ QString name() const;
+ QString credit() const;
+ QStringList features() const;
+ Context *createContext(const QString &type);
+
+ bool client_init;
+ bool server_init;
+ QString appname;
};
//----------------------------------------------------------------------------
// SASLParams
//----------------------------------------------------------------------------
class SASLParams
{
public:
- class SParams
- {
- public:
- bool user, authzid, pass, realm;
- };
-
- SASLParams()
- {
- reset();
- }
-
- void reset()
- {
- resetNeed();
- resetHave();
- foreach(char *result, results)
- delete result;
- results.clear();
- }
-
- void resetNeed()
- {
- need.user = false;
- need.authzid = false;
- need.pass = false;
- need.realm = false;
- }
-
- void resetHave()
- {
- have.user = false;
- have.authzid = false;
- have.pass = false;
- have.realm = false;
- }
-
- void setUsername(const QString &s)
- {
- have.user = true;
- user = s;
- }
-
- void setAuthzid(const QString &s)
- {
- have.authzid = true;
- authzid = s;
- }
-
- void setPassword(const SecureArray &s)
- {
- have.pass = true;
- pass = QString::fromUtf8(s.toByteArray());
- }
-
- void setRealm(const QString &s)
- {
- have.realm = true;
- realm = s;
- }
-
- void applyInteract(sasl_interact_t *needp)
- {
- for(int n = 0; needp[n].id != SASL_CB_LIST_END; ++n) {
- if(needp[n].id == SASL_CB_AUTHNAME)
- need.user = true; // yes, I know these
- if(needp[n].id == SASL_CB_USER)
- need.authzid = true; // look backwards
- if(needp[n].id == SASL_CB_PASS)
- need.pass = true;
- if(needp[n].id == SASL_CB_GETREALM)
- need.realm = true;
- }
- }
-
- void extractHave(sasl_interact_t *needp)
- {
- for(int n = 0; needp[n].id != SASL_CB_LIST_END; ++n) {
- if(needp[n].id == SASL_CB_AUTHNAME && have.user)
- setValue(&needp[n], user);
- if(needp[n].id == SASL_CB_USER && have.authzid)
- setValue(&needp[n], authzid);
- if(needp[n].id == SASL_CB_PASS && have.pass)
- setValue(&needp[n], pass);
- if(needp[n].id == SASL_CB_GETREALM && have.realm)
- setValue(&needp[n], realm);
- }
- }
-
- bool missingAny() const
- {
- if((need.user && !have.user) /*|| (need.authzid && !have.authzid)*/ || (need.pass && !have.pass) /*|| (need.realm && !have.realm)*/)
- return true;
- return false;
- }
-
- SParams missing() const
- {
- SParams np = need;
- if(have.user)
- np.user = false;
- if(have.authzid)
- np.authzid = false;
- if(have.pass)
- np.pass = false;
- if(have.realm)
- np.realm = false;
- return np;
- }
-
- void setValue(sasl_interact_t *i, const QString &s)
- {
- if(i->result)
- return;
- QByteArray cs = s.toUtf8();
- int len = cs.length();
- char *p = new char[len+1];
- memcpy(p, cs.data(), len);
- p[len] = 0;
- i->result = p;
- i->len = len;
-
- // record this
- results.append(p);
- }
-
- QList<char *> results;
- SParams need;
- SParams have;
- QString user, authzid, pass, realm;
+ class SParams
+ {
+ public:
+ bool user, authzid, pass, realm;
+ };
+
+ SASLParams()
+ {
+ reset();
+ }
+
+ void reset()
+ {
+ resetNeed();
+ resetHave();
+ foreach (char *result, results) {
+ delete result;
+ }
+ results.clear();
+ }
+
+ void resetNeed()
+ {
+ need.user = false;
+ need.authzid = false;
+ need.pass = false;
+ need.realm = false;
+ }
+
+ void resetHave()
+ {
+ have.user = false;
+ have.authzid = false;
+ have.pass = false;
+ have.realm = false;
+ }
+
+ void setUsername(const QString &s)
+ {
+ have.user = true;
+ user = s;
+ }
+
+ void setAuthzid(const QString &s)
+ {
+ have.authzid = true;
+ authzid = s;
+ }
+
+ void setPassword(const SecureArray &s)
+ {
+ have.pass = true;
+ pass = QString::fromUtf8(s.toByteArray());
+ }
+
+ void setRealm(const QString &s)
+ {
+ have.realm = true;
+ realm = s;
+ }
+
+ void applyInteract(sasl_interact_t *needp)
+ {
+ for (int n = 0; needp[n].id != SASL_CB_LIST_END; ++n) {
+ if (needp[n].id == SASL_CB_AUTHNAME) {
+ need.user = true; // yes, I know these
+ }
+ if (needp[n].id == SASL_CB_USER) {
+ need.authzid = true; // look backwards
+ }
+ if (needp[n].id == SASL_CB_PASS) {
+ need.pass = true;
+ }
+ if (needp[n].id == SASL_CB_GETREALM) {
+ need.realm = true;
+ }
+ }
+ }
+
+ void extractHave(sasl_interact_t *needp)
+ {
+ for (int n = 0; needp[n].id != SASL_CB_LIST_END; ++n) {
+ if (needp[n].id == SASL_CB_AUTHNAME && have.user) {
+ setValue(&needp[n], user);
+ }
+ if (needp[n].id == SASL_CB_USER && have.authzid) {
+ setValue(&needp[n], authzid);
+ }
+ if (needp[n].id == SASL_CB_PASS && have.pass) {
+ setValue(&needp[n], pass);
+ }
+ if (needp[n].id == SASL_CB_GETREALM && have.realm) {
+ setValue(&needp[n], realm);
+ }
+ }
+ }
+
+ bool missingAny() const
+ {
+ if ((need.user && !have.user) /*|| (need.authzid && !have.authzid)*/ || (need.pass && !have.pass) /*|| (need.realm && !have.realm)*/) {
+ return true;
+ }
+ return false;
+ }
+
+ SParams missing() const
+ {
+ SParams np = need;
+ if (have.user) {
+ np.user = false;
+ }
+ if (have.authzid) {
+ np.authzid = false;
+ }
+ if (have.pass) {
+ np.pass = false;
+ }
+ if (have.realm) {
+ np.realm = false;
+ }
+ return np;
+ }
+
+ void setValue(sasl_interact_t *i, const QString &s)
+ {
+ if (i->result) {
+ return;
+ }
+ QByteArray cs = s.toUtf8();
+ int len = cs.length();
+ char *p = new char[len + 1];
+ memcpy(p, cs.data(), len);
+ p[len] = 0;
+ i->result = p;
+ i->len = len;
+
+ // record this
+ results.append(p);
+ }
+
+ QList<char *> results;
+ SParams need;
+ SParams have;
+ QString user, authzid, pass, realm;
};
static QByteArray makeByteArray(const void *in, unsigned int len)
{
- QByteArray buf(len, 0);
- memcpy(buf.data(), in, len);
- return buf;
+ QByteArray buf(len, 0);
+ memcpy(buf.data(), in, len);
+ return buf;
}
static QString addrString(const SASLContext::HostPort &hp)
{
- return (hp.addr + ';' + QString::number(hp.port));
+ return (hp.addr + ';' + QString::number(hp.port));
}
//----------------------------------------------------------------------------
// saslContext
//----------------------------------------------------------------------------
class saslContext : public SASLContext
{
- saslProvider *g;
-
- // core props
- QString service, host;
- QString localAddr, remoteAddr;
-
- // security props
- int secflags;
- int ssf_min, ssf_max;
- QString ext_authid;
- int ext_ssf;
-
- sasl_conn_t *con;
- sasl_interact_t *need;
- int maxoutbuf;
- sasl_callback_t *callbacks;
-
- // state
- bool servermode;
- int step;
- bool in_sendFirst;
- QByteArray in_buf;
- QString in_mech;
- bool in_useClientInit;
- QByteArray in_clientInit;
- QString out_mech;
- // bool out_useClientInit;
- // QByteArray out_clientInit;
- QByteArray out_buf;
-
- SASLParams params;
- QString sc_username, sc_authzid;
- bool ca_flag, ca_done, ca_skip;
- int last_r;
-
- int result_ssf;
- Result result_result;
- bool result_haveClientInit;
- QStringList result_mechlist;
- SASL::AuthCondition result_authCondition;
- QByteArray result_to_net;
- QByteArray result_plain;
- int result_encoded;
+ saslProvider *g;
+
+ // core props
+ QString service, host;
+ QString localAddr, remoteAddr;
+
+ // security props
+ int secflags;
+ int ssf_min, ssf_max;
+ QString ext_authid;
+ int ext_ssf;
+
+ sasl_conn_t *con;
+ sasl_interact_t *need;
+ int maxoutbuf;
+ sasl_callback_t *callbacks;
+
+ // state
+ bool servermode;
+ int step;
+ bool in_sendFirst;
+ QByteArray in_buf;
+ QString in_mech;
+ bool in_useClientInit;
+ QByteArray in_clientInit;
+ QString out_mech;
+ // bool out_useClientInit;
+ // QByteArray out_clientInit;
+ QByteArray out_buf;
+
+ SASLParams params;
+ QString sc_username, sc_authzid;
+ bool ca_flag, ca_done, ca_skip;
+ int last_r;
+
+ int result_ssf;
+ Result result_result;
+ bool result_haveClientInit;
+ QStringList result_mechlist;
+ SASL::AuthCondition result_authCondition;
+ QByteArray result_to_net;
+ QByteArray result_plain;
+ int result_encoded;
private:
- void resetState()
- {
- if(con) {
- sasl_dispose(&con);
- con = 0;
- }
- need = 0;
- if(callbacks) {
- delete callbacks;
- callbacks = 0;
- }
-
- localAddr = "";
- remoteAddr = "";
- maxoutbuf = 128;
- sc_username = "";
- sc_authzid = "";
-
- result_authCondition = SASL::AuthFail;
- result_haveClientInit = false;
- result_mechlist.clear();
- result_plain.clear();
- result_plain.clear();
- result_plain.clear();
- result_ssf = 0;
- }
-
- void resetParams()
- {
- params.reset();
- secflags = 0;
- ssf_min = 0;
- ssf_max = 0;
- ext_authid = "";
- ext_ssf = 0;
- }
-
- bool setsecprops()
- {
- sasl_security_properties_t secprops;
- secprops.min_ssf = ssf_min;
- secprops.max_ssf = ssf_max;
- secprops.maxbufsize = SASL_BUFSIZE;
- secprops.property_names = NULL;
- secprops.property_values = NULL;
- secprops.security_flags = secflags;
- int r = sasl_setprop(con, SASL_SEC_PROPS, &secprops);
- if(r != SASL_OK)
- return false;
-
- if(!ext_authid.isEmpty()) {
- const char *authid = ext_authid.toLatin1().data();
- sasl_ssf_t ssf = ext_ssf;
- r = sasl_setprop(con, SASL_SSF_EXTERNAL, &ssf);
- if(r != SASL_OK)
- return false;
- r = sasl_setprop(con, SASL_AUTH_EXTERNAL, &authid);
- if(r != SASL_OK)
- return false;
- }
-
- return true;
- }
-
- void setAuthCondition(int r)
- {
- //qDebug() << "authcondition: " << r;
- SASL::AuthCondition x;
- switch(r) {
- // common
- case SASL_NOMECH: x = SASL::NoMechanism; break;
- case SASL_BADPROT: x = SASL::BadProtocol; break;
-
- // client
- case SASL_BADSERV: x = SASL::BadServer; break;
-
- // server
- case SASL_BADAUTH: x = SASL::BadAuth; break;
- case SASL_NOAUTHZ: x = SASL::NoAuthzid; break;
- case SASL_TOOWEAK: x = SASL::TooWeak; break;
- case SASL_ENCRYPT: x = SASL::NeedEncrypt; break;
- case SASL_EXPIRED: x = SASL::Expired; break;
- case SASL_DISABLED: x = SASL::Disabled; break;
- case SASL_NOUSER: x = SASL::NoUser; break;
- case SASL_UNAVAIL: x = SASL::RemoteUnavailable; break;
-
- default: x = SASL::AuthFail; break;
- }
- result_authCondition = x;
- }
-
- void getssfparams()
- {
- const void *maybe_sff;
- if( SASL_OK == sasl_getprop( con, SASL_SSF, &maybe_sff ) )
- result_ssf = *(const int*)maybe_sff;
-
- const void *maybe_maxoutbuf;
- if (SASL_OK == sasl_getprop( con, SASL_MAXOUTBUF, &maybe_maxoutbuf ) )
- maxoutbuf = *(const int*)maybe_maxoutbuf;
- }
-
- static int scb_checkauth(sasl_conn_t *, void *context, const char *requested_user, unsigned, const char *auth_identity, unsigned, const char *, unsigned, struct propctx *)
- {
- saslContext *that = (saslContext *)context;
- that->sc_username = auth_identity; // yeah yeah, it looks
- that->sc_authzid = requested_user; // backwards, but it is right
- that->ca_flag = true;
- return SASL_OK;
- }
-
- void clientTryAgain()
- {
- result_haveClientInit = false;
-
- if(step == 0) {
- const char *clientout, *m;
- unsigned int clientoutlen;
-
- need = 0;
- QString list = result_mechlist.join(" ");
- int r;
- while(1) {
- if(need)
- params.extractHave(need);
- if(in_sendFirst)
- r = sasl_client_start(con, list.toLatin1().data(), &need, &clientout, &clientoutlen, &m);
- else
- r = sasl_client_start(con, list.toLatin1().data(), &need, NULL, NULL, &m);
- if(r != SASL_INTERACT)
- break;
-
- params.applyInteract(need);
- if(params.missingAny()) {
- out_mech = m;
- result_result = Params;
- return;
- }
- }
- if(r != SASL_OK && r != SASL_CONTINUE) {
- setAuthCondition(r);
- result_result = Error;
- return;
- }
-
- out_mech = m;
- if(in_sendFirst && clientout) {
- out_buf = makeByteArray(clientout, clientoutlen);
- result_haveClientInit = true;
- }
-
- ++step;
-
- if(r == SASL_OK) {
- getssfparams();
- result_result = Success;
- return;
- }
- result_result = Continue;
- return;
- }
- else {
- const char *clientout;
- unsigned int clientoutlen;
- int r;
- while(1) {
- if(need)
- params.extractHave(need);
- //printf("sasl_client_step(con, {%s}, %d, &need, &clientout, &clientoutlen);\n", in_buf.data(), in_buf.size());
- r = sasl_client_step(con, in_buf.data(), in_buf.size(), &need, &clientout, &clientoutlen);
- //printf("returned: %d\n", r);
- if(r != SASL_INTERACT)
- break;
-
- params.applyInteract(need);
- if(params.missingAny()) {
- result_result = Params;
- return;
- }
- }
- if(r != SASL_OK && r != SASL_CONTINUE) {
- setAuthCondition(r);
- result_result = Error;
- return;
- }
- out_buf = makeByteArray(clientout, clientoutlen);
- if(r == SASL_OK) {
- getssfparams();
- result_result = Success;
- return;
- }
- result_result = Continue;
- return;
- }
- }
-
- void serverTryAgain()
- {
- if(step == 0) {
- if(!ca_skip) {
- const char *clientin = 0;
- unsigned int clientinlen = 0;
- if(in_useClientInit) {
- clientin = in_clientInit.data();
- clientinlen = in_clientInit.size();
- }
- const char *serverout;
- unsigned int serveroutlen;
- ca_flag = false;
- int r = sasl_server_start(con, in_mech.toLatin1().data(), clientin, clientinlen, &serverout, &serveroutlen);
- if(r != SASL_OK && r != SASL_CONTINUE) {
- setAuthCondition(r);
- result_result = Error;
- return;
- }
- out_buf = makeByteArray(serverout, serveroutlen);
- last_r = r;
- if(ca_flag && !ca_done) {
- ca_done = true;
- ca_skip = true;
- result_result = AuthCheck;
- return;
- }
- }
- ca_skip = false;
- ++step;
-
- if(last_r == SASL_OK) {
- getssfparams();
- result_result = Success;
- return;
- }
- result_result = Continue;
- return;
- }
- else {
- if(!ca_skip) {
- const char *serverout;
- unsigned int serveroutlen;
- int r = sasl_server_step(con, in_buf.data(), in_buf.size(), &serverout, &serveroutlen);
- if(r != SASL_OK && r != SASL_CONTINUE) {
- setAuthCondition(r);
- result_result = Error;
- return;
- }
- if(r == SASL_OK)
- out_buf.resize(0);
- else
- out_buf = makeByteArray(serverout, serveroutlen);
- last_r = r;
- if(ca_flag && !ca_done) {
- ca_done = true;
- ca_skip = true;
- result_result = AuthCheck;
- return;
- }
- }
- ca_skip = false;
- if(last_r == SASL_OK) {
- getssfparams();
- result_result = Success;
- return;
- }
- result_result = Continue;
- return;
- }
- }
-
- bool sasl_endecode(const QByteArray &in, QByteArray *out, bool enc)
- {
- // no security
- if(result_ssf == 0) {
- *out = in;
- return true;
- }
-
- int at = 0;
- out->resize(0);
- while(1) {
- int size = in.size() - at;
- if(size == 0)
- break;
- if(size > maxoutbuf)
- size = maxoutbuf;
- const char *outbuf;
- unsigned len;
- int r;
- if(enc)
- r = sasl_encode(con, in.data() + at, size, &outbuf, &len);
- else
- r = sasl_decode(con, in.data() + at, size, &outbuf, &len);
- if(r != SASL_OK)
- return false;
- int oldsize = out->size();
- out->resize(oldsize + len);
- memcpy(out->data() + oldsize, outbuf, len);
- at += size;
- }
- return true;
- }
-
- void doResultsReady()
- {
- QMetaObject::invokeMethod(this, "resultsReady", Qt::QueuedConnection);
- }
+ void resetState()
+ {
+ if (con) {
+ sasl_dispose(&con);
+ con = 0;
+ }
+ need = 0;
+ if (callbacks) {
+ delete callbacks;
+ callbacks = 0;
+ }
+
+ localAddr = "";
+ remoteAddr = "";
+ maxoutbuf = 128;
+ sc_username = "";
+ sc_authzid = "";
+
+ result_authCondition = SASL::AuthFail;
+ result_haveClientInit = false;
+ result_mechlist.clear();
+ result_plain.clear();
+ result_plain.clear();
+ result_plain.clear();
+ result_ssf = 0;
+ }
+
+ void resetParams()
+ {
+ params.reset();
+ secflags = 0;
+ ssf_min = 0;
+ ssf_max = 0;
+ ext_authid = "";
+ ext_ssf = 0;
+ }
+
+ bool setsecprops()
+ {
+ sasl_security_properties_t secprops;
+ secprops.min_ssf = ssf_min;
+ secprops.max_ssf = ssf_max;
+ secprops.maxbufsize = SASL_BUFSIZE;
+ secprops.property_names = NULL;
+ secprops.property_values = NULL;
+ secprops.security_flags = secflags;
+ int r = sasl_setprop(con, SASL_SEC_PROPS, &secprops);
+ if (r != SASL_OK) {
+ return false;
+ }
+
+ if (!ext_authid.isEmpty()) {
+ const char *authid = ext_authid.toLatin1().data();
+ sasl_ssf_t ssf = ext_ssf;
+ r = sasl_setprop(con, SASL_SSF_EXTERNAL, &ssf);
+ if (r != SASL_OK) {
+ return false;
+ }
+ r = sasl_setprop(con, SASL_AUTH_EXTERNAL, &authid);
+ if (r != SASL_OK) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ void setAuthCondition(int r)
+ {
+ //qDebug() << "authcondition: " << r;
+ SASL::AuthCondition x;
+ switch (r) {
+ // common
+ case SASL_NOMECH: x = SASL::NoMechanism; break;
+ case SASL_BADPROT: x = SASL::BadProtocol; break;
+
+ // client
+ case SASL_BADSERV: x = SASL::BadServer; break;
+
+ // server
+ case SASL_BADAUTH: x = SASL::BadAuth; break;
+ case SASL_NOAUTHZ: x = SASL::NoAuthzid; break;
+ case SASL_TOOWEAK: x = SASL::TooWeak; break;
+ case SASL_ENCRYPT: x = SASL::NeedEncrypt; break;
+ case SASL_EXPIRED: x = SASL::Expired; break;
+ case SASL_DISABLED: x = SASL::Disabled; break;
+ case SASL_NOUSER: x = SASL::NoUser; break;
+ case SASL_UNAVAIL: x = SASL::RemoteUnavailable; break;
+
+ default: x = SASL::AuthFail; break;
+ }
+ result_authCondition = x;
+ }
+
+ void getssfparams()
+ {
+ const void *maybe_sff;
+ if (SASL_OK == sasl_getprop(con, SASL_SSF, &maybe_sff)) {
+ result_ssf = *(const int *)maybe_sff;
+ }
+
+ const void *maybe_maxoutbuf;
+ if (SASL_OK == sasl_getprop(con, SASL_MAXOUTBUF, &maybe_maxoutbuf)) {
+ maxoutbuf = *(const int *)maybe_maxoutbuf;
+ }
+ }
+
+ static int scb_checkauth(sasl_conn_t *, void *context, const char *requested_user, unsigned, const char *auth_identity, unsigned, const char *, unsigned, struct propctx *)
+ {
+ saslContext *that = (saslContext *)context;
+ that->sc_username = auth_identity; // yeah yeah, it looks
+ that->sc_authzid = requested_user; // backwards, but it is right
+ that->ca_flag = true;
+ return SASL_OK;
+ }
+
+ void clientTryAgain()
+ {
+ result_haveClientInit = false;
+
+ if (step == 0) {
+ const char *clientout, *m;
+ unsigned int clientoutlen;
+
+ need = 0;
+ QString list = result_mechlist.join(" ");
+ int r;
+ while (1) {
+ if (need) {
+ params.extractHave(need);
+ }
+ if (in_sendFirst) {
+ r = sasl_client_start(con, list.toLatin1().data(), &need, &clientout, &clientoutlen, &m);
+ } else {
+ r = sasl_client_start(con, list.toLatin1().data(), &need, NULL, NULL, &m);
+ }
+ if (r != SASL_INTERACT) {
+ break;
+ }
+
+ params.applyInteract(need);
+ if (params.missingAny()) {
+ out_mech = m;
+ result_result = Params;
+ return;
+ }
+ }
+ if (r != SASL_OK && r != SASL_CONTINUE) {
+ setAuthCondition(r);
+ result_result = Error;
+ return;
+ }
+
+ out_mech = m;
+ if (in_sendFirst && clientout) {
+ out_buf = makeByteArray(clientout, clientoutlen);
+ result_haveClientInit = true;
+ }
+
+ ++step;
+
+ if (r == SASL_OK) {
+ getssfparams();
+ result_result = Success;
+ return;
+ }
+ result_result = Continue;
+ return;
+ } else {
+ const char *clientout;
+ unsigned int clientoutlen;
+ int r;
+ while (1) {
+ if (need) {
+ params.extractHave(need);
+ }
+ //printf("sasl_client_step(con, {%s}, %d, &need, &clientout, &clientoutlen);\n", in_buf.data(), in_buf.size());
+ r = sasl_client_step(con, in_buf.data(), in_buf.size(), &need, &clientout, &clientoutlen);
+ //printf("returned: %d\n", r);
+ if (r != SASL_INTERACT) {
+ break;
+ }
+
+ params.applyInteract(need);
+ if (params.missingAny()) {
+ result_result = Params;
+ return;
+ }
+ }
+ if (r != SASL_OK && r != SASL_CONTINUE) {
+ setAuthCondition(r);
+ result_result = Error;
+ return;
+ }
+ out_buf = makeByteArray(clientout, clientoutlen);
+ if (r == SASL_OK) {
+ getssfparams();
+ result_result = Success;
+ return;
+ }
+ result_result = Continue;
+ return;
+ }
+ }
+
+ void serverTryAgain()
+ {
+ if (step == 0) {
+ if (!ca_skip) {
+ const char *clientin = 0;
+ unsigned int clientinlen = 0;
+ if (in_useClientInit) {
+ clientin = in_clientInit.data();
+ clientinlen = in_clientInit.size();
+ }
+ const char *serverout;
+ unsigned int serveroutlen;
+ ca_flag = false;
+ int r = sasl_server_start(con, in_mech.toLatin1().data(), clientin, clientinlen, &serverout, &serveroutlen);
+ if (r != SASL_OK && r != SASL_CONTINUE) {
+ setAuthCondition(r);
+ result_result = Error;
+ return;
+ }
+ out_buf = makeByteArray(serverout, serveroutlen);
+ last_r = r;
+ if (ca_flag && !ca_done) {
+ ca_done = true;
+ ca_skip = true;
+ result_result = AuthCheck;
+ return;
+ }
+ }
+ ca_skip = false;
+ ++step;
+
+ if (last_r == SASL_OK) {
+ getssfparams();
+ result_result = Success;
+ return;
+ }
+ result_result = Continue;
+ return;
+ } else {
+ if (!ca_skip) {
+ const char *serverout;
+ unsigned int serveroutlen;
+ int r = sasl_server_step(con, in_buf.data(), in_buf.size(), &serverout, &serveroutlen);
+ if (r != SASL_OK && r != SASL_CONTINUE) {
+ setAuthCondition(r);
+ result_result = Error;
+ return;
+ }
+ if (r == SASL_OK) {
+ out_buf.resize(0);
+ } else {
+ out_buf = makeByteArray(serverout, serveroutlen);
+ }
+ last_r = r;
+ if (ca_flag && !ca_done) {
+ ca_done = true;
+ ca_skip = true;
+ result_result = AuthCheck;
+ return;
+ }
+ }
+ ca_skip = false;
+ if (last_r == SASL_OK) {
+ getssfparams();
+ result_result = Success;
+ return;
+ }
+ result_result = Continue;
+ return;
+ }
+ }
+
+ bool sasl_endecode(const QByteArray &in, QByteArray *out, bool enc)
+ {
+ // no security
+ if (result_ssf == 0) {
+ *out = in;
+ return true;
+ }
+
+ int at = 0;
+ out->resize(0);
+ while (1) {
+ int size = in.size() - at;
+ if (size == 0) {
+ break;
+ }
+ if (size > maxoutbuf) {
+ size = maxoutbuf;
+ }
+ const char *outbuf;
+ unsigned len;
+ int r;
+ if (enc) {
+ r = sasl_encode(con, in.data() + at, size, &outbuf, &len);
+ } else {
+ r = sasl_decode(con, in.data() + at, size, &outbuf, &len);
+ }
+ if (r != SASL_OK) {
+ return false;
+ }
+ int oldsize = out->size();
+ out->resize(oldsize + len);
+ memcpy(out->data() + oldsize, outbuf, len);
+ at += size;
+ }
+ return true;
+ }
+
+ void doResultsReady()
+ {
+ QMetaObject::invokeMethod(this, "resultsReady", Qt::QueuedConnection);
+ }
public:
- saslContext(saslProvider *_g)
- : SASLContext(_g)
- {
- result_result = Success;
- g = _g;
- con = 0;
- callbacks = 0;
-
- reset();
- }
-
- ~saslContext()
- {
- reset();
- }
-
- virtual Provider::Context *clone() const
- {
- return 0;
- }
-
- virtual Result result() const
- {
- return result_result;
- }
-
- virtual void reset()
- {
- resetState();
- resetParams();
- }
-
- virtual void setup(const QString &_service, const QString &_host, const HostPort *local, const HostPort *remote, const QString &ext_id, int _ext_ssf)
- {
- service = _service;
- host = _host;
- localAddr = local ? addrString(*local) : "";
- remoteAddr = remote ? addrString(*remote) : "";
- ext_authid = ext_id;
- ext_ssf = _ext_ssf;
- }
-
- virtual int ssf() const
- {
- return result_ssf;
- }
-
- virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst)
- {
- resetState();
-
- in_sendFirst = allowClientSendFirst;
-
- if(!g->client_init) {
- sasl_client_init(NULL);
- g->client_init = true;
- }
-
- callbacks = new sasl_callback_t[5];
-
- callbacks[0].id = SASL_CB_GETREALM;
- callbacks[0].proc = 0;
- callbacks[0].context = 0;
-
- callbacks[1].id = SASL_CB_USER;
- callbacks[1].proc = 0;
- callbacks[1].context = 0;
-
- callbacks[2].id = SASL_CB_AUTHNAME;
- callbacks[2].proc = 0;
- callbacks[2].context = 0;
-
- callbacks[3].id = SASL_CB_PASS;
- callbacks[3].proc = 0;
- callbacks[3].context = 0;
-
- callbacks[4].id = SASL_CB_LIST_END;
- callbacks[4].proc = 0;
- callbacks[4].context = 0;
-
- result_result = Error;
-
- int r = sasl_client_new(service.toLatin1().data(), host.toLatin1().data(), localAddr.isEmpty() ? 0 : localAddr.toLatin1().data(), remoteAddr.isEmpty() ? 0 : remoteAddr.toLatin1().data(), callbacks, 0, &con);
- if(r != SASL_OK) {
- setAuthCondition(r);
- doResultsReady();
- return;
- }
-
- if(!setsecprops())
- {
- doResultsReady();
- return;
- }
-
- result_mechlist = mechlist;
- servermode = false;
- step = 0;
- result_result = Success;
- clientTryAgain();
- doResultsReady();
- return;
- }
-
- // TODO: make use of disableServerSendLast
- virtual void startServer(const QString &realm, bool disableServerSendLast)
- {
- Q_UNUSED(disableServerSendLast);
- resetState();
-
- g->appname = SASL_APP;
- if(!g->server_init) {
- sasl_server_init(NULL, QFile::encodeName(g->appname));
- g->server_init = true;
- }
-
- callbacks = new sasl_callback_t[2];
-
- callbacks[0].id = SASL_CB_PROXY_POLICY;
- callbacks[0].proc = (int(*)())scb_checkauth;
- callbacks[0].context = this;
-
- callbacks[1].id = SASL_CB_LIST_END;
- callbacks[1].proc = 0;
- callbacks[1].context = 0;
-
- result_result = Error;
-
- int r = sasl_server_new(service.toLatin1().data(), host.toLatin1().data(), !realm.isEmpty() ? realm.toLatin1().data() : 0, localAddr.isEmpty() ? 0 : localAddr.toLatin1().data(), remoteAddr.isEmpty() ? 0 : remoteAddr.toLatin1().data(), callbacks, 0, &con);
- if(r != SASL_OK) {
- setAuthCondition(r);
- doResultsReady();
- return;
- }
-
- if(!setsecprops())
- {
- doResultsReady();
- return;
- }
-
- const char *ml;
- r = sasl_listmech(con, 0, 0, " ", 0, &ml, 0, 0);
- if(r != SASL_OK)
- return;
- result_mechlist = QString::fromUtf8(ml).split(' ');
-
- servermode = true;
- step = 0;
- ca_done = false;
- ca_skip = false;
- result_result = Success;
- doResultsReady();
- return;
- }
-
- virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit)
- {
- in_mech = mech;
- if(clientInit) {
- in_useClientInit = true;
- in_clientInit = *clientInit;
- }
- else
- in_useClientInit = false;
- serverTryAgain();
- doResultsReady();
- }
-
- virtual SASL::Params clientParams() const
- {
- SASLParams::SParams sparams = params.missing();
- return SASL::Params(sparams.user, sparams.authzid, sparams.pass, sparams.realm);
- }
-
- virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm)
- {
- if(user)
- params.setUsername(*user);
- if(authzid)
- params.setAuthzid(*authzid);
- if(pass)
- params.setPassword(*pass);
- if(realm)
- params.setRealm(*realm);
- }
-
- virtual QString username() const
- {
- return sc_username;
- }
-
- virtual QString authzid() const
- {
- return sc_authzid;
- }
-
- virtual void nextStep(const QByteArray &from_net)
- {
- in_buf = from_net;
- tryAgain();
- }
-
- virtual void tryAgain()
- {
- if(servermode)
- serverTryAgain();
- else
- clientTryAgain();
- doResultsReady();
- }
-
- virtual QString mech() const
- {
- if (servermode)
- return in_mech;
- else
- return out_mech;
- }
-
- virtual QStringList mechlist() const
- {
- return result_mechlist;
- }
-
- virtual QStringList realmlist() const
- {
- // TODO
- return QStringList();
- }
-
- virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF)
- {
- int sf = 0;
- if( !(f & SASL::AllowPlain) )
- sf |= SASL_SEC_NOPLAINTEXT;
- // if( !(f & SASL::AllowActiveVulnerable) ) // TODO
- // sf |= SASL_SEC_NOACTIVE;
- // if( !(f & SASL::AllowDictVulnerable) ) // TODO
- // sf |= SASL_SEC_NODICTIONARY;
- if( !(f & SASL::AllowAnonymous) )
- sf |= SASL_SEC_NOANONYMOUS;
- if( f & SASL::RequireForwardSecrecy )
- sf |= SASL_SEC_FORWARD_SECRECY;
- if( f & SASL::RequirePassCredentials )
- sf |= SASL_SEC_PASS_CREDENTIALS;
- if( f & SASL::RequireMutualAuth )
- sf |= SASL_SEC_MUTUAL_AUTH;
-
- secflags = sf;
- ssf_min = minSSF;
- ssf_max = maxSSF;
- }
-
- virtual bool waitForResultsReady(int msecs)
- {
- // TODO: for now, all operations block anyway
- Q_UNUSED(msecs);
- return true;
- }
-
- virtual void update(const QByteArray &from_net, const QByteArray &from_app)
- {
- bool ok = true;
- if(!from_app.isEmpty())
- ok = sasl_endecode(from_app, &result_to_net, true);
- if(ok && !from_net.isEmpty())
- ok = sasl_endecode(from_net, &result_plain, false);
- result_result = ok ? Success : Error;
- result_encoded = from_app.size();
-
- //printf("update (from_net=%d, to_net=%d, from_app=%d, to_app=%d)\n", from_net.size(), result_to_net.size(), from_app.size(), result_plain.size());
-
- doResultsReady();
- }
-
- virtual bool haveClientInit() const
- {
- return result_haveClientInit;
- }
-
- virtual QByteArray stepData() const
- {
- return out_buf;
- }
-
- virtual QByteArray to_net()
- {
- QByteArray a = result_to_net;
- result_to_net.clear();
- return a;
- }
-
- virtual int encoded() const
- {
- return result_encoded;
- }
-
- virtual QByteArray to_app()
- {
- QByteArray a = result_plain;
- result_plain.clear();
- return a;
- }
-
- virtual SASL::AuthCondition authCondition() const
- {
- return result_authCondition;
- }
+ saslContext(saslProvider *_g)
+ : SASLContext(_g)
+ {
+ result_result = Success;
+ g = _g;
+ con = 0;
+ callbacks = 0;
+
+ reset();
+ }
+
+ ~saslContext()
+ {
+ reset();
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual Result result() const
+ {
+ return result_result;
+ }
+
+ virtual void reset()
+ {
+ resetState();
+ resetParams();
+ }
+
+ virtual void setup(const QString &_service, const QString &_host, const HostPort *local, const HostPort *remote, const QString &ext_id, int _ext_ssf)
+ {
+ service = _service;
+ host = _host;
+ localAddr = local ? addrString(*local) : "";
+ remoteAddr = remote ? addrString(*remote) : "";
+ ext_authid = ext_id;
+ ext_ssf = _ext_ssf;
+ }
+
+ virtual int ssf() const
+ {
+ return result_ssf;
+ }
+
+ virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst)
+ {
+ resetState();
+
+ in_sendFirst = allowClientSendFirst;
+
+ if (!g->client_init) {
+ sasl_client_init(NULL);
+ g->client_init = true;
+ }
+
+ callbacks = new sasl_callback_t[5];
+
+ callbacks[0].id = SASL_CB_GETREALM;
+ callbacks[0].proc = 0;
+ callbacks[0].context = 0;
+
+ callbacks[1].id = SASL_CB_USER;
+ callbacks[1].proc = 0;
+ callbacks[1].context = 0;
+
+ callbacks[2].id = SASL_CB_AUTHNAME;
+ callbacks[2].proc = 0;
+ callbacks[2].context = 0;
+
+ callbacks[3].id = SASL_CB_PASS;
+ callbacks[3].proc = 0;
+ callbacks[3].context = 0;
+
+ callbacks[4].id = SASL_CB_LIST_END;
+ callbacks[4].proc = 0;
+ callbacks[4].context = 0;
+
+ result_result = Error;
+
+ int r = sasl_client_new(service.toLatin1().data(), host.toLatin1().data(), localAddr.isEmpty() ? 0 : localAddr.toLatin1().data(), remoteAddr.isEmpty() ? 0 : remoteAddr.toLatin1().data(), callbacks, 0, &con);
+ if (r != SASL_OK) {
+ setAuthCondition(r);
+ doResultsReady();
+ return;
+ }
+
+ if (!setsecprops()) {
+ doResultsReady();
+ return;
+ }
+
+ result_mechlist = mechlist;
+ servermode = false;
+ step = 0;
+ result_result = Success;
+ clientTryAgain();
+ doResultsReady();
+ return;
+ }
+
+ // TODO: make use of disableServerSendLast
+ virtual void startServer(const QString &realm, bool disableServerSendLast)
+ {
+ Q_UNUSED(disableServerSendLast);
+ resetState();
+
+ g->appname = SASL_APP;
+ if (!g->server_init) {
+ sasl_server_init(NULL, QFile::encodeName(g->appname));
+ g->server_init = true;
+ }
+
+ callbacks = new sasl_callback_t[2];
+
+ callbacks[0].id = SASL_CB_PROXY_POLICY;
+ callbacks[0].proc = (int(*)())scb_checkauth;
+ callbacks[0].context = this;
+
+ callbacks[1].id = SASL_CB_LIST_END;
+ callbacks[1].proc = 0;
+ callbacks[1].context = 0;
+
+ result_result = Error;
+
+ int r = sasl_server_new(service.toLatin1().data(), host.toLatin1().data(), !realm.isEmpty() ? realm.toLatin1().data() : 0, localAddr.isEmpty() ? 0 : localAddr.toLatin1().data(), remoteAddr.isEmpty() ? 0 : remoteAddr.toLatin1().data(), callbacks, 0, &con);
+ if (r != SASL_OK) {
+ setAuthCondition(r);
+ doResultsReady();
+ return;
+ }
+
+ if (!setsecprops()) {
+ doResultsReady();
+ return;
+ }
+
+ const char *ml;
+ r = sasl_listmech(con, 0, 0, " ", 0, &ml, 0, 0);
+ if (r != SASL_OK) {
+ return;
+ }
+ result_mechlist = QString::fromUtf8(ml).split(' ');
+
+ servermode = true;
+ step = 0;
+ ca_done = false;
+ ca_skip = false;
+ result_result = Success;
+ doResultsReady();
+ return;
+ }
+
+ virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit)
+ {
+ in_mech = mech;
+ if (clientInit) {
+ in_useClientInit = true;
+ in_clientInit = *clientInit;
+ } else {
+ in_useClientInit = false;
+ }
+ serverTryAgain();
+ doResultsReady();
+ }
+
+ virtual SASL::Params clientParams() const
+ {
+ SASLParams::SParams sparams = params.missing();
+ return SASL::Params(sparams.user, sparams.authzid, sparams.pass, sparams.realm);
+ }
+
+ virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm)
+ {
+ if (user) {
+ params.setUsername(*user);
+ }
+ if (authzid) {
+ params.setAuthzid(*authzid);
+ }
+ if (pass) {
+ params.setPassword(*pass);
+ }
+ if (realm) {
+ params.setRealm(*realm);
+ }
+ }
+
+ virtual QString username() const
+ {
+ return sc_username;
+ }
+
+ virtual QString authzid() const
+ {
+ return sc_authzid;
+ }
+
+ virtual void nextStep(const QByteArray &from_net)
+ {
+ in_buf = from_net;
+ tryAgain();
+ }
+
+ virtual void tryAgain()
+ {
+ if (servermode) {
+ serverTryAgain();
+ } else {
+ clientTryAgain();
+ }
+ doResultsReady();
+ }
+
+ virtual QString mech() const
+ {
+ if (servermode) {
+ return in_mech;
+ } else {
+ return out_mech;
+ }
+ }
+
+ virtual QStringList mechlist() const
+ {
+ return result_mechlist;
+ }
+
+ virtual QStringList realmlist() const
+ {
+ // TODO
+ return QStringList();
+ }
+
+ virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF)
+ {
+ int sf = 0;
+ if (!(f & SASL::AllowPlain)) {
+ sf |= SASL_SEC_NOPLAINTEXT;
+ }
+ // if( !(f & SASL::AllowActiveVulnerable) ) // TODO
+ // sf |= SASL_SEC_NOACTIVE;
+ // if( !(f & SASL::AllowDictVulnerable) ) // TODO
+ // sf |= SASL_SEC_NODICTIONARY;
+ if (!(f & SASL::AllowAnonymous)) {
+ sf |= SASL_SEC_NOANONYMOUS;
+ }
+ if (f & SASL::RequireForwardSecrecy) {
+ sf |= SASL_SEC_FORWARD_SECRECY;
+ }
+ if (f & SASL::RequirePassCredentials) {
+ sf |= SASL_SEC_PASS_CREDENTIALS;
+ }
+ if (f & SASL::RequireMutualAuth) {
+ sf |= SASL_SEC_MUTUAL_AUTH;
+ }
+
+ secflags = sf;
+ ssf_min = minSSF;
+ ssf_max = maxSSF;
+ }
+
+ virtual bool waitForResultsReady(int msecs)
+ {
+ // TODO: for now, all operations block anyway
+ Q_UNUSED(msecs);
+ return true;
+ }
+
+ virtual void update(const QByteArray &from_net, const QByteArray &from_app)
+ {
+ bool ok = true;
+ if (!from_app.isEmpty()) {
+ ok = sasl_endecode(from_app, &result_to_net, true);
+ }
+ if (ok && !from_net.isEmpty()) {
+ ok = sasl_endecode(from_net, &result_plain, false);
+ }
+ result_result = ok ? Success : Error;
+ result_encoded = from_app.size();
+
+ //printf("update (from_net=%d, to_net=%d, from_app=%d, to_app=%d)\n", from_net.size(), result_to_net.size(), from_app.size(), result_plain.size());
+
+ doResultsReady();
+ }
+
+ virtual bool haveClientInit() const
+ {
+ return result_haveClientInit;
+ }
+
+ virtual QByteArray stepData() const
+ {
+ return out_buf;
+ }
+
+ virtual QByteArray to_net()
+ {
+ QByteArray a = result_to_net;
+ result_to_net.clear();
+ return a;
+ }
+
+ virtual int encoded() const
+ {
+ return result_encoded;
+ }
+
+ virtual QByteArray to_app()
+ {
+ QByteArray a = result_plain;
+ result_plain.clear();
+ return a;
+ }
+
+ virtual SASL::AuthCondition authCondition() const
+ {
+ return result_authCondition;
+ }
};
//----------------------------------------------------------------------------
// saslProvider
//----------------------------------------------------------------------------
saslProvider::saslProvider()
{
- client_init = false;
- server_init = false;
+ client_init = false;
+ server_init = false;
}
void saslProvider::init()
{
}
saslProvider::~saslProvider()
{
- if(client_init || server_init)
- sasl_done();
+ if (client_init || server_init) {
+ sasl_done();
+ }
}
int saslProvider::qcaVersion() const
{
- return QCA_VERSION;
+ return QCA_VERSION;
}
QString saslProvider::name() const
{
- return "qca-cyrus-sasl";
+ return "qca-cyrus-sasl";
}
QString saslProvider::credit() const
{
- return QString(); // TODO
+ return QString(); // TODO
}
QStringList saslProvider::features() const
{
- QStringList list;
- list += "sasl";
+ QStringList list;
+ list += "sasl";
- return list;
+ return list;
}
Provider::Context *saslProvider::createContext(const QString &type)
{
- if ( type == "sasl" )
- return new saslContext( this );
+ if (type == "sasl") {
+ return new saslContext(this);
+ }
- return 0;
+ return 0;
}
} // namespace saslQCAPlugin
using namespace saslQCAPlugin;
//----------------------------------------------------------------------------
// saslPlugin
//----------------------------------------------------------------------------
class saslPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { return new saslProvider; }
+ virtual Provider *createProvider()
+ {
+ return new saslProvider;
+ }
};
#include "qca-cyrus-sasl.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_cyrus_sasl, saslPlugin)
#endif
diff --git a/plugins/qca-gcrypt/pkcs5.c b/plugins/qca-gcrypt/pkcs5.c
index 8d415bcd..14749839 100644
--- a/plugins/qca-gcrypt/pkcs5.c
+++ b/plugins/qca-gcrypt/pkcs5.c
@@ -1,197 +1,199 @@
/* pkcs5.c Partial Password-Based Cryptography (PKCS#5) implementation
* Copyright (C) 2002 Free Software Foundation, Inc.
*
* This file is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This file is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include "gcrypt.h"
/*
* 5.2 PBKDF2
*
* PBKDF2 applies a pseudorandom function (see Appendix B.1 for an
* example) to derive keys. The length of the derived key is essentially
* unbounded. (However, the maximum effective search space for the
* derived key may be limited by the structure of the underlying
* pseudorandom function. See Appendix B.1 for further discussion.)
* PBKDF2 is recommended for new applications.
*
* PBKDF2 (P, S, c, dkLen)
*
* Options: PRF underlying pseudorandom function (hLen
* denotes the length in octets of the
* pseudorandom function output)
*
* Input: P password, an octet string
* S salt, an octet string
* c iteration count, a positive integer
* dkLen intended length in octets of the derived
* key, a positive integer, at most
* (2^32 - 1) * hLen
*
* Output: DK derived key, a dkLen-octet string
*/
gcry_error_t
-gcry_pbkdf2 (int PRF, const char *P, size_t Plen, const char *S,
- size_t Slen, unsigned int c, unsigned int dkLen, char *DK)
+gcry_pbkdf2(int PRF, const char *P, size_t Plen, const char *S,
+ size_t Slen, unsigned int c, unsigned int dkLen, char *DK)
{
- gcry_md_hd_t prf;
- gcry_error_t rc;
- char *U;
- unsigned int u;
- unsigned int hLen;
- unsigned int l;
- unsigned int r;
- unsigned char *p;
- unsigned int i;
- unsigned int k;
-
- hLen = gcry_md_get_algo_dlen (PRF);
- if (hLen == 0)
- return GPG_ERR_UNSUPPORTED_ALGORITHM;
-
- if (c == 0)
- return GPG_ERR_INV_ARG;
-
- if (dkLen == 0)
- return GPG_ERR_TOO_SHORT;
-
- /*
- *
- * Steps:
- *
- * 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and
- * stop.
- */
-
- if (dkLen > 4294967295U)
- return GPG_ERR_TOO_LARGE;
-
- /*
- * 2. Let l be the number of hLen-octet blocks in the derived key,
- * rounding up, and let r be the number of octets in the last
- * block:
- *
- * l = CEIL (dkLen / hLen) ,
- * r = dkLen - (l - 1) * hLen .
- *
- * Here, CEIL (x) is the "ceiling" function, i.e. the smallest
- * integer greater than, or equal to, x.
- */
-
- l = dkLen / hLen;
- if (dkLen % hLen)
- l++;
- r = dkLen - (l - 1) * hLen;
-
- /*
- * 3. For each block of the derived key apply the function F defined
- * below to the password P, the salt S, the iteration count c, and
- * the block index to compute the block:
- *
- * T_1 = F (P, S, c, 1) ,
- * T_2 = F (P, S, c, 2) ,
- * ...
- * T_l = F (P, S, c, l) ,
- *
- * where the function F is defined as the exclusive-or sum of the
- * first c iterates of the underlying pseudorandom function PRF
- * applied to the password P and the concatenation of the salt S
- * and the block index i:
- *
- * F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
- *
- * where
- *
- * U_1 = PRF (P, S || INT (i)) ,
- * U_2 = PRF (P, U_1) ,
- * ...
- * U_c = PRF (P, U_{c-1}) .
- *
- * Here, INT (i) is a four-octet encoding of the integer i, most
- * significant octet first.
- *
- * 4. Concatenate the blocks and extract the first dkLen octets to
- * produce a derived key DK:
- *
- * DK = T_1 || T_2 || ... || T_l<0..r-1>
- *
- * 5. Output the derived key DK.
- *
- * Note. The construction of the function F follows a "belt-and-
- * suspenders" approach. The iterates U_i are computed recursively to
- * remove a degree of parallelism from an opponent; they are exclusive-
- * ored together to reduce concerns about the recursion degenerating
- * into a small set of values.
- *
- */
- rc = gcry_md_open (&prf, PRF, GCRY_MD_FLAG_HMAC | GCRY_MD_FLAG_SECURE);
- if (rc != GPG_ERR_NO_ERROR)
- return rc;
+ gcry_md_hd_t prf;
+ gcry_error_t rc;
+ char *U;
+ unsigned int u;
+ unsigned int hLen;
+ unsigned int l;
+ unsigned int r;
+ unsigned char *p;
+ unsigned int i;
+ unsigned int k;
+
+ hLen = gcry_md_get_algo_dlen(PRF);
+ if (hLen == 0) {
+ return GPG_ERR_UNSUPPORTED_ALGORITHM;
+ }
- U = (char*)gcry_malloc(hLen);
- if (!U)
- {
- rc = GPG_ERR_ENOMEM;
- goto done;
+ if (c == 0) {
+ return GPG_ERR_INV_ARG;
}
- for (i = 1; i <= l; i++)
- {
- memset(DK + (i - 1) * hLen, 0, i == l ? r : hLen);
-
- for (u = 1; u <= c; u++)
- {
- gcry_md_reset (prf);
-
- rc = gcry_md_setkey (prf, P, Plen);
- if (rc != GPG_ERR_NO_ERROR) {
- goto done;
- }
- if (u == 1)
- {
- char tmp[4];
- gcry_md_write (prf, S, Slen);
- tmp[0] = (i & 0xff000000) >> 24;
- tmp[1] = (i & 0x00ff0000) >> 16;
- tmp[2] = (i & 0x0000ff00) >> 8;
- tmp[3] = (i & 0x000000ff) >> 0;
- gcry_md_write (prf, tmp, 4);
- }
- else
- gcry_md_write (prf, U, hLen);
-
- p = gcry_md_read (prf, PRF);
- if (p == NULL)
- {
- rc = GPG_ERR_CONFIGURATION;
- goto done;
- }
-
- memcpy (U, p, hLen);
- for (k = 0; k < (i == l ? r : hLen); k++)
- DK[(i - 1) * hLen + k] ^= U[k];
- }
+ if (dkLen == 0) {
+ return GPG_ERR_TOO_SHORT;
}
- rc = GPG_ERR_NO_ERROR;
- done:
- gcry_md_close (prf);
- gcry_free(U);
- return rc;
+ /*
+ *
+ * Steps:
+ *
+ * 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and
+ * stop.
+ */
+
+ if (dkLen > 4294967295U) {
+ return GPG_ERR_TOO_LARGE;
+ }
+
+ /*
+ * 2. Let l be the number of hLen-octet blocks in the derived key,
+ * rounding up, and let r be the number of octets in the last
+ * block:
+ *
+ * l = CEIL (dkLen / hLen) ,
+ * r = dkLen - (l - 1) * hLen .
+ *
+ * Here, CEIL (x) is the "ceiling" function, i.e. the smallest
+ * integer greater than, or equal to, x.
+ */
+
+ l = dkLen / hLen;
+ if (dkLen % hLen) {
+ l++;
+ }
+ r = dkLen - (l - 1) * hLen;
+
+ /*
+ * 3. For each block of the derived key apply the function F defined
+ * below to the password P, the salt S, the iteration count c, and
+ * the block index to compute the block:
+ *
+ * T_1 = F (P, S, c, 1) ,
+ * T_2 = F (P, S, c, 2) ,
+ * ...
+ * T_l = F (P, S, c, l) ,
+ *
+ * where the function F is defined as the exclusive-or sum of the
+ * first c iterates of the underlying pseudorandom function PRF
+ * applied to the password P and the concatenation of the salt S
+ * and the block index i:
+ *
+ * F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
+ *
+ * where
+ *
+ * U_1 = PRF (P, S || INT (i)) ,
+ * U_2 = PRF (P, U_1) ,
+ * ...
+ * U_c = PRF (P, U_{c-1}) .
+ *
+ * Here, INT (i) is a four-octet encoding of the integer i, most
+ * significant octet first.
+ *
+ * 4. Concatenate the blocks and extract the first dkLen octets to
+ * produce a derived key DK:
+ *
+ * DK = T_1 || T_2 || ... || T_l<0..r-1>
+ *
+ * 5. Output the derived key DK.
+ *
+ * Note. The construction of the function F follows a "belt-and-
+ * suspenders" approach. The iterates U_i are computed recursively to
+ * remove a degree of parallelism from an opponent; they are exclusive-
+ * ored together to reduce concerns about the recursion degenerating
+ * into a small set of values.
+ *
+ */
+ rc = gcry_md_open(&prf, PRF, GCRY_MD_FLAG_HMAC | GCRY_MD_FLAG_SECURE);
+ if (rc != GPG_ERR_NO_ERROR) {
+ return rc;
+ }
+
+ U = (char *)gcry_malloc(hLen);
+ if (!U) {
+ rc = GPG_ERR_ENOMEM;
+ goto done;
+ }
+
+ for (i = 1; i <= l; i++) {
+ memset(DK + (i - 1) * hLen, 0, i == l ? r : hLen);
+
+ for (u = 1; u <= c; u++) {
+ gcry_md_reset(prf);
+
+ rc = gcry_md_setkey(prf, P, Plen);
+ if (rc != GPG_ERR_NO_ERROR) {
+ goto done;
+ }
+ if (u == 1) {
+ char tmp[4];
+ gcry_md_write(prf, S, Slen);
+ tmp[0] = (i & 0xff000000) >> 24;
+ tmp[1] = (i & 0x00ff0000) >> 16;
+ tmp[2] = (i & 0x0000ff00) >> 8;
+ tmp[3] = (i & 0x000000ff) >> 0;
+ gcry_md_write(prf, tmp, 4);
+ } else {
+ gcry_md_write(prf, U, hLen);
+ }
+
+ p = gcry_md_read(prf, PRF);
+ if (p == NULL) {
+ rc = GPG_ERR_CONFIGURATION;
+ goto done;
+ }
+
+ memcpy(U, p, hLen);
+ for (k = 0; k < (i == l ? r : hLen); k++) {
+ DK[(i - 1) * hLen + k] ^= U[k];
+ }
+ }
+ }
+
+ rc = GPG_ERR_NO_ERROR;
+done:
+ gcry_md_close(prf);
+ gcry_free(U);
+ return rc;
}
diff --git a/plugins/qca-gcrypt/qca-gcrypt.cpp b/plugins/qca-gcrypt/qca-gcrypt.cpp
index 780fcdde..54cd83db 100644
--- a/plugins/qca-gcrypt/qca-gcrypt.cpp
+++ b/plugins/qca-gcrypt/qca-gcrypt.cpp
@@ -1,699 +1,702 @@
/*
* Copyright (C) 2004 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <QtCore/qplugin.h>
#include <QTime>
#include <qstringlist.h>
#include <gcrypt.h>
#include <iostream>
-namespace gcryptQCAPlugin {
+namespace gcryptQCAPlugin
+{
#include "pkcs5.c"
-void check_error( const QString &label, gcry_error_t err )
+void check_error(const QString &label, gcry_error_t err)
{
// we ignore the case where it is not an error, and
// we also don't flag weak keys.
- if ( ( GPG_ERR_NO_ERROR != err ) && ( GPG_ERR_WEAK_KEY != gpg_err_code(err) ) ) {
- std::cout << "Failure (" << qPrintable(label) << "): ";
- std::cout << gcry_strsource(err) << "/";
- std::cout << gcry_strerror(err) << std::endl;
+ if ((GPG_ERR_NO_ERROR != err) && (GPG_ERR_WEAK_KEY != gpg_err_code(err))) {
+ std::cout << "Failure (" << qPrintable(label) << "): ";
+ std::cout << gcry_strsource(err) << "/";
+ std::cout << gcry_strerror(err) << std::endl;
}
}
class gcryHashContext : public QCA::HashContext
{
public:
gcryHashContext(int hashAlgorithm, QCA::Provider *p, const QString &type) : QCA::HashContext(p, type)
{
- m_hashAlgorithm = hashAlgorithm;
- err = gcry_md_open( &context, m_hashAlgorithm, 0 );
- if ( GPG_ERR_NO_ERROR != err ) {
- std::cout << "Failure: " ;
- std::cout << gcry_strsource(err) << "/";
- std::cout << gcry_strerror(err) << std::endl;
- }
+ m_hashAlgorithm = hashAlgorithm;
+ err = gcry_md_open(&context, m_hashAlgorithm, 0);
+ if (GPG_ERR_NO_ERROR != err) {
+ std::cout << "Failure: " ;
+ std::cout << gcry_strsource(err) << "/";
+ std::cout << gcry_strerror(err) << std::endl;
+ }
}
~gcryHashContext()
{
- gcry_md_close( context );
+ gcry_md_close(context);
}
Context *clone() const
{
- return new gcryHashContext(*this);
+ return new gcryHashContext(*this);
}
void clear()
{
- gcry_md_reset( context );
+ gcry_md_reset(context);
}
void update(const QCA::MemoryRegion &a)
{
- gcry_md_write( context, a.data(), a.size() );
+ gcry_md_write(context, a.data(), a.size());
}
QCA::MemoryRegion final()
{
- unsigned char *md;
- QCA::SecureArray a( gcry_md_get_algo_dlen( m_hashAlgorithm ) );
- md = gcry_md_read( context, m_hashAlgorithm );
- memcpy( a.data(), md, a.size() );
- return a;
+ unsigned char *md;
+ QCA::SecureArray a(gcry_md_get_algo_dlen(m_hashAlgorithm));
+ md = gcry_md_read(context, m_hashAlgorithm);
+ memcpy(a.data(), md, a.size());
+ return a;
}
protected:
gcry_md_hd_t context;
gcry_error_t err;
int m_hashAlgorithm;
};
class gcryHMACContext : public QCA::MACContext
{
public:
gcryHMACContext(int hashAlgorithm, QCA::Provider *p, const QString &type) : QCA::MACContext(p, type)
{
m_hashAlgorithm = hashAlgorithm;
- err = gcry_md_open( &context, m_hashAlgorithm, GCRY_MD_FLAG_HMAC );
- if ( GPG_ERR_NO_ERROR != err ) {
+ err = gcry_md_open(&context, m_hashAlgorithm, GCRY_MD_FLAG_HMAC);
+ if (GPG_ERR_NO_ERROR != err) {
std::cout << "Failure: " ;
std::cout << gcry_strsource(err) << "/";
std::cout << gcry_strerror(err) << std::endl;
}
}
~gcryHMACContext()
{
- gcry_md_close( context );
+ gcry_md_close(context);
}
void setup(const QCA::SymmetricKey &key)
{
- gcry_md_setkey( context, key.data(), key.size() );
+ gcry_md_setkey(context, key.data(), key.size());
}
Context *clone() const
{
return new gcryHMACContext(*this);
}
void clear()
{
- gcry_md_reset( context );
+ gcry_md_reset(context);
}
QCA::KeyLength keyLength() const
{
return anyKeyLength();
}
void update(const QCA::MemoryRegion &a)
{
- gcry_md_write( context, a.data(), a.size() );
+ gcry_md_write(context, a.data(), a.size());
}
- void final( QCA::MemoryRegion *out)
+ void final(QCA::MemoryRegion *out)
{
- QCA::SecureArray sa( gcry_md_get_algo_dlen( m_hashAlgorithm ), 0 );
+ QCA::SecureArray sa(gcry_md_get_algo_dlen(m_hashAlgorithm), 0);
unsigned char *md;
- md = gcry_md_read( context, m_hashAlgorithm );
- memcpy( sa.data(), md, sa.size() );
+ md = gcry_md_read(context, m_hashAlgorithm);
+ memcpy(sa.data(), md, sa.size());
*out = sa;
}
protected:
gcry_md_hd_t context;
gcry_error_t err;
int m_hashAlgorithm;
};
-
class gcryCipherContext : public QCA::CipherContext
{
public:
gcryCipherContext(int algorithm, int mode, bool pad, QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type)
{
- m_cryptoAlgorithm = algorithm;
- m_mode = mode;
- m_pad = pad;
+ m_cryptoAlgorithm = algorithm;
+ m_mode = mode;
+ m_pad = pad;
}
void setup(QCA::Direction dir,
- const QCA::SymmetricKey &key,
- const QCA::InitializationVector &iv,
- const QCA::AuthTag &tag)
- {
- Q_UNUSED(tag);
- m_direction = dir;
- err = gcry_cipher_open( &context, m_cryptoAlgorithm, m_mode, 0 );
- check_error( "gcry_cipher_open", err );
- if ( ( GCRY_CIPHER_3DES == m_cryptoAlgorithm ) && (key.size() == 16) ) {
- // this is triple DES with two keys, and gcrypt wants three
- QCA::SymmetricKey keyCopy(key);
+ const QCA::SymmetricKey &key,
+ const QCA::InitializationVector &iv,
+ const QCA::AuthTag &tag)
+ {
+ Q_UNUSED(tag);
+ m_direction = dir;
+ err = gcry_cipher_open(&context, m_cryptoAlgorithm, m_mode, 0);
+ check_error("gcry_cipher_open", err);
+ if ((GCRY_CIPHER_3DES == m_cryptoAlgorithm) && (key.size() == 16)) {
+ // this is triple DES with two keys, and gcrypt wants three
+ QCA::SymmetricKey keyCopy(key);
QCA::SecureArray thirdKey(key);
- thirdKey.resize(8);
- keyCopy += thirdKey;
- err = gcry_cipher_setkey( context, keyCopy.data(), keyCopy.size() );
- } else {
- err = gcry_cipher_setkey( context, key.data(), key.size() );
- }
- check_error( "gcry_cipher_setkey", err );
- err = gcry_cipher_setiv( context, iv.data(), iv.size() );
- check_error( "gcry_cipher_setiv", err );
+ thirdKey.resize(8);
+ keyCopy += thirdKey;
+ err = gcry_cipher_setkey(context, keyCopy.data(), keyCopy.size());
+ } else {
+ err = gcry_cipher_setkey(context, key.data(), key.size());
+ }
+ check_error("gcry_cipher_setkey", err);
+ err = gcry_cipher_setiv(context, iv.data(), iv.size());
+ check_error("gcry_cipher_setiv", err);
}
Context *clone() const
{
- return new gcryCipherContext( *this );
+ return new gcryCipherContext(*this);
}
int blockSize() const
{
- unsigned int blockSize;
- gcry_cipher_algo_info( m_cryptoAlgorithm, GCRYCTL_GET_BLKLEN, 0, (size_t*)&blockSize );
- return blockSize;
+ unsigned int blockSize;
+ gcry_cipher_algo_info(m_cryptoAlgorithm, GCRYCTL_GET_BLKLEN, 0, (size_t *)&blockSize);
+ return blockSize;
}
QCA::AuthTag tag() const
{
- // For future implementation
- return QCA::AuthTag();
+ // For future implementation
+ return QCA::AuthTag();
}
bool update(const QCA::SecureArray &in, QCA::SecureArray *out)
{
- QCA::SecureArray result( in.size() );
- if (QCA::Encode == m_direction) {
- err = gcry_cipher_encrypt( context, (unsigned char*)result.data(), result.size(), (unsigned char*)in.data(), in.size() );
- } else {
- err = gcry_cipher_decrypt( context, (unsigned char*)result.data(), result.size(), (unsigned char*)in.data(), in.size() );
- }
- check_error( "update cipher encrypt/decrypt", err );
- result.resize( in.size() );
- *out = result;
- return true;
+ QCA::SecureArray result(in.size());
+ if (QCA::Encode == m_direction) {
+ err = gcry_cipher_encrypt(context, (unsigned char *)result.data(), result.size(), (unsigned char *)in.data(), in.size());
+ } else {
+ err = gcry_cipher_decrypt(context, (unsigned char *)result.data(), result.size(), (unsigned char *)in.data(), in.size());
+ }
+ check_error("update cipher encrypt/decrypt", err);
+ result.resize(in.size());
+ *out = result;
+ return true;
}
bool final(QCA::SecureArray *out)
{
QCA::SecureArray result;
- if (m_pad) {
- result.resize( blockSize() );
- if (QCA::Encode == m_direction) {
- err = gcry_cipher_encrypt( context, (unsigned char*)result.data(), result.size(), NULL, 0 );
- } else {
- err = gcry_cipher_decrypt( context, (unsigned char*)result.data(), result.size(), NULL, 0 );
- }
- check_error( "final cipher encrypt/decrypt", err );
- } else {
- // just return null
- }
- *out = result;
- return true;
+ if (m_pad) {
+ result.resize(blockSize());
+ if (QCA::Encode == m_direction) {
+ err = gcry_cipher_encrypt(context, (unsigned char *)result.data(), result.size(), NULL, 0);
+ } else {
+ err = gcry_cipher_decrypt(context, (unsigned char *)result.data(), result.size(), NULL, 0);
+ }
+ check_error("final cipher encrypt/decrypt", err);
+ } else {
+ // just return null
+ }
+ *out = result;
+ return true;
}
QCA::KeyLength keyLength() const
{
- switch (m_cryptoAlgorithm)
- {
- case GCRY_CIPHER_DES:
- return QCA::KeyLength( 8, 8, 1);
- case GCRY_CIPHER_AES128:
- return QCA::KeyLength( 16, 16, 1);
- case GCRY_CIPHER_AES192:
- return QCA::KeyLength( 24, 24, 1);
- case GCRY_CIPHER_3DES:
- // we do two and three key versions
- return QCA::KeyLength( 16, 24, 8);
- case GCRY_CIPHER_AES256:
- return QCA::KeyLength( 32, 32, 1);
- case GCRY_CIPHER_BLOWFISH:
- // Don't know - TODO
- return QCA::KeyLength( 1, 32, 1);
- default:
- return QCA::KeyLength( 0, 1, 1);
- }
+ switch (m_cryptoAlgorithm) {
+ case GCRY_CIPHER_DES:
+ return QCA::KeyLength(8, 8, 1);
+ case GCRY_CIPHER_AES128:
+ return QCA::KeyLength(16, 16, 1);
+ case GCRY_CIPHER_AES192:
+ return QCA::KeyLength(24, 24, 1);
+ case GCRY_CIPHER_3DES:
+ // we do two and three key versions
+ return QCA::KeyLength(16, 24, 8);
+ case GCRY_CIPHER_AES256:
+ return QCA::KeyLength(32, 32, 1);
+ case GCRY_CIPHER_BLOWFISH:
+ // Don't know - TODO
+ return QCA::KeyLength(1, 32, 1);
+ default:
+ return QCA::KeyLength(0, 1, 1);
+ }
}
-
protected:
gcry_cipher_hd_t context;
gcry_error_t err;
int m_cryptoAlgorithm;
QCA::Direction m_direction;
int m_mode;
bool m_pad;
};
-
class pbkdf1Context : public QCA::KDFContext
{
public:
pbkdf1Context(int algorithm, QCA::Provider *p, const QString &type) : QCA::KDFContext(p, type)
{
- m_hashAlgorithm = algorithm;
- err = gcry_md_open( &context, m_hashAlgorithm, 0 );
- if ( GPG_ERR_NO_ERROR != err ) {
- std::cout << "Failure: " ;
- std::cout << gcry_strsource(err) << "/";
- std::cout << gcry_strerror(err) << std::endl;
- }
+ m_hashAlgorithm = algorithm;
+ err = gcry_md_open(&context, m_hashAlgorithm, 0);
+ if (GPG_ERR_NO_ERROR != err) {
+ std::cout << "Failure: " ;
+ std::cout << gcry_strsource(err) << "/";
+ std::cout << gcry_strerror(err) << std::endl;
+ }
}
~pbkdf1Context()
{
- gcry_md_close( context );
+ gcry_md_close(context);
}
Context *clone() const
{
- return new pbkdf1Context( *this );
+ return new pbkdf1Context(*this);
}
QCA::SymmetricKey makeKey(const QCA::SecureArray &secret, const QCA::InitializationVector &salt,
- unsigned int keyLength, unsigned int iterationCount)
- {
- /* from RFC2898:
- Steps:
-
- 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
- "derived key too long" and stop.
- */
- if ( keyLength > gcry_md_get_algo_dlen(m_hashAlgorithm) ) {
- std::cout << "derived key too long" << std::endl;
- return QCA::SymmetricKey();
- }
-
- /*
- 2. Apply the underlying hash function Hash for c iterations to the
- concatenation of the password P and the salt S, then extract
- the first dkLen octets to produce a derived key DK:
-
- T_1 = Hash (P || S) ,
- T_2 = Hash (T_1) ,
- ...
- T_c = Hash (T_{c-1}) ,
- DK = Tc<0..dkLen-1>
- */
- // calculate T_1
- gcry_md_write( context, secret.data(), secret.size() );
- gcry_md_write( context, salt.data(), salt.size() );
- unsigned char *md;
- md = gcry_md_read( context, m_hashAlgorithm );
- QCA::SecureArray a( gcry_md_get_algo_dlen( m_hashAlgorithm ) );
- memcpy( a.data(), md, a.size() );
-
- // calculate T_2 up to T_c
- for ( unsigned int i = 2; i <= iterationCount; ++i ) {
- gcry_md_reset( context );
- gcry_md_write( context, a.data(), a.size() );
- md = gcry_md_read( context, m_hashAlgorithm );
- memcpy( a.data(), md, a.size() );
- }
-
- // shrink a to become DK, of the required length
- a.resize(keyLength);
-
- /*
- 3. Output the derived key DK.
- */
- return a;
- }
-
- QCA::SymmetricKey makeKey(const QCA::SecureArray &secret,
- const QCA::InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount)
- {
- Q_ASSERT(iterationCount != NULL);
- QTime timer;
-
- /*
- from RFC2898:
- Steps:
-
- 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
- "derived key too long" and stop.
- */
- if ( keyLength > gcry_md_get_algo_dlen(m_hashAlgorithm) ) {
- std::cout << "derived key too long" << std::endl;
- return QCA::SymmetricKey();
- }
-
- /*
- 2. Apply the underlying hash function Hash for M milliseconds
- to the concatenation of the password P and the salt S, incrementing c,
- then extract the first dkLen octets to produce a derived key DK:
-
- time from 0 to M
- T_1 = Hash (P || S) ,
- T_2 = Hash (T_1) ,
- ...
- T_c = Hash (T_{c-1}) ,
- when time = 0: stop,
- DK = Tc<0..dkLen-1>
- */
- // calculate T_1
- gcry_md_write( context, secret.data(), secret.size() );
- gcry_md_write( context, salt.data(), salt.size() );
- unsigned char *md;
- md = gcry_md_read( context, m_hashAlgorithm );
- QCA::SecureArray a( gcry_md_get_algo_dlen( m_hashAlgorithm ) );
- memcpy( a.data(), md, a.size() );
-
- // calculate T_2 up to T_c
- *iterationCount = 2 - 1; // <- Have to remove 1, unless it computes one
- timer.start(); // ^ time more than the base function
- // ^ with the same iterationCount
- while (timer.elapsed() < msecInterval) {
- gcry_md_reset( context );
- gcry_md_write( context, a.data(), a.size() );
- md = gcry_md_read( context, m_hashAlgorithm );
- memcpy( a.data(), md, a.size() );
- ++(*iterationCount);
- }
-
- // shrink a to become DK, of the required length
- a.resize(keyLength);
-
- /*
- 3. Output the derived key DK.
- */
- return a;
- }
+ unsigned int keyLength, unsigned int iterationCount)
+ {
+ /* from RFC2898:
+ Steps:
+
+ 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
+ "derived key too long" and stop.
+ */
+ if (keyLength > gcry_md_get_algo_dlen(m_hashAlgorithm)) {
+ std::cout << "derived key too long" << std::endl;
+ return QCA::SymmetricKey();
+ }
+
+ /*
+ 2. Apply the underlying hash function Hash for c iterations to the
+ concatenation of the password P and the salt S, then extract
+ the first dkLen octets to produce a derived key DK:
+
+ T_1 = Hash (P || S) ,
+ T_2 = Hash (T_1) ,
+ ...
+ T_c = Hash (T_{c-1}) ,
+ DK = Tc<0..dkLen-1>
+ */
+ // calculate T_1
+ gcry_md_write(context, secret.data(), secret.size());
+ gcry_md_write(context, salt.data(), salt.size());
+ unsigned char *md;
+ md = gcry_md_read(context, m_hashAlgorithm);
+ QCA::SecureArray a(gcry_md_get_algo_dlen(m_hashAlgorithm));
+ memcpy(a.data(), md, a.size());
+
+ // calculate T_2 up to T_c
+ for (unsigned int i = 2; i <= iterationCount; ++i) {
+ gcry_md_reset(context);
+ gcry_md_write(context, a.data(), a.size());
+ md = gcry_md_read(context, m_hashAlgorithm);
+ memcpy(a.data(), md, a.size());
+ }
+
+ // shrink a to become DK, of the required length
+ a.resize(keyLength);
+
+ /*
+ 3. Output the derived key DK.
+ */
+ return a;
+ }
+
+ QCA::SymmetricKey makeKey(const QCA::SecureArray &secret,
+ const QCA::InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount)
+ {
+ Q_ASSERT(iterationCount != NULL);
+ QTime timer;
+
+ /*
+ from RFC2898:
+ Steps:
+
+ 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
+ "derived key too long" and stop.
+ */
+ if (keyLength > gcry_md_get_algo_dlen(m_hashAlgorithm)) {
+ std::cout << "derived key too long" << std::endl;
+ return QCA::SymmetricKey();
+ }
+
+ /*
+ 2. Apply the underlying hash function Hash for M milliseconds
+ to the concatenation of the password P and the salt S, incrementing c,
+ then extract the first dkLen octets to produce a derived key DK:
+
+ time from 0 to M
+ T_1 = Hash (P || S) ,
+ T_2 = Hash (T_1) ,
+ ...
+ T_c = Hash (T_{c-1}) ,
+ when time = 0: stop,
+ DK = Tc<0..dkLen-1>
+ */
+ // calculate T_1
+ gcry_md_write(context, secret.data(), secret.size());
+ gcry_md_write(context, salt.data(), salt.size());
+ unsigned char *md;
+ md = gcry_md_read(context, m_hashAlgorithm);
+ QCA::SecureArray a(gcry_md_get_algo_dlen(m_hashAlgorithm));
+ memcpy(a.data(), md, a.size());
+
+ // calculate T_2 up to T_c
+ *iterationCount = 2 - 1; // <- Have to remove 1, unless it computes one
+ timer.start(); // ^ time more than the base function
+ // ^ with the same iterationCount
+ while (timer.elapsed() < msecInterval) {
+ gcry_md_reset(context);
+ gcry_md_write(context, a.data(), a.size());
+ md = gcry_md_read(context, m_hashAlgorithm);
+ memcpy(a.data(), md, a.size());
+ ++(*iterationCount);
+ }
+
+ // shrink a to become DK, of the required length
+ a.resize(keyLength);
+
+ /*
+ 3. Output the derived key DK.
+ */
+ return a;
+ }
protected:
gcry_md_hd_t context;
gcry_error_t err;
int m_hashAlgorithm;
};
-
class pbkdf2Context : public QCA::KDFContext
{
public:
pbkdf2Context(int algorithm, QCA::Provider *p, const QString &type) : QCA::KDFContext(p, type)
{
- m_algorithm = algorithm;
+ m_algorithm = algorithm;
}
Context *clone() const
{
- return new pbkdf2Context( *this );
+ return new pbkdf2Context(*this);
}
QCA::SymmetricKey makeKey(const QCA::SecureArray &secret, const QCA::InitializationVector &salt,
- unsigned int keyLength, unsigned int iterationCount)
- {
- QCA::SymmetricKey result(keyLength);
- gcry_error_t retval = gcry_pbkdf2(m_algorithm, secret.data(), secret.size(),
- salt.data(), salt.size(),
- iterationCount, keyLength, result.data());
- if (retval == GPG_ERR_NO_ERROR) {
- return result;
- } else {
- // std::cout << "got: " << retval << std::endl;
- return QCA::SymmetricKey();
- }
- }
-
- QCA::SymmetricKey makeKey(const QCA::SecureArray &secret,
- const QCA::InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount)
- {
- Q_ASSERT(iterationCount != NULL);
- QCA::SymmetricKey result(keyLength);
- QTime timer;
-
- *iterationCount = 0;
- timer.start();
-
- while (timer.elapsed() < msecInterval) {
- gcry_pbkdf2(m_algorithm,
- secret.data(),
- secret.size(),
- salt.data(),
- salt.size(),
- 1,
- keyLength,
- result.data());
- ++(*iterationCount);
- }
-
- return makeKey(secret, salt, keyLength, *iterationCount);
- }
+ unsigned int keyLength, unsigned int iterationCount)
+ {
+ QCA::SymmetricKey result(keyLength);
+ gcry_error_t retval = gcry_pbkdf2(m_algorithm, secret.data(), secret.size(),
+ salt.data(), salt.size(),
+ iterationCount, keyLength, result.data());
+ if (retval == GPG_ERR_NO_ERROR) {
+ return result;
+ } else {
+ // std::cout << "got: " << retval << std::endl;
+ return QCA::SymmetricKey();
+ }
+ }
+
+ QCA::SymmetricKey makeKey(const QCA::SecureArray &secret,
+ const QCA::InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount)
+ {
+ Q_ASSERT(iterationCount != NULL);
+ QCA::SymmetricKey result(keyLength);
+ QTime timer;
+
+ *iterationCount = 0;
+ timer.start();
+
+ while (timer.elapsed() < msecInterval) {
+ gcry_pbkdf2(m_algorithm,
+ secret.data(),
+ secret.size(),
+ salt.data(),
+ salt.size(),
+ 1,
+ keyLength,
+ result.data());
+ ++(*iterationCount);
+ }
+
+ return makeKey(secret, salt, keyLength, *iterationCount);
+ }
protected:
int m_algorithm;
};
}
extern "C"
{
-static void * qca_func_malloc(size_t n)
-{
- return qca_secure_alloc(n);
-}
+ static void *qca_func_malloc(size_t n)
+ {
+ return qca_secure_alloc(n);
+ }
-static void * qca_func_secure_malloc(size_t n)
-{
- return qca_secure_alloc(n);
-}
+ static void *qca_func_secure_malloc(size_t n)
+ {
+ return qca_secure_alloc(n);
+ }
-static void * qca_func_realloc(void *oldBlock, size_t newBlockSize)
-{
- return qca_secure_realloc(oldBlock, newBlockSize);
-}
+ static void *qca_func_realloc(void *oldBlock, size_t newBlockSize)
+ {
+ return qca_secure_realloc(oldBlock, newBlockSize);
+ }
-static void qca_func_free(void *mem)
-{
- qca_secure_free(mem);
-}
+ static void qca_func_free(void *mem)
+ {
+ qca_secure_free(mem);
+ }
-int qca_func_secure_check (const void *)
-{
- return (int)QCA::haveSecureMemory();
-}
+ int qca_func_secure_check(const void *)
+ {
+ return (int)QCA::haveSecureMemory();
+ }
} // extern "C"
class gcryptProvider : public QCA::Provider
{
public:
void init()
{
- if (!gcry_control (GCRYCTL_ANY_INITIALIZATION_P))
- { /* No other library has already initialized libgcrypt. */
-
- if (!gcry_check_version (GCRYPT_VERSION) )
- {
- std::cout << "libgcrypt is too old (need " << GCRYPT_VERSION;
- std::cout << ", have " << gcry_check_version(NULL) << ")" << std::endl;
- }
- gcry_set_allocation_handler (qca_func_malloc,
- qca_func_secure_malloc,
- qca_func_secure_check,
- qca_func_realloc,
- qca_func_free);
- gcry_control (GCRYCTL_INITIALIZATION_FINISHED);
- }
+ if (!gcry_control(GCRYCTL_ANY_INITIALIZATION_P)) {
+ /* No other library has already initialized libgcrypt. */
+
+ if (!gcry_check_version(GCRYPT_VERSION)) {
+ std::cout << "libgcrypt is too old (need " << GCRYPT_VERSION;
+ std::cout << ", have " << gcry_check_version(NULL) << ")" << std::endl;
+ }
+ gcry_set_allocation_handler(qca_func_malloc,
+ qca_func_secure_malloc,
+ qca_func_secure_check,
+ qca_func_realloc,
+ qca_func_free);
+ gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
+ }
}
int qcaVersion() const
{
return QCA_VERSION;
}
QString name() const
{
- return "qca-gcrypt";
+ return "qca-gcrypt";
}
QStringList features() const
{
- QStringList list;
- list += "sha1";
- list += "md4";
- list += "md5";
- list += "ripemd160";
+ QStringList list;
+ list += "sha1";
+ list += "md4";
+ list += "md5";
+ list += "ripemd160";
#ifdef GCRY_MD_SHA224
- list += "sha224";
+ list += "sha224";
#endif
- list += "sha256";
- list += "sha384";
- list += "sha512";
- list += "hmac(md5)";
- list += "hmac(sha1)";
+ list += "sha256";
+ list += "sha384";
+ list += "sha512";
+ list += "hmac(md5)";
+ list += "hmac(sha1)";
#ifdef GCRY_MD_SHA224
- list += "hmac(sha224)";
+ list += "hmac(sha224)";
#endif
- list += "hmac(sha256)";
- if ( ! ( NULL == gcry_check_version("1.3.0") ) ) {
- // 1.2 and earlier have broken implementation
- list += "hmac(sha384)";
- list += "hmac(sha512)";
- }
- list += "hmac(ripemd160)";
- list += "aes128-ecb";
- list += "aes128-cfb";
- list += "aes128-cbc";
- list += "aes192-ecb";
- list += "aes192-cfb";
- list += "aes192-cbc";
- list += "aes256-ecb";
- list += "aes256-cfb";
- list += "aes256-cbc";
- list += "blowfish-ecb";
- list += "blowfish-cbc";
- list += "blowfish-cfb";
- list += "tripledes-ecb";
- list += "des-ecb";
- list += "des-cbc";
- list += "des-cfb";
- if ( ! ( NULL == gcry_check_version("1.3.0") ) ) {
- // 1.2 branch and earlier doesn't support OFB mode
- list += "aes128-ofb";
- list += "aes192-ofb";
- list += "aes256-ofb";
- list += "des-ofb";
- list += "tripledes-ofb";
- list += "blowfish-ofb";
- }
- list += "pbkdf1(sha1)";
- list += "pbkdf2(sha1)";
- return list;
+ list += "hmac(sha256)";
+ if (!(NULL == gcry_check_version("1.3.0"))) {
+ // 1.2 and earlier have broken implementation
+ list += "hmac(sha384)";
+ list += "hmac(sha512)";
+ }
+ list += "hmac(ripemd160)";
+ list += "aes128-ecb";
+ list += "aes128-cfb";
+ list += "aes128-cbc";
+ list += "aes192-ecb";
+ list += "aes192-cfb";
+ list += "aes192-cbc";
+ list += "aes256-ecb";
+ list += "aes256-cfb";
+ list += "aes256-cbc";
+ list += "blowfish-ecb";
+ list += "blowfish-cbc";
+ list += "blowfish-cfb";
+ list += "tripledes-ecb";
+ list += "des-ecb";
+ list += "des-cbc";
+ list += "des-cfb";
+ if (!(NULL == gcry_check_version("1.3.0"))) {
+ // 1.2 branch and earlier doesn't support OFB mode
+ list += "aes128-ofb";
+ list += "aes192-ofb";
+ list += "aes256-ofb";
+ list += "des-ofb";
+ list += "tripledes-ofb";
+ list += "blowfish-ofb";
+ }
+ list += "pbkdf1(sha1)";
+ list += "pbkdf2(sha1)";
+ return list;
}
Context *createContext(const QString &type)
{
// std::cout << "type: " << qPrintable(type) << std::endl;
- if ( type == "sha1" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_SHA1, this, type );
- else if ( type == "md4" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_MD4, this, type );
- else if ( type == "md5" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_MD5, this, type );
- else if ( type == "ripemd160" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_RMD160, this, type );
+ if (type == "sha1") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_SHA1, this, type);
+ } else if (type == "md4") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_MD4, this, type);
+ } else if (type == "md5") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_MD5, this, type);
+ } else if (type == "ripemd160") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_RMD160, this, type);
+ }
#ifdef GCRY_MD_SHA224
- else if ( type == "sha224" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_SHA224, this, type );
+ else if (type == "sha224") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_SHA224, this, type);
+ }
#endif
- else if ( type == "sha256" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_SHA256, this, type );
- else if ( type == "sha384" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_SHA384, this, type );
- else if ( type == "sha512" )
- return new gcryptQCAPlugin::gcryHashContext( GCRY_MD_SHA512, this, type );
- else if ( type == "hmac(md5)" )
- return new gcryptQCAPlugin::gcryHMACContext( GCRY_MD_MD5, this, type );
- else if ( type == "hmac(sha1)" )
- return new gcryptQCAPlugin::gcryHMACContext( GCRY_MD_SHA1, this, type );
+ else if (type == "sha256") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_SHA256, this, type);
+ } else if (type == "sha384") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_SHA384, this, type);
+ } else if (type == "sha512") {
+ return new gcryptQCAPlugin::gcryHashContext(GCRY_MD_SHA512, this, type);
+ } else if (type == "hmac(md5)") {
+ return new gcryptQCAPlugin::gcryHMACContext(GCRY_MD_MD5, this, type);
+ } else if (type == "hmac(sha1)") {
+ return new gcryptQCAPlugin::gcryHMACContext(GCRY_MD_SHA1, this, type);
+ }
#ifdef GCRY_MD_SHA224
- else if ( type == "hmac(sha224)" )
- return new gcryptQCAPlugin::gcryHMACContext( GCRY_MD_SHA224, this, type );
+ else if (type == "hmac(sha224)") {
+ return new gcryptQCAPlugin::gcryHMACContext(GCRY_MD_SHA224, this, type);
+ }
#endif
- else if ( type == "hmac(sha256)" )
- return new gcryptQCAPlugin::gcryHMACContext( GCRY_MD_SHA256, this, type );
- else if ( type == "hmac(sha384)" )
- return new gcryptQCAPlugin::gcryHMACContext( GCRY_MD_SHA384, this, type );
- else if ( type == "hmac(sha512)" )
- return new gcryptQCAPlugin::gcryHMACContext( GCRY_MD_SHA512, this, type );
- else if ( type == "hmac(ripemd160)" )
- return new gcryptQCAPlugin::gcryHMACContext( GCRY_MD_RMD160, this, type );
- else if ( type == "aes128-ecb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, false, this, type );
- else if ( type == "aes128-cfb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CFB, false, this, type );
- else if ( type == "aes128-ofb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_OFB, false, this, type );
- else if ( type == "aes128-cbc" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, false, this, type );
- else if ( type == "aes192-ecb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_ECB, false, this, type );
- else if ( type == "aes192-cfb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB, false, this, type );
- else if ( type == "aes192-ofb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_OFB, false, this, type );
- else if ( type == "aes192-cbc" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC, false, this, type );
- else if ( type == "aes256-ecb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, false, this, type );
- else if ( type == "aes256-cfb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB, false, this, type );
- else if ( type == "aes256-ofb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, false, this, type );
- else if ( type == "aes256-cbc" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, false, this, type );
- else if ( type == "blowfish-ecb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_ECB, false, this, type );
- else if ( type == "blowfish-cbc" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC, false, this, type );
- else if ( type == "blowfish-cfb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CFB, false, this, type );
- else if ( type == "blowfish-ofb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_OFB, false, this, type );
- else if ( type == "tripledes-ecb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_ECB, false, this, type );
- else if ( type == "tripledes-ofb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_OFB, false, this, type );
- else if ( type == "des-ecb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, false, this, type );
- else if ( type == "des-cbc" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CBC, false, this, type );
- else if ( type == "des-cfb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CFB, false, this, type );
- else if ( type == "des-ofb" )
- return new gcryptQCAPlugin::gcryCipherContext( GCRY_CIPHER_DES, GCRY_CIPHER_MODE_OFB, false, this, type );
- else if ( type == "pbkdf1(sha1)" )
- return new gcryptQCAPlugin::pbkdf1Context( GCRY_MD_SHA1, this, type );
- else if ( type == "pbkdf2(sha1)" )
- return new gcryptQCAPlugin::pbkdf2Context( GCRY_MD_SHA1, this, type );
- else
- return 0;
+ else if (type == "hmac(sha256)") {
+ return new gcryptQCAPlugin::gcryHMACContext(GCRY_MD_SHA256, this, type);
+ } else if (type == "hmac(sha384)") {
+ return new gcryptQCAPlugin::gcryHMACContext(GCRY_MD_SHA384, this, type);
+ } else if (type == "hmac(sha512)") {
+ return new gcryptQCAPlugin::gcryHMACContext(GCRY_MD_SHA512, this, type);
+ } else if (type == "hmac(ripemd160)") {
+ return new gcryptQCAPlugin::gcryHMACContext(GCRY_MD_RMD160, this, type);
+ } else if (type == "aes128-ecb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB, false, this, type);
+ } else if (type == "aes128-cfb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CFB, false, this, type);
+ } else if (type == "aes128-ofb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_OFB, false, this, type);
+ } else if (type == "aes128-cbc") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC, false, this, type);
+ } else if (type == "aes192-ecb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_ECB, false, this, type);
+ } else if (type == "aes192-cfb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB, false, this, type);
+ } else if (type == "aes192-ofb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_OFB, false, this, type);
+ } else if (type == "aes192-cbc") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC, false, this, type);
+ } else if (type == "aes256-ecb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB, false, this, type);
+ } else if (type == "aes256-cfb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB, false, this, type);
+ } else if (type == "aes256-ofb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB, false, this, type);
+ } else if (type == "aes256-cbc") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC, false, this, type);
+ } else if (type == "blowfish-ecb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_ECB, false, this, type);
+ } else if (type == "blowfish-cbc") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC, false, this, type);
+ } else if (type == "blowfish-cfb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CFB, false, this, type);
+ } else if (type == "blowfish-ofb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_OFB, false, this, type);
+ } else if (type == "tripledes-ecb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_ECB, false, this, type);
+ } else if (type == "tripledes-ofb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_OFB, false, this, type);
+ } else if (type == "des-ecb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB, false, this, type);
+ } else if (type == "des-cbc") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CBC, false, this, type);
+ } else if (type == "des-cfb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CFB, false, this, type);
+ } else if (type == "des-ofb") {
+ return new gcryptQCAPlugin::gcryCipherContext(GCRY_CIPHER_DES, GCRY_CIPHER_MODE_OFB, false, this, type);
+ } else if (type == "pbkdf1(sha1)") {
+ return new gcryptQCAPlugin::pbkdf1Context(GCRY_MD_SHA1, this, type);
+ } else if (type == "pbkdf2(sha1)") {
+ return new gcryptQCAPlugin::pbkdf2Context(GCRY_MD_SHA1, this, type);
+ } else {
+ return 0;
+ }
}
};
class gcryptPlugin : public QObject, public QCAPlugin
{
Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
Q_INTERFACES(QCAPlugin)
- public:
- virtual QCA::Provider *createProvider() { return new gcryptProvider; }
+public:
+ virtual QCA::Provider *createProvider()
+ {
+ return new gcryptProvider;
+ }
};
#include "qca-gcrypt.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_gcrypt, gcryptPlugin)
#endif
diff --git a/plugins/qca-gnupg/gpgaction.cpp b/plugins/qca-gnupg/gpgaction.cpp
index 82d5ec7f..e1187e65 100644
--- a/plugins/qca-gnupg/gpgaction.cpp
+++ b/plugins/qca-gnupg/gpgaction.cpp
@@ -1,955 +1,894 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
// #define GPGOP_DEBUG
#include "gpgaction.h"
#ifdef GPGOP_DEBUG
#include "stdio.h"
#endif
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
static QDateTime getTimestamp(const QString &s)
{
- if(s.isEmpty())
- return QDateTime();
-
- if(s.contains('T'))
- {
- return QDateTime::fromString(s, Qt::ISODate);
- }
- else
- {
- QDateTime dt;
- dt.setTime_t(s.toInt());
- return dt;
- }
+ if (s.isEmpty()) {
+ return QDateTime();
+ }
+
+ if (s.contains('T')) {
+ return QDateTime::fromString(s, Qt::ISODate);
+ } else {
+ QDateTime dt;
+ dt.setTime_t(s.toInt());
+ return dt;
+ }
}
static QByteArray getCString(const QByteArray &a)
{
- QByteArray out;
-
- // convert the "backslash" C-string syntax
- for(int n = 0; n < a.size(); ++n)
- {
- if(a[n] == '\\' && n + 1 < a.size())
- {
- ++n;
- unsigned char c = (unsigned char)a[n];
- if(c == '\\')
- {
- out += '\\';
- }
- else if(c == 'x' && n + 2 < a.size())
- {
- ++n;
- QByteArray hex = a.mid(n, 2);
- ++n; // only skip one, loop will skip the next
-
- bool ok;
- uint val = hex.toInt(&ok, 16);
- if(ok)
- {
- out += (unsigned char)val;
- }
- else
- {
- out += "\\x";
- out += hex;
- }
- }
- }
- else
- {
- out += a[n];
- }
- }
-
- return out;
+ QByteArray out;
+
+ // convert the "backslash" C-string syntax
+ for (int n = 0; n < a.size(); ++n) {
+ if (a[n] == '\\' && n + 1 < a.size()) {
+ ++n;
+ unsigned char c = (unsigned char)a[n];
+ if (c == '\\') {
+ out += '\\';
+ } else if (c == 'x' && n + 2 < a.size()) {
+ ++n;
+ QByteArray hex = a.mid(n, 2);
+ ++n; // only skip one, loop will skip the next
+
+ bool ok;
+ uint val = hex.toInt(&ok, 16);
+ if (ok) {
+ out += (unsigned char)val;
+ } else {
+ out += "\\x";
+ out += hex;
+ }
+ }
+ } else {
+ out += a[n];
+ }
+ }
+
+ return out;
}
static bool stringToKeyList(const QString &outstr, GpgOp::KeyList *_keylist, QString *_keyring)
{
- GpgOp::KeyList keyList;
- QStringList lines = outstr.split('\n');
-
- if(lines.count() < 1)
- return false;
-
- QStringList::ConstIterator it = lines.constBegin();
-
- // first line is keyring file
- QString keyring = *(it++);
-
- // if the second line isn't a divider, we are dealing
- // with a new version of gnupg that doesn't give us
- // the keyring file on gpg --list-keys --with-colons
- if(it == lines.constEnd() || (*it).isEmpty() || (*it).at(0) != '-')
- {
- // first line wasn't the keyring name...
- keyring.clear();
- // ...so read the first line again
- it--;
- }
- else
- {
- // this was the divider line - skip it
- it++;
- }
-
- for(; it != lines.constEnd(); ++it)
- {
- QStringList f = (*it).split(':');
- if(f.count() < 1)
- continue;
- QString type = f[0];
-
- bool key = false; // key or not
- bool primary = false; // primary key or sub key
- // bool sec = false; // private key or not
-
- if(type == "pub")
- {
- key = true;
- primary = true;
- }
- else if(type == "sec")
- {
- key = true;
- primary = true;
- // sec = true;
- }
- else if(type == "sub")
- {
- key = true;
- }
- else if(type == "ssb")
- {
- key = true;
- // sec = true;
- }
-
- if(key)
- {
- if(primary)
- {
- keyList += GpgOp::Key();
-
- QString trust = f[1];
- if(trust == "f" || trust == "u")
- keyList.last().isTrusted = true;
- }
-
- int key_type = f[3].toInt();
- QString caps = f[11];
-
- GpgOp::KeyItem item;
- item.bits = f[2].toInt();
- if(key_type == 1)
- item.type = GpgOp::KeyItem::RSA;
- else if(key_type == 16)
- item.type = GpgOp::KeyItem::ElGamal;
- else if(key_type == 17)
- item.type = GpgOp::KeyItem::DSA;
- else
- item.type = GpgOp::KeyItem::Unknown;
- item.id = f[4];
- item.creationDate = getTimestamp(f[5]);
- item.expirationDate = getTimestamp(f[6]);
- if(caps.contains('e'))
- item.caps |= GpgOp::KeyItem::Encrypt;
- if(caps.contains('s'))
- item.caps |= GpgOp::KeyItem::Sign;
- if(caps.contains('c'))
- item.caps |= GpgOp::KeyItem::Certify;
- if(caps.contains('a'))
- item.caps |= GpgOp::KeyItem::Auth;
-
- keyList.last().keyItems += item;
- }
- else if(type == "uid")
- {
- QByteArray uid = getCString(f[9].toUtf8());
- keyList.last().userIds.append(QString::fromUtf8(uid));
- }
- else if(type == "fpr")
- {
- QString s = f[9];
- keyList.last().keyItems.last().fingerprint = s;
- }
- }
-
- if(_keylist)
- *_keylist = keyList;
- if(_keyring)
- *_keyring = keyring;
-
- return true;
+ GpgOp::KeyList keyList;
+ QStringList lines = outstr.split('\n');
+
+ if (lines.count() < 1) {
+ return false;
+ }
+
+ QStringList::ConstIterator it = lines.constBegin();
+
+ // first line is keyring file
+ QString keyring = *(it++);
+
+ // if the second line isn't a divider, we are dealing
+ // with a new version of gnupg that doesn't give us
+ // the keyring file on gpg --list-keys --with-colons
+ if (it == lines.constEnd() || (*it).isEmpty() || (*it).at(0) != '-') {
+ // first line wasn't the keyring name...
+ keyring.clear();
+ // ...so read the first line again
+ it--;
+ } else {
+ // this was the divider line - skip it
+ it++;
+ }
+
+ for (; it != lines.constEnd(); ++it) {
+ QStringList f = (*it).split(':');
+ if (f.count() < 1) {
+ continue;
+ }
+ QString type = f[0];
+
+ bool key = false; // key or not
+ bool primary = false; // primary key or sub key
+ // bool sec = false; // private key or not
+
+ if (type == "pub") {
+ key = true;
+ primary = true;
+ } else if (type == "sec") {
+ key = true;
+ primary = true;
+ // sec = true;
+ } else if (type == "sub") {
+ key = true;
+ } else if (type == "ssb") {
+ key = true;
+ // sec = true;
+ }
+
+ if (key) {
+ if (primary) {
+ keyList += GpgOp::Key();
+
+ QString trust = f[1];
+ if (trust == "f" || trust == "u") {
+ keyList.last().isTrusted = true;
+ }
+ }
+
+ int key_type = f[3].toInt();
+ QString caps = f[11];
+
+ GpgOp::KeyItem item;
+ item.bits = f[2].toInt();
+ if (key_type == 1) {
+ item.type = GpgOp::KeyItem::RSA;
+ } else if (key_type == 16) {
+ item.type = GpgOp::KeyItem::ElGamal;
+ } else if (key_type == 17) {
+ item.type = GpgOp::KeyItem::DSA;
+ } else {
+ item.type = GpgOp::KeyItem::Unknown;
+ }
+ item.id = f[4];
+ item.creationDate = getTimestamp(f[5]);
+ item.expirationDate = getTimestamp(f[6]);
+ if (caps.contains('e')) {
+ item.caps |= GpgOp::KeyItem::Encrypt;
+ }
+ if (caps.contains('s')) {
+ item.caps |= GpgOp::KeyItem::Sign;
+ }
+ if (caps.contains('c')) {
+ item.caps |= GpgOp::KeyItem::Certify;
+ }
+ if (caps.contains('a')) {
+ item.caps |= GpgOp::KeyItem::Auth;
+ }
+
+ keyList.last().keyItems += item;
+ } else if (type == "uid") {
+ QByteArray uid = getCString(f[9].toUtf8());
+ keyList.last().userIds.append(QString::fromUtf8(uid));
+ } else if (type == "fpr") {
+ QString s = f[9];
+ keyList.last().keyItems.last().fingerprint = s;
+ }
+ }
+
+ if (_keylist) {
+ *_keylist = keyList;
+ }
+ if (_keyring) {
+ *_keyring = keyring;
+ }
+
+ return true;
}
static bool findKeyringFilename(const QString &outstr, QString *_keyring)
{
- QStringList lines = outstr.split('\n');
- if(lines.count() < 1)
- return false;
+ QStringList lines = outstr.split('\n');
+ if (lines.count() < 1) {
+ return false;
+ }
- *_keyring = lines[0];
- return true;
+ *_keyring = lines[0];
+ return true;
}
GpgAction::GpgAction(QObject *parent)
- : QObject(parent)
- , proc(this)
- , dtextTimer(this)
- , utf8Output(false)
+ : QObject(parent)
+ , proc(this)
+ , dtextTimer(this)
+ , utf8Output(false)
{
- dtextTimer.setSingleShot(true);
-
- connect(&proc, SIGNAL(error(gpgQCAPlugin::GPGProc::Error)), SLOT(proc_error(gpgQCAPlugin::GPGProc::Error)));
- connect(&proc, SIGNAL(finished(int)), SLOT(proc_finished(int)));
- connect(&proc, SIGNAL(readyReadStdout()), SLOT(proc_readyReadStdout()));
- connect(&proc, SIGNAL(readyReadStderr()), SLOT(proc_readyReadStderr()));
- connect(&proc, SIGNAL(readyReadStatusLines()), SLOT(proc_readyReadStatusLines()));
- connect(&proc, SIGNAL(bytesWrittenStdin(int)), SLOT(proc_bytesWrittenStdin(int)));
- connect(&proc, SIGNAL(bytesWrittenAux(int)), SLOT(proc_bytesWrittenAux(int)));
- connect(&proc, SIGNAL(bytesWrittenCommand(int)), SLOT(proc_bytesWrittenCommand(int)));
- connect(&proc, SIGNAL(debug(const QString &)), SLOT(proc_debug(const QString &)));
- connect(&dtextTimer, SIGNAL(timeout()), SLOT(t_dtext()));
-
- reset();
+ dtextTimer.setSingleShot(true);
+
+ connect(&proc, SIGNAL(error(gpgQCAPlugin::GPGProc::Error)), SLOT(proc_error(gpgQCAPlugin::GPGProc::Error)));
+ connect(&proc, SIGNAL(finished(int)), SLOT(proc_finished(int)));
+ connect(&proc, SIGNAL(readyReadStdout()), SLOT(proc_readyReadStdout()));
+ connect(&proc, SIGNAL(readyReadStderr()), SLOT(proc_readyReadStderr()));
+ connect(&proc, SIGNAL(readyReadStatusLines()), SLOT(proc_readyReadStatusLines()));
+ connect(&proc, SIGNAL(bytesWrittenStdin(int)), SLOT(proc_bytesWrittenStdin(int)));
+ connect(&proc, SIGNAL(bytesWrittenAux(int)), SLOT(proc_bytesWrittenAux(int)));
+ connect(&proc, SIGNAL(bytesWrittenCommand(int)), SLOT(proc_bytesWrittenCommand(int)));
+ connect(&proc, SIGNAL(debug(QString)), SLOT(proc_debug(QString)));
+ connect(&dtextTimer, SIGNAL(timeout()), SLOT(t_dtext()));
+
+ reset();
}
GpgAction::~GpgAction()
{
- reset();
+ reset();
}
void GpgAction::reset()
{
- collectOutput = true;
- allowInput = false;
- readConv.setup(LineConverter::Read);
- writeConv.setup(LineConverter::Write);
- readText = false;
- writeText = false;
- useAux = false;
- passphraseKeyId = QString();
- signing = false;
- decryptGood = false;
- signGood = false;
- curError = GpgOp::ErrorUnknown;
- badPassphrase = false;
- need_submitPassphrase = false;
- need_cardOkay = false;
- diagnosticText = QString();
- dtextTimer.stop();
-
- output = Output();
-
- proc.reset();
+ collectOutput = true;
+ allowInput = false;
+ readConv.setup(LineConverter::Read);
+ writeConv.setup(LineConverter::Write);
+ readText = false;
+ writeText = false;
+ useAux = false;
+ passphraseKeyId = QString();
+ signing = false;
+ decryptGood = false;
+ signGood = false;
+ curError = GpgOp::ErrorUnknown;
+ badPassphrase = false;
+ need_submitPassphrase = false;
+ need_cardOkay = false;
+ diagnosticText = QString();
+ dtextTimer.stop();
+
+ output = Output();
+
+ proc.reset();
}
void GpgAction::start()
{
- reset();
-
- QStringList args;
- bool extra = false;
-
- if(input.opt_ascii)
- args += "--armor";
-
- if(input.opt_noagent)
- args += "--no-use-agent";
-
- if(input.opt_alwaystrust)
- args += "--always-trust";
-
- if(!input.opt_pubfile.isEmpty() && !input.opt_secfile.isEmpty())
- {
- args += "--no-default-keyring";
- args += "--keyring";
- args += input.opt_pubfile;
- args += "--secret-keyring";
- args += input.opt_secfile;
- }
-
- switch(input.op)
- {
- case GpgOp::Check:
- {
- args += "--version";
- readText = true;
- break;
- }
- case GpgOp::SecretKeyringFile:
- {
+ reset();
+
+ QStringList args;
+ bool extra = false;
+
+ if (input.opt_ascii) {
+ args += "--armor";
+ }
+
+ if (input.opt_noagent) {
+ args += "--no-use-agent";
+ }
+
+ if (input.opt_alwaystrust) {
+ args += "--always-trust";
+ }
+
+ if (!input.opt_pubfile.isEmpty() && !input.opt_secfile.isEmpty()) {
+ args += "--no-default-keyring";
+ args += "--keyring";
+ args += input.opt_pubfile;
+ args += "--secret-keyring";
+ args += input.opt_secfile;
+ }
+
+ switch (input.op) {
+ case GpgOp::Check: {
+ args += "--version";
+ readText = true;
+ break;
+ }
+ case GpgOp::SecretKeyringFile: {
#ifndef Q_OS_WIN
- args += "--display-charset=utf-8";
+ args += "--display-charset=utf-8";
#endif
- args += "--list-secret-keys";
- readText = true;
- break;
- }
- case GpgOp::PublicKeyringFile:
- {
+ args += "--list-secret-keys";
+ readText = true;
+ break;
+ }
+ case GpgOp::PublicKeyringFile: {
#ifndef Q_OS_WIN
- args += "--display-charset=utf-8";
+ args += "--display-charset=utf-8";
#endif
- args += "--list-public-keys";
- readText = true;
- break;
- }
- case GpgOp::SecretKeys:
- {
- args += "--fixed-list-mode";
- args += "--with-colons";
- args += "--with-fingerprint";
- args += "--with-fingerprint";
- args += "--list-secret-keys";
- utf8Output = true;
- readText = true;
- break;
- }
- case GpgOp::PublicKeys:
- {
- args += "--fixed-list-mode";
- args += "--with-colons";
- args += "--with-fingerprint";
- args += "--with-fingerprint";
- args += "--list-public-keys";
- utf8Output = true;
- readText = true;
- break;
- }
- case GpgOp::Encrypt:
- {
- args += "--encrypt";
-
- // recipients
- for(QStringList::ConstIterator it = input.recip_ids.constBegin(); it != input.recip_ids.constEnd(); ++it)
- {
- args += "--recipient";
- args += QString("0x") + *it;
- }
- extra = true;
- collectOutput = false;
- allowInput = true;
- if(input.opt_ascii)
- readText = true;
- break;
- }
- case GpgOp::Decrypt:
- {
- args += "--decrypt";
- extra = true;
- collectOutput = false;
- allowInput = true;
- if(input.opt_ascii)
- writeText = true;
- break;
- }
- case GpgOp::Sign:
- {
- args += "--default-key";
- args += QString("0x") + input.signer_id;
- args += "--sign";
- extra = true;
- collectOutput = false;
- allowInput = true;
- if(input.opt_ascii)
- readText = true;
- signing = true;
- break;
- }
- case GpgOp::SignAndEncrypt:
- {
- args += "--default-key";
- args += QString("0x") + input.signer_id;
- args += "--sign";
- args += "--encrypt";
-
- // recipients
- for(QStringList::ConstIterator it = input.recip_ids.constBegin(); it != input.recip_ids.constEnd(); ++it)
- {
- args += "--recipient";
- args += QString("0x") + *it;
- }
- extra = true;
- collectOutput = false;
- allowInput = true;
- if(input.opt_ascii)
- readText = true;
- signing = true;
- break;
- }
- case GpgOp::SignClearsign:
- {
- args += "--default-key";
- args += QString("0x") + input.signer_id;
- args += "--clearsign";
- extra = true;
- collectOutput = false;
- allowInput = true;
- if(input.opt_ascii)
- readText = true;
- signing = true;
- break;
- }
- case GpgOp::SignDetached:
- {
- args += "--default-key";
- args += QString("0x") + input.signer_id;
- args += "--detach-sign";
- extra = true;
- collectOutput = false;
- allowInput = true;
- if(input.opt_ascii)
- readText = true;
- signing = true;
- break;
- }
- case GpgOp::Verify:
- {
- args += "--verify";
- args += "-"; //krazy:exclude=doublequote_chars
- extra = true;
- allowInput = true;
- if(input.opt_ascii)
- writeText = true;
- break;
- }
- case GpgOp::VerifyDetached:
- {
- args += "--verify";
- args += "-"; //krazy:exclude=doublequote_chars
- args += "-&?";
- extra = true;
- allowInput = true;
- useAux = true;
- break;
- }
- case GpgOp::Import:
- {
- args += "--import";
- readText = true;
- if(input.opt_ascii)
- writeText = true;
- break;
- }
- case GpgOp::Export:
- {
- args += "--export";
- args += QString("0x") + input.export_key_id;
- collectOutput = false;
- if(input.opt_ascii)
- readText = true;
- break;
- }
- case GpgOp::DeleteKey:
- {
- args += "--batch";
- args += "--delete-key";
- args += QString("0x") + input.delete_key_fingerprint;
- break;
- }
- }
+ args += "--list-public-keys";
+ readText = true;
+ break;
+ }
+ case GpgOp::SecretKeys: {
+ args += "--fixed-list-mode";
+ args += "--with-colons";
+ args += "--with-fingerprint";
+ args += "--with-fingerprint";
+ args += "--list-secret-keys";
+ utf8Output = true;
+ readText = true;
+ break;
+ }
+ case GpgOp::PublicKeys: {
+ args += "--fixed-list-mode";
+ args += "--with-colons";
+ args += "--with-fingerprint";
+ args += "--with-fingerprint";
+ args += "--list-public-keys";
+ utf8Output = true;
+ readText = true;
+ break;
+ }
+ case GpgOp::Encrypt: {
+ args += "--encrypt";
+
+ // recipients
+ for (QStringList::ConstIterator it = input.recip_ids.constBegin(); it != input.recip_ids.constEnd(); ++it) {
+ args += "--recipient";
+ args += QString("0x") + *it;
+ }
+ extra = true;
+ collectOutput = false;
+ allowInput = true;
+ if (input.opt_ascii) {
+ readText = true;
+ }
+ break;
+ }
+ case GpgOp::Decrypt: {
+ args += "--decrypt";
+ extra = true;
+ collectOutput = false;
+ allowInput = true;
+ if (input.opt_ascii) {
+ writeText = true;
+ }
+ break;
+ }
+ case GpgOp::Sign: {
+ args += "--default-key";
+ args += QString("0x") + input.signer_id;
+ args += "--sign";
+ extra = true;
+ collectOutput = false;
+ allowInput = true;
+ if (input.opt_ascii) {
+ readText = true;
+ }
+ signing = true;
+ break;
+ }
+ case GpgOp::SignAndEncrypt: {
+ args += "--default-key";
+ args += QString("0x") + input.signer_id;
+ args += "--sign";
+ args += "--encrypt";
+
+ // recipients
+ for (QStringList::ConstIterator it = input.recip_ids.constBegin(); it != input.recip_ids.constEnd(); ++it) {
+ args += "--recipient";
+ args += QString("0x") + *it;
+ }
+ extra = true;
+ collectOutput = false;
+ allowInput = true;
+ if (input.opt_ascii) {
+ readText = true;
+ }
+ signing = true;
+ break;
+ }
+ case GpgOp::SignClearsign: {
+ args += "--default-key";
+ args += QString("0x") + input.signer_id;
+ args += "--clearsign";
+ extra = true;
+ collectOutput = false;
+ allowInput = true;
+ if (input.opt_ascii) {
+ readText = true;
+ }
+ signing = true;
+ break;
+ }
+ case GpgOp::SignDetached: {
+ args += "--default-key";
+ args += QString("0x") + input.signer_id;
+ args += "--detach-sign";
+ extra = true;
+ collectOutput = false;
+ allowInput = true;
+ if (input.opt_ascii) {
+ readText = true;
+ }
+ signing = true;
+ break;
+ }
+ case GpgOp::Verify: {
+ args += "--verify";
+ args += "-"; //krazy:exclude=doublequote_chars
+ extra = true;
+ allowInput = true;
+ if (input.opt_ascii) {
+ writeText = true;
+ }
+ break;
+ }
+ case GpgOp::VerifyDetached: {
+ args += "--verify";
+ args += "-"; //krazy:exclude=doublequote_chars
+ args += "-&?";
+ extra = true;
+ allowInput = true;
+ useAux = true;
+ break;
+ }
+ case GpgOp::Import: {
+ args += "--import";
+ readText = true;
+ if (input.opt_ascii) {
+ writeText = true;
+ }
+ break;
+ }
+ case GpgOp::Export: {
+ args += "--export";
+ args += QString("0x") + input.export_key_id;
+ collectOutput = false;
+ if (input.opt_ascii) {
+ readText = true;
+ }
+ break;
+ }
+ case GpgOp::DeleteKey: {
+ args += "--batch";
+ args += "--delete-key";
+ args += QString("0x") + input.delete_key_fingerprint;
+ break;
+ }
+ }
#ifdef GPG_PROFILE
- timer.start();
- printf("<< launch >>\n");
+ timer.start();
+ printf("<< launch >>\n");
#endif
- proc.start(input.bin, args, extra ? GPGProc::ExtendedMode : GPGProc::NormalMode);
-
- // detached sig
- if(input.op == GpgOp::VerifyDetached)
- {
- QByteArray a = input.sig;
- if(input.opt_ascii)
- {
- LineConverter conv;
- conv.setup(LineConverter::Write);
- a = conv.process(a);
- }
- proc.writeStdin(a);
- proc.closeStdin();
- }
-
- // import
- if(input.op == GpgOp::Import)
- {
- QByteArray a = input.inkey;
- if(writeText)
- {
- LineConverter conv;
- conv.setup(LineConverter::Write);
- a = conv.process(a);
- }
- proc.writeStdin(a);
- proc.closeStdin();
- }
+ proc.start(input.bin, args, extra ? GPGProc::ExtendedMode : GPGProc::NormalMode);
+
+ // detached sig
+ if (input.op == GpgOp::VerifyDetached) {
+ QByteArray a = input.sig;
+ if (input.opt_ascii) {
+ LineConverter conv;
+ conv.setup(LineConverter::Write);
+ a = conv.process(a);
+ }
+ proc.writeStdin(a);
+ proc.closeStdin();
+ }
+
+ // import
+ if (input.op == GpgOp::Import) {
+ QByteArray a = input.inkey;
+ if (writeText) {
+ LineConverter conv;
+ conv.setup(LineConverter::Write);
+ a = conv.process(a);
+ }
+ proc.writeStdin(a);
+ proc.closeStdin();
+ }
}
#ifdef QPIPE_SECURE
void GpgAction::submitPassphrase(const QCA::SecureArray &a)
#else
- void GpgAction::submitPassphrase(const QByteArray &a)
+void GpgAction::submitPassphrase(const QByteArray &a)
#endif
{
- if(!need_submitPassphrase)
- return;
+ if (!need_submitPassphrase) {
+ return;
+ }
- need_submitPassphrase = false;
+ need_submitPassphrase = false;
#ifdef QPIPE_SECURE
- QCA::SecureArray b;
+ QCA::SecureArray b;
#else
- QByteArray b;
+ QByteArray b;
#endif
- // filter out newlines, since that's the delimiter used
- // to indicate a submitted passphrase
- b.resize(a.size());
- int at = 0;
- for(int n = 0; n < a.size(); ++n)
- {
- if(a[n] != '\n')
- b[at++] = a[n];
- }
- b.resize(at);
-
- // append newline
- b.resize(b.size() + 1);
- b[b.size() - 1] = '\n';
- proc.writeCommand(b);
+ // filter out newlines, since that's the delimiter used
+ // to indicate a submitted passphrase
+ b.resize(a.size());
+ int at = 0;
+ for (int n = 0; n < a.size(); ++n) {
+ if (a[n] != '\n') {
+ b[at++] = a[n];
+ }
+ }
+ b.resize(at);
+
+ // append newline
+ b.resize(b.size() + 1);
+ b[b.size() - 1] = '\n';
+ proc.writeCommand(b);
}
QByteArray GpgAction::read()
{
- if(collectOutput)
- return QByteArray();
-
- QByteArray a = proc.readStdout();
- if(readText)
- a = readConv.update(a);
- if(!proc.isActive())
- a += readConv.final();
- return a;
+ if (collectOutput) {
+ return QByteArray();
+ }
+
+ QByteArray a = proc.readStdout();
+ if (readText) {
+ a = readConv.update(a);
+ }
+ if (!proc.isActive()) {
+ a += readConv.final();
+ }
+ return a;
}
void GpgAction::write(const QByteArray &in)
{
- if(!allowInput)
- return;
-
- QByteArray a = in;
- if(writeText)
- a = writeConv.update(in);
-
- if(useAux)
- proc.writeAux(a);
- else
- proc.writeStdin(a);
+ if (!allowInput) {
+ return;
+ }
+
+ QByteArray a = in;
+ if (writeText) {
+ a = writeConv.update(in);
+ }
+
+ if (useAux) {
+ proc.writeAux(a);
+ } else {
+ proc.writeStdin(a);
+ }
}
void GpgAction::endWrite()
{
- if(!allowInput)
- return;
-
- if(useAux)
- proc.closeAux();
- else
- proc.closeStdin();
+ if (!allowInput) {
+ return;
+ }
+
+ if (useAux) {
+ proc.closeAux();
+ } else {
+ proc.closeStdin();
+ }
}
void GpgAction::cardOkay()
{
- if(need_cardOkay)
- {
- need_cardOkay = false;
- submitCommand("\n");
- }
+ if (need_cardOkay) {
+ need_cardOkay = false;
+ submitCommand("\n");
+ }
}
QString GpgAction::readDiagnosticText()
{
- QString s = diagnosticText;
- diagnosticText = QString();
- return s;
+ QString s = diagnosticText;
+ diagnosticText = QString();
+ return s;
}
void GpgAction::submitCommand(const QByteArray &a)
{
- proc.writeCommand(a);
+ proc.writeCommand(a);
}
// since str is taken as a value, it is ok to use the same variable for 'rest'
QString GpgAction::nextArg(QString str, QString *rest)
{
- QString out;
- int n = str.indexOf(' ');
- if(n == -1)
- {
- if(rest)
- *rest = QString();
- return str;
- }
- else
- {
- if(rest)
- *rest = str.mid(n + 1);
- return str.mid(0, n);
- }
+ QString out;
+ int n = str.indexOf(' ');
+ if (n == -1) {
+ if (rest) {
+ *rest = QString();
+ }
+ return str;
+ } else {
+ if (rest) {
+ *rest = str.mid(n + 1);
+ }
+ return str.mid(0, n);
+ }
}
void GpgAction::processStatusLine(const QString &line)
{
- appendDiagnosticText("{" + line + "}");
- ensureDTextEmit();
-
- if(!proc.isActive())
- return;
-
- QString s, rest;
- s = nextArg(line, &rest);
-
- if(s == "NODATA")
- {
- // only set this if it'll make it better
- if(curError == GpgOp::ErrorUnknown)
- curError = GpgOp::ErrorFormat;
- }
- else if(s == "UNEXPECTED")
- {
- if(curError == GpgOp::ErrorUnknown)
- curError = GpgOp::ErrorFormat;
- }
- else if(s == "EXPKEYSIG")
- {
- curError = GpgOp::ErrorSignerExpired;
- }
- else if(s == "REVKEYSIG")
- {
- curError = GpgOp::ErrorSignerRevoked;
- }
- else if(s == "EXPSIG")
- {
- curError = GpgOp::ErrorSignatureExpired;
- }
- else if(s == "INV_RECP")
- {
- int r = nextArg(rest).toInt();
-
- if(curError == GpgOp::ErrorUnknown)
- {
- if(r == 10)
- curError = GpgOp::ErrorEncryptUntrusted;
- else if(r == 4)
- curError = GpgOp::ErrorEncryptRevoked;
- else if(r == 5)
- curError = GpgOp::ErrorEncryptExpired;
- else
- // due to GnuPG bug #1650
- // <https://bugs.g10code.com/gnupg/issue1650>
- // encrypting to expired and revoked keys will
- // not specify any reason for failing,
- // defaulting to this
- curError = GpgOp::ErrorEncryptInvalid;
- }
- }
- else if(s == "NO_SECKEY")
- {
- output.encryptedToId = nextArg(rest);
-
- if(curError == GpgOp::ErrorUnknown)
- curError = GpgOp::ErrorDecryptNoKey;
- }
- else if(s == "DECRYPTION_OKAY")
- {
- decryptGood = true;
-
- // message could be encrypted with several keys
- if(curError == GpgOp::ErrorDecryptNoKey)
- curError = GpgOp::ErrorUnknown;
- }
- else if(s == "SIG_CREATED")
- {
- signGood = true;
- }
- else if(s == "USERID_HINT")
- {
- passphraseKeyId = nextArg(rest);
- }
- else if(s == "GET_HIDDEN")
- {
- QString arg = nextArg(rest);
- if(arg == "passphrase.enter" || arg == "passphrase.pin.ask")
- {
- need_submitPassphrase = true;
-
- // for signal-safety, emit later
- QMetaObject::invokeMethod(this, "needPassphrase", Qt::QueuedConnection, Q_ARG(QString, passphraseKeyId));
- }
- }
- else if(s == "GET_LINE")
- {
- QString arg = nextArg(rest);
- if(arg == "cardctrl.insert_card.okay")
- {
- need_cardOkay = true;
-
- QMetaObject::invokeMethod(this, "needCard", Qt::QueuedConnection);
- }
- }
- else if(s == "GET_BOOL")
- {
- QString arg = nextArg(rest);
- if(arg == "untrusted_key.override")
- submitCommand("no\n");
- }
- else if(s == "GOOD_PASSPHRASE")
- {
- badPassphrase = false;
- }
- else if(s == "BAD_PASSPHRASE")
- {
- badPassphrase = true;
- }
- else if(s == "GOODSIG")
- {
- output.wasSigned = true;
- output.signerId = nextArg(rest);
- output.verifyResult = GpgOp::VerifyGood;
- }
- else if(s == "BADSIG")
- {
- output.wasSigned = true;
- output.signerId = nextArg(rest);
- output.verifyResult = GpgOp::VerifyBad;
- }
- else if(s == "ERRSIG")
- {
- output.wasSigned = true;
- QStringList list = rest.split(' ', QString::SkipEmptyParts);
- output.signerId = list[0];
- output.timestamp = getTimestamp(list[4]);
- output.verifyResult = GpgOp::VerifyNoKey;
- }
- else if(s == "VALIDSIG")
- {
- QStringList list = rest.split(' ', QString::SkipEmptyParts);
- output.timestamp = getTimestamp(list[2]);
- }
+ appendDiagnosticText("{" + line + "}");
+ ensureDTextEmit();
+
+ if (!proc.isActive()) {
+ return;
+ }
+
+ QString s, rest;
+ s = nextArg(line, &rest);
+
+ if (s == "NODATA") {
+ // only set this if it'll make it better
+ if (curError == GpgOp::ErrorUnknown) {
+ curError = GpgOp::ErrorFormat;
+ }
+ } else if (s == "UNEXPECTED") {
+ if (curError == GpgOp::ErrorUnknown) {
+ curError = GpgOp::ErrorFormat;
+ }
+ } else if (s == "EXPKEYSIG") {
+ curError = GpgOp::ErrorSignerExpired;
+ } else if (s == "REVKEYSIG") {
+ curError = GpgOp::ErrorSignerRevoked;
+ } else if (s == "EXPSIG") {
+ curError = GpgOp::ErrorSignatureExpired;
+ } else if (s == "INV_RECP") {
+ int r = nextArg(rest).toInt();
+
+ if (curError == GpgOp::ErrorUnknown) {
+ if (r == 10) {
+ curError = GpgOp::ErrorEncryptUntrusted;
+ } else if (r == 4) {
+ curError = GpgOp::ErrorEncryptRevoked;
+ } else if (r == 5) {
+ curError = GpgOp::ErrorEncryptExpired;
+ } else
+ // due to GnuPG bug #1650
+ // <https://bugs.g10code.com/gnupg/issue1650>
+ // encrypting to expired and revoked keys will
+ // not specify any reason for failing,
+ // defaulting to this
+ {
+ curError = GpgOp::ErrorEncryptInvalid;
+ }
+ }
+ } else if (s == "NO_SECKEY") {
+ output.encryptedToId = nextArg(rest);
+
+ if (curError == GpgOp::ErrorUnknown) {
+ curError = GpgOp::ErrorDecryptNoKey;
+ }
+ } else if (s == "DECRYPTION_OKAY") {
+ decryptGood = true;
+
+ // message could be encrypted with several keys
+ if (curError == GpgOp::ErrorDecryptNoKey) {
+ curError = GpgOp::ErrorUnknown;
+ }
+ } else if (s == "SIG_CREATED") {
+ signGood = true;
+ } else if (s == "USERID_HINT") {
+ passphraseKeyId = nextArg(rest);
+ } else if (s == "GET_HIDDEN") {
+ QString arg = nextArg(rest);
+ if (arg == "passphrase.enter" || arg == "passphrase.pin.ask") {
+ need_submitPassphrase = true;
+
+ // for signal-safety, emit later
+ QMetaObject::invokeMethod(this, "needPassphrase", Qt::QueuedConnection, Q_ARG(QString, passphraseKeyId));
+ }
+ } else if (s == "GET_LINE") {
+ QString arg = nextArg(rest);
+ if (arg == "cardctrl.insert_card.okay") {
+ need_cardOkay = true;
+
+ QMetaObject::invokeMethod(this, "needCard", Qt::QueuedConnection);
+ }
+ } else if (s == "GET_BOOL") {
+ QString arg = nextArg(rest);
+ if (arg == "untrusted_key.override") {
+ submitCommand("no\n");
+ }
+ } else if (s == "GOOD_PASSPHRASE") {
+ badPassphrase = false;
+ } else if (s == "BAD_PASSPHRASE") {
+ badPassphrase = true;
+ } else if (s == "GOODSIG") {
+ output.wasSigned = true;
+ output.signerId = nextArg(rest);
+ output.verifyResult = GpgOp::VerifyGood;
+ } else if (s == "BADSIG") {
+ output.wasSigned = true;
+ output.signerId = nextArg(rest);
+ output.verifyResult = GpgOp::VerifyBad;
+ } else if (s == "ERRSIG") {
+ output.wasSigned = true;
+ QStringList list = rest.split(' ', QString::SkipEmptyParts);
+ output.signerId = list[0];
+ output.timestamp = getTimestamp(list[4]);
+ output.verifyResult = GpgOp::VerifyNoKey;
+ } else if (s == "VALIDSIG") {
+ QStringList list = rest.split(' ', QString::SkipEmptyParts);
+ output.timestamp = getTimestamp(list[2]);
+ }
}
void GpgAction::processResult(int code)
{
#ifdef GPG_PROFILE
- printf("<< launch: %d >>\n", timer.elapsed());
+ printf("<< launch: %d >>\n", timer.elapsed());
#endif
- // put stdout and stderr into QStrings
+ // put stdout and stderr into QStrings
+
+ QString outstr;
+ QString errstr;
- QString outstr;
- QString errstr;
-
#ifdef Q_OS_WIN
- if (!utf8Output)
- {
- outstr = QString::fromLocal8Bit(buf_stdout);
- errstr = QString::fromLocal8Bit(buf_stderr);
- }
- else
- {
+ if (!utf8Output) {
+ outstr = QString::fromLocal8Bit(buf_stdout);
+ errstr = QString::fromLocal8Bit(buf_stderr);
+ } else {
#endif
- outstr = QString::fromUtf8(buf_stdout);
- errstr = QString::fromUtf8(buf_stderr);
+ outstr = QString::fromUtf8(buf_stdout);
+ errstr = QString::fromUtf8(buf_stderr);
#ifdef Q_OS_WIN
- }
+ }
#endif
- if(collectOutput)
- appendDiagnosticText(QString("stdout: [%1]").arg(outstr));
- appendDiagnosticText(QString("stderr: [%1]").arg(errstr));
- ensureDTextEmit();
-
- if(badPassphrase)
- {
- output.errorCode = GpgOp::ErrorPassphrase;
- }
- else if(curError != GpgOp::ErrorUnknown)
- {
- output.errorCode = curError;
- }
- else if(code == 0)
- {
- if(input.op == GpgOp::Check)
- {
- QStringList strList = outstr.split("\n");
- foreach (const QString &str, strList)
- {
- if (!str.startsWith("Home: "))
- continue;
-
- output.homeDir = str.section(' ', 1);
- break;
- }
- output.success = true;
- }
- else if(input.op == GpgOp::SecretKeyringFile || input.op == GpgOp::PublicKeyringFile)
- {
- if(findKeyringFilename(outstr, &output.keyringFile))
- output.success = true;
- }
- else if(input.op == GpgOp::SecretKeys || input.op == GpgOp::PublicKeys)
- {
- if(stringToKeyList(outstr, &output.keys, &output.keyringFile))
- output.success = true;
- }
- else
- output.success = true;
- }
- else
- {
- // decrypt and sign success based on status only.
- // this is mainly because gpg uses fatal return
- // values if there is trouble with gpg-agent, even
- // though the operation otherwise works.
-
- if(input.op == GpgOp::Decrypt && decryptGood)
- output.success = true;
- if(signing && signGood)
- output.success = true;
-
- // gpg will indicate failure for bad sigs, but we don't
- // consider this to be operation failure.
-
- bool signedMakesItGood = false;
- if(input.op == GpgOp::Verify || input.op == GpgOp::VerifyDetached)
- signedMakesItGood = true;
-
- if(signedMakesItGood && output.wasSigned)
- output.success = true;
- }
-
- emit finished();
+ if (collectOutput) {
+ appendDiagnosticText(QString("stdout: [%1]").arg(outstr));
+ }
+ appendDiagnosticText(QString("stderr: [%1]").arg(errstr));
+ ensureDTextEmit();
+
+ if (badPassphrase) {
+ output.errorCode = GpgOp::ErrorPassphrase;
+ } else if (curError != GpgOp::ErrorUnknown) {
+ output.errorCode = curError;
+ } else if (code == 0) {
+ if (input.op == GpgOp::Check) {
+ QStringList strList = outstr.split("\n");
+ foreach (const QString &str, strList) {
+ if (!str.startsWith("Home: ")) {
+ continue;
+ }
+
+ output.homeDir = str.section(' ', 1);
+ break;
+ }
+ output.success = true;
+ } else if (input.op == GpgOp::SecretKeyringFile || input.op == GpgOp::PublicKeyringFile) {
+ if (findKeyringFilename(outstr, &output.keyringFile)) {
+ output.success = true;
+ }
+ } else if (input.op == GpgOp::SecretKeys || input.op == GpgOp::PublicKeys) {
+ if (stringToKeyList(outstr, &output.keys, &output.keyringFile)) {
+ output.success = true;
+ }
+ } else {
+ output.success = true;
+ }
+ } else {
+ // decrypt and sign success based on status only.
+ // this is mainly because gpg uses fatal return
+ // values if there is trouble with gpg-agent, even
+ // though the operation otherwise works.
+
+ if (input.op == GpgOp::Decrypt && decryptGood) {
+ output.success = true;
+ }
+ if (signing && signGood) {
+ output.success = true;
+ }
+
+ // gpg will indicate failure for bad sigs, but we don't
+ // consider this to be operation failure.
+
+ bool signedMakesItGood = false;
+ if (input.op == GpgOp::Verify || input.op == GpgOp::VerifyDetached) {
+ signedMakesItGood = true;
+ }
+
+ if (signedMakesItGood && output.wasSigned) {
+ output.success = true;
+ }
+ }
+
+ emit finished();
}
void GpgAction::ensureDTextEmit()
{
- if(!dtextTimer.isActive())
- dtextTimer.start();
+ if (!dtextTimer.isActive()) {
+ dtextTimer.start();
+ }
}
void GpgAction::t_dtext()
{
- emit readyReadDiagnosticText();
+ emit readyReadDiagnosticText();
}
void GpgAction::proc_error(gpgQCAPlugin::GPGProc::Error e)
{
- QString str;
- if(e == GPGProc::FailedToStart)
- str = "FailedToStart";
- else if(e == GPGProc::UnexpectedExit)
- str = "UnexpectedExit";
- else if(e == GPGProc::ErrorWrite)
- str = "ErrorWrite";
-
- appendDiagnosticText(QString("GPG Process Error: %1").arg(str));
- ensureDTextEmit();
-
- output.errorCode = GpgOp::ErrorProcess;
- emit finished();
+ QString str;
+ if (e == GPGProc::FailedToStart) {
+ str = "FailedToStart";
+ } else if (e == GPGProc::UnexpectedExit) {
+ str = "UnexpectedExit";
+ } else if (e == GPGProc::ErrorWrite) {
+ str = "ErrorWrite";
+ }
+
+ appendDiagnosticText(QString("GPG Process Error: %1").arg(str));
+ ensureDTextEmit();
+
+ output.errorCode = GpgOp::ErrorProcess;
+ emit finished();
}
void GpgAction::proc_finished(int exitCode)
{
- appendDiagnosticText(QString("GPG Process Finished: exitStatus=%1").arg(exitCode));
- ensureDTextEmit();
+ appendDiagnosticText(QString("GPG Process Finished: exitStatus=%1").arg(exitCode));
+ ensureDTextEmit();
- processResult(exitCode);
+ processResult(exitCode);
}
void GpgAction::proc_readyReadStdout()
{
- if(collectOutput)
- {
- QByteArray a = proc.readStdout();
- if(readText)
- a = readConv.update(a);
- buf_stdout.append(a);
- }
- else
- emit readyRead();
+ if (collectOutput) {
+ QByteArray a = proc.readStdout();
+ if (readText) {
+ a = readConv.update(a);
+ }
+ buf_stdout.append(a);
+ } else {
+ emit readyRead();
+ }
}
void GpgAction::proc_readyReadStderr()
{
- buf_stderr.append(proc.readStderr());
+ buf_stderr.append(proc.readStderr());
}
void GpgAction::proc_readyReadStatusLines()
{
- QStringList lines = proc.readStatusLines();
- for(int n = 0; n < lines.count(); ++n)
- processStatusLine(lines[n]);
+ QStringList lines = proc.readStatusLines();
+ for (int n = 0; n < lines.count(); ++n) {
+ processStatusLine(lines[n]);
+ }
}
void GpgAction::proc_bytesWrittenStdin(int bytes)
{
- if(!useAux)
- {
- int actual = writeConv.writtenToActual(bytes);
- emit bytesWritten(actual);
- }
+ if (!useAux) {
+ int actual = writeConv.writtenToActual(bytes);
+ emit bytesWritten(actual);
+ }
}
void GpgAction::proc_bytesWrittenAux(int bytes)
{
- if(useAux)
- {
- int actual = writeConv.writtenToActual(bytes);
- emit bytesWritten(actual);
- }
+ if (useAux) {
+ int actual = writeConv.writtenToActual(bytes);
+ emit bytesWritten(actual);
+ }
}
void GpgAction::proc_bytesWrittenCommand(int)
{
- // don't care about this
+ // don't care about this
}
void GpgAction::proc_debug(const QString &str)
{
- appendDiagnosticText("GPGProc: " + str);
- ensureDTextEmit();
+ appendDiagnosticText("GPGProc: " + str);
+ ensureDTextEmit();
}
void GpgAction::appendDiagnosticText(const QString &line)
{
#ifdef GPGOP_DEBUG
- printf("%s\n", qPrintable(line));
+ printf("%s\n", qPrintable(line));
#endif
- diagnosticText += line;
+ diagnosticText += line;
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/gpgaction.h b/plugins/qca-gnupg/gpgaction.h
index d29109ad..a97fe3cc 100644
--- a/plugins/qca-gnupg/gpgaction.h
+++ b/plugins/qca-gnupg/gpgaction.h
@@ -1,143 +1,141 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#pragma once
#include "lineconverter.h"
#include "qca_safetimer.h"
#include "gpgop.h"
#include "gpgproc.h"
#include <QObject>
#include <QStringList>
#include <QByteArray>
#ifdef GPG_PROFILE
#include <QTime>
#endif
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
class GpgAction : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- struct Input
- {
- QString bin;
- GpgOp::Type op;
- bool opt_ascii, opt_noagent, opt_alwaystrust;
- QString opt_pubfile, opt_secfile;
- QStringList recip_ids;
- QString signer_id;
- QByteArray sig;
- QByteArray inkey;
- QString export_key_id;
- QString delete_key_fingerprint;
-
- Input() : opt_ascii(false), opt_noagent(false), opt_alwaystrust(false) {}
- };
-
- struct Output
- {
- bool success;
- GpgOp::Error errorCode;
- GpgOp::KeyList keys;
- QString keyringFile;
- QString encryptedToId;
- bool wasSigned;
- QString signerId;
- QDateTime timestamp;
- GpgOp::VerifyResult verifyResult;
- QString homeDir;
-
- Output() : success(false), errorCode(GpgOp::ErrorUnknown), wasSigned(false) {}
- };
-
- Input input;
- Output output;
-
- GpgAction(QObject *parent = 0);
- ~GpgAction();
- void reset();
- void start();
+ struct Input {
+ QString bin;
+ GpgOp::Type op;
+ bool opt_ascii, opt_noagent, opt_alwaystrust;
+ QString opt_pubfile, opt_secfile;
+ QStringList recip_ids;
+ QString signer_id;
+ QByteArray sig;
+ QByteArray inkey;
+ QString export_key_id;
+ QString delete_key_fingerprint;
+
+ Input() : opt_ascii(false), opt_noagent(false), opt_alwaystrust(false) {}
+ };
+
+ struct Output {
+ bool success;
+ GpgOp::Error errorCode;
+ GpgOp::KeyList keys;
+ QString keyringFile;
+ QString encryptedToId;
+ bool wasSigned;
+ QString signerId;
+ QDateTime timestamp;
+ GpgOp::VerifyResult verifyResult;
+ QString homeDir;
+
+ Output() : success(false), errorCode(GpgOp::ErrorUnknown), wasSigned(false) {}
+ };
+
+ Input input;
+ Output output;
+
+ GpgAction(QObject *parent = 0);
+ ~GpgAction();
+ void reset();
+ void start();
#ifdef QPIPE_SECURE
- void submitPassphrase(const QCA::SecureArray &a);
+ void submitPassphrase(const QCA::SecureArray &a);
#else
- void submitPassphrase(const QByteArray &a);
+ void submitPassphrase(const QByteArray &a);
#endif
public slots:
- QByteArray read();
- void write(const QByteArray &in);
- void endWrite();
- void cardOkay();
- QString readDiagnosticText();
+ QByteArray read();
+ void write(const QByteArray &in);
+ void endWrite();
+ void cardOkay();
+ QString readDiagnosticText();
signals:
- void readyRead();
- void bytesWritten(int bytes);
- void finished();
- void needPassphrase(const QString &keyId);
- void needCard();
- void readyReadDiagnosticText();
+ void readyRead();
+ void bytesWritten(int bytes);
+ void finished();
+ void needPassphrase(const QString &keyId);
+ void needCard();
+ void readyReadDiagnosticText();
private:
- void submitCommand(const QByteArray &a);
-
- // since str is taken as a value, it is ok to use the same variable for 'rest'
- QString nextArg(QString str, QString *rest = 0);
- void processStatusLine(const QString &line);
- void processResult(int code);
- void ensureDTextEmit();
-
- GPGProc proc;
- bool collectOutput, allowInput;
- LineConverter readConv, writeConv;
- bool readText, writeText;
- QByteArray buf_stdout, buf_stderr;
- bool useAux;
- QString passphraseKeyId;
- bool signing, decryptGood, signGood;
- GpgOp::Error curError;
- bool badPassphrase;
- bool need_submitPassphrase, need_cardOkay;
- QString diagnosticText;
- QCA::SafeTimer dtextTimer;
- bool utf8Output;
+ void submitCommand(const QByteArray &a);
+
+ // since str is taken as a value, it is ok to use the same variable for 'rest'
+ QString nextArg(QString str, QString *rest = 0);
+ void processStatusLine(const QString &line);
+ void processResult(int code);
+ void ensureDTextEmit();
+
+ GPGProc proc;
+ bool collectOutput, allowInput;
+ LineConverter readConv, writeConv;
+ bool readText, writeText;
+ QByteArray buf_stdout, buf_stderr;
+ bool useAux;
+ QString passphraseKeyId;
+ bool signing, decryptGood, signGood;
+ GpgOp::Error curError;
+ bool badPassphrase;
+ bool need_submitPassphrase, need_cardOkay;
+ QString diagnosticText;
+ QCA::SafeTimer dtextTimer;
+ bool utf8Output;
#ifdef GPG_PROFILE
- QTime timer;
+ QTime timer;
#endif
private slots:
- void t_dtext();
- void proc_error(gpgQCAPlugin::GPGProc::Error e);
- void proc_finished(int exitCode);
- void proc_readyReadStdout();
- void proc_readyReadStderr();
- void proc_readyReadStatusLines();
- void proc_bytesWrittenStdin(int bytes);
- void proc_bytesWrittenAux(int bytes);
- void proc_bytesWrittenCommand(int);
- void proc_debug(const QString &str);
- void appendDiagnosticText(const QString &line);
+ void t_dtext();
+ void proc_error(gpgQCAPlugin::GPGProc::Error e);
+ void proc_finished(int exitCode);
+ void proc_readyReadStdout();
+ void proc_readyReadStderr();
+ void proc_readyReadStatusLines();
+ void proc_bytesWrittenStdin(int bytes);
+ void proc_bytesWrittenAux(int bytes);
+ void proc_bytesWrittenCommand(int);
+ void proc_debug(const QString &str);
+ void appendDiagnosticText(const QString &line);
};
-
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/gpgop.cpp b/plugins/qca-gnupg/gpgop.cpp
index 811026bc..8048543a 100644
--- a/plugins/qca-gnupg/gpgop.cpp
+++ b/plugins/qca-gnupg/gpgop.cpp
@@ -1,489 +1,495 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include "gpgop_p.h"
#include "gpgop.h"
#include "gpgaction.h"
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
//----------------------------------------------------------------------------
// GpgOp
//----------------------------------------------------------------------------
GpgOp::Private::Private(GpgOp *_q)
- : QObject(_q)
- , sync(_q)
- , q(_q)
- , act(0)
- , waiting(false)
+ : QObject(_q)
+ , sync(_q)
+ , q(_q)
+ , act(0)
+ , waiting(false)
{
- reset(ResetAll);
+ reset(ResetAll);
}
GpgOp::Private::~Private()
{
- reset(ResetAll);
+ reset(ResetAll);
}
void GpgOp::Private::reset(ResetMode mode)
{
- if(act)
- {
- act->disconnect(this);
- act->setParent(0);
- act->deleteLater();
-
- act = 0;
- }
-
- if(mode >= ResetSessionAndData)
- {
- output = GpgAction::Output();
- result.clear();
- diagnosticText = QString();
- eventList.clear();
- }
-
- if(mode >= ResetAll)
- {
- opt_ascii = false;
- opt_noagent = false;
- opt_alwaystrust = false;
- opt_pubfile = QString();
- opt_secfile = QString();
- }
+ if (act) {
+ act->disconnect(this);
+ act->setParent(0);
+ act->deleteLater();
+
+ act = 0;
+ }
+
+ if (mode >= ResetSessionAndData) {
+ output = GpgAction::Output();
+ result.clear();
+ diagnosticText = QString();
+ eventList.clear();
+ }
+
+ if (mode >= ResetAll) {
+ opt_ascii = false;
+ opt_noagent = false;
+ opt_alwaystrust = false;
+ opt_pubfile = QString();
+ opt_secfile = QString();
+ }
}
void GpgOp::Private::make_act(GpgOp::Type _op)
{
- reset(ResetSessionAndData);
+ reset(ResetSessionAndData);
- op = _op;
+ op = _op;
- act = new GpgAction(this);
+ act = new GpgAction(this);
- connect(act, SIGNAL(readyRead()), SLOT(act_readyRead()));
- connect(act, SIGNAL(bytesWritten(int)), SLOT(act_bytesWritten(int)));
- connect(act, SIGNAL(needPassphrase(const QString &)), SLOT(act_needPassphrase(const QString &)));
- connect(act, SIGNAL(needCard()), SLOT(act_needCard()));
- connect(act, SIGNAL(finished()), SLOT(act_finished()));
- connect(act, SIGNAL(readyReadDiagnosticText()), SLOT(act_readyReadDiagnosticText()));
+ connect(act, SIGNAL(readyRead()), SLOT(act_readyRead()));
+ connect(act, SIGNAL(bytesWritten(int)), SLOT(act_bytesWritten(int)));
+ connect(act, SIGNAL(needPassphrase(QString)), SLOT(act_needPassphrase(QString)));
+ connect(act, SIGNAL(needCard()), SLOT(act_needCard()));
+ connect(act, SIGNAL(finished()), SLOT(act_finished()));
+ connect(act, SIGNAL(readyReadDiagnosticText()), SLOT(act_readyReadDiagnosticText()));
- act->input.bin = bin;
- act->input.op = op;
- act->input.opt_ascii = opt_ascii;
- act->input.opt_noagent = opt_noagent;
- act->input.opt_alwaystrust = opt_alwaystrust;
- act->input.opt_pubfile = opt_pubfile;
- act->input.opt_secfile = opt_secfile;
+ act->input.bin = bin;
+ act->input.op = op;
+ act->input.opt_ascii = opt_ascii;
+ act->input.opt_noagent = opt_noagent;
+ act->input.opt_alwaystrust = opt_alwaystrust;
+ act->input.opt_pubfile = opt_pubfile;
+ act->input.opt_secfile = opt_secfile;
}
void GpgOp::Private::eventReady(const GpgOp::Event &e)
{
- eventList += e;
- sync.conditionMet();
+ eventList += e;
+ sync.conditionMet();
}
void GpgOp::Private::eventReady(GpgOp::Event::Type type)
{
- GpgOp::Event e;
- e.type = type;
- eventReady(e);
+ GpgOp::Event e;
+ e.type = type;
+ eventReady(e);
}
void GpgOp::Private::eventReady(GpgOp::Event::Type type, int written)
{
- GpgOp::Event e;
- e.type = type;
- e.written = written;
- eventReady(e);
+ GpgOp::Event e;
+ e.type = type;
+ e.written = written;
+ eventReady(e);
}
void GpgOp::Private::eventReady(GpgOp::Event::Type type, const QString &keyId)
{
- GpgOp::Event e;
- e.type = type;
- e.keyId = keyId;
- eventReady(e);
+ GpgOp::Event e;
+ e.type = type;
+ e.keyId = keyId;
+ eventReady(e);
}
void GpgOp::Private::act_readyRead()
{
- if(waiting)
- eventReady(GpgOp::Event::ReadyRead);
- else
- emit q->readyRead();
+ if (waiting) {
+ eventReady(GpgOp::Event::ReadyRead);
+ } else {
+ emit q->readyRead();
+ }
}
void GpgOp::Private::act_bytesWritten(int bytes)
{
- if(waiting)
- eventReady(GpgOp::Event::BytesWritten, bytes);
- else
- emit q->bytesWritten(bytes);
+ if (waiting) {
+ eventReady(GpgOp::Event::BytesWritten, bytes);
+ } else {
+ emit q->bytesWritten(bytes);
+ }
}
void GpgOp::Private::act_needPassphrase(const QString &keyId)
{
- if(waiting)
- eventReady(GpgOp::Event::NeedPassphrase, keyId);
- else
- emit q->needPassphrase(keyId);
+ if (waiting) {
+ eventReady(GpgOp::Event::NeedPassphrase, keyId);
+ } else {
+ emit q->needPassphrase(keyId);
+ }
}
void GpgOp::Private::act_needCard()
{
- if(waiting)
- eventReady(GpgOp::Event::NeedCard);
- else
- emit q->needCard();
+ if (waiting) {
+ eventReady(GpgOp::Event::NeedCard);
+ } else {
+ emit q->needCard();
+ }
}
void GpgOp::Private::act_readyReadDiagnosticText()
{
- QString s = act->readDiagnosticText();
- //printf("dtext ready: [%s]\n", qPrintable(s));
- diagnosticText += s;
+ QString s = act->readDiagnosticText();
+ //printf("dtext ready: [%s]\n", qPrintable(s));
+ diagnosticText += s;
- if(waiting)
- eventReady(GpgOp::Event::ReadyReadDiagnosticText);
- else
- emit q->readyReadDiagnosticText();
+ if (waiting) {
+ eventReady(GpgOp::Event::ReadyReadDiagnosticText);
+ } else {
+ emit q->readyReadDiagnosticText();
+ }
}
void GpgOp::Private::act_finished()
{
#ifdef GPG_PROFILE
- if(op == GpgOp::Encrypt)
- printf("<< doEncrypt: %d >>\n", timer.elapsed());
+ if (op == GpgOp::Encrypt) {
+ printf("<< doEncrypt: %d >>\n", timer.elapsed());
+ }
#endif
- result = act->read();
- diagnosticText += act->readDiagnosticText();
- output = act->output;
-
- QMap<int, QString> errmap;
- errmap[GpgOp::ErrorProcess] = "ErrorProcess";
- errmap[GpgOp::ErrorPassphrase] = "ErrorPassphrase";
- errmap[GpgOp::ErrorFormat] = "ErrorFormat";
- errmap[GpgOp::ErrorSignerExpired] = "ErrorSignerExpired";
- errmap[GpgOp::ErrorEncryptExpired] = "ErrorEncryptExpired";
- errmap[GpgOp::ErrorEncryptUntrusted] = "ErrorEncryptUntrusted";
- errmap[GpgOp::ErrorEncryptInvalid] = "ErrorEncryptInvalid";
- errmap[GpgOp::ErrorDecryptNoKey] = "ErrorDecryptNoKey";
- errmap[GpgOp::ErrorUnknown] = "ErrorUnknown";
- if(output.success)
- diagnosticText += "GpgAction success\n";
- else
- diagnosticText += QString("GpgAction error: %1\n").arg(errmap[output.errorCode]);
-
- if(output.wasSigned)
- {
- QString s;
- if(output.verifyResult == GpgOp::VerifyGood)
- s = "VerifyGood";
- else if(output.verifyResult == GpgOp::VerifyBad)
- s = "VerifyBad";
- else
- s = "VerifyNoKey";
- diagnosticText += QString("wasSigned: verifyResult: %1\n").arg(s);
- }
-
- //printf("diagnosticText:\n%s", qPrintable(diagnosticText));
-
- reset(ResetSession);
-
- if(waiting)
- eventReady(GpgOp::Event::Finished);
- else
- emit q->finished();
+ result = act->read();
+ diagnosticText += act->readDiagnosticText();
+ output = act->output;
+
+ QMap<int, QString> errmap;
+ errmap[GpgOp::ErrorProcess] = "ErrorProcess";
+ errmap[GpgOp::ErrorPassphrase] = "ErrorPassphrase";
+ errmap[GpgOp::ErrorFormat] = "ErrorFormat";
+ errmap[GpgOp::ErrorSignerExpired] = "ErrorSignerExpired";
+ errmap[GpgOp::ErrorEncryptExpired] = "ErrorEncryptExpired";
+ errmap[GpgOp::ErrorEncryptUntrusted] = "ErrorEncryptUntrusted";
+ errmap[GpgOp::ErrorEncryptInvalid] = "ErrorEncryptInvalid";
+ errmap[GpgOp::ErrorDecryptNoKey] = "ErrorDecryptNoKey";
+ errmap[GpgOp::ErrorUnknown] = "ErrorUnknown";
+ if (output.success) {
+ diagnosticText += "GpgAction success\n";
+ } else {
+ diagnosticText += QString("GpgAction error: %1\n").arg(errmap[output.errorCode]);
+ }
+
+ if (output.wasSigned) {
+ QString s;
+ if (output.verifyResult == GpgOp::VerifyGood) {
+ s = "VerifyGood";
+ } else if (output.verifyResult == GpgOp::VerifyBad) {
+ s = "VerifyBad";
+ } else {
+ s = "VerifyNoKey";
+ }
+ diagnosticText += QString("wasSigned: verifyResult: %1\n").arg(s);
+ }
+
+ //printf("diagnosticText:\n%s", qPrintable(diagnosticText));
+
+ reset(ResetSession);
+
+ if (waiting) {
+ eventReady(GpgOp::Event::Finished);
+ } else {
+ emit q->finished();
+ }
}
GpgOp::GpgOp(const QString &bin, QObject *parent)
- :QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
- d->bin = bin;
+ d = new Private(this);
+ d->bin = bin;
}
GpgOp::~GpgOp()
{
- delete d;
+ delete d;
}
void GpgOp::reset()
{
- d->reset(ResetAll);
+ d->reset(ResetAll);
}
bool GpgOp::isActive() const
{
- return (d->act ? true : false);
+ return (d->act ? true : false);
}
GpgOp::Type GpgOp::op() const
{
- return d->op;
+ return d->op;
}
void GpgOp::setAsciiFormat(bool b)
{
- d->opt_ascii = b;
+ d->opt_ascii = b;
}
void GpgOp::setDisableAgent(bool b)
{
- d->opt_noagent = b;
+ d->opt_noagent = b;
}
void GpgOp::setAlwaysTrust(bool b)
{
- d->opt_alwaystrust = b;
+ d->opt_alwaystrust = b;
}
void GpgOp::setKeyrings(const QString &pubfile, const QString &secfile)
{
- d->opt_pubfile = pubfile;
- d->opt_secfile = secfile;
+ d->opt_pubfile = pubfile;
+ d->opt_secfile = secfile;
}
void GpgOp::doCheck()
{
- d->make_act(Check);
- d->act->start();
+ d->make_act(Check);
+ d->act->start();
}
void GpgOp::doSecretKeyringFile()
{
- d->make_act(SecretKeyringFile);
- d->act->start();
+ d->make_act(SecretKeyringFile);
+ d->act->start();
}
void GpgOp::doPublicKeyringFile()
{
- d->make_act(PublicKeyringFile);
- d->act->start();
+ d->make_act(PublicKeyringFile);
+ d->act->start();
}
void GpgOp::doSecretKeys()
{
- d->make_act(SecretKeys);
- d->act->start();
+ d->make_act(SecretKeys);
+ d->act->start();
}
void GpgOp::doPublicKeys()
{
- d->make_act(PublicKeys);
- d->act->start();
+ d->make_act(PublicKeys);
+ d->act->start();
}
void GpgOp::doEncrypt(const QStringList &recip_ids)
{
#ifdef GPG_PROFILE
- d->timer.start();
- printf("<< doEncrypt >>\n");
+ d->timer.start();
+ printf("<< doEncrypt >>\n");
#endif
- d->make_act(Encrypt);
- d->act->input.recip_ids = recip_ids;
- d->act->start();
+ d->make_act(Encrypt);
+ d->act->input.recip_ids = recip_ids;
+ d->act->start();
}
void GpgOp::doDecrypt()
{
- d->make_act(Decrypt);
- d->act->start();
+ d->make_act(Decrypt);
+ d->act->start();
}
void GpgOp::doSign(const QString &signer_id)
{
- d->make_act(Sign);
- d->act->input.signer_id = signer_id;
- d->act->start();
+ d->make_act(Sign);
+ d->act->input.signer_id = signer_id;
+ d->act->start();
}
void GpgOp::doSignAndEncrypt(const QString &signer_id, const QStringList &recip_ids)
{
- d->make_act(SignAndEncrypt);
- d->act->input.signer_id = signer_id;
- d->act->input.recip_ids = recip_ids;
- d->act->start();
+ d->make_act(SignAndEncrypt);
+ d->act->input.signer_id = signer_id;
+ d->act->input.recip_ids = recip_ids;
+ d->act->start();
}
void GpgOp::doSignClearsign(const QString &signer_id)
{
- d->make_act(SignClearsign);
- d->act->input.signer_id = signer_id;
- d->act->start();
+ d->make_act(SignClearsign);
+ d->act->input.signer_id = signer_id;
+ d->act->start();
}
void GpgOp::doSignDetached(const QString &signer_id)
{
- d->make_act(SignDetached);
- d->act->input.signer_id = signer_id;
- d->act->start();
+ d->make_act(SignDetached);
+ d->act->input.signer_id = signer_id;
+ d->act->start();
}
void GpgOp::doVerify()
{
- d->make_act(Verify);
- d->act->start();
+ d->make_act(Verify);
+ d->act->start();
}
void GpgOp::doVerifyDetached(const QByteArray &sig)
{
- d->make_act(VerifyDetached);
- d->act->input.sig = sig;
- d->act->start();
+ d->make_act(VerifyDetached);
+ d->act->input.sig = sig;
+ d->act->start();
}
void GpgOp::doImport(const QByteArray &in)
{
- d->make_act(Import);
- d->act->input.inkey = in;
- d->act->start();
+ d->make_act(Import);
+ d->act->input.inkey = in;
+ d->act->start();
}
void GpgOp::doExport(const QString &key_id)
{
- d->make_act(Export);
- d->act->input.export_key_id = key_id;
- d->act->start();
+ d->make_act(Export);
+ d->act->input.export_key_id = key_id;
+ d->act->start();
}
void GpgOp::doDeleteKey(const QString &key_fingerprint)
{
- d->make_act(DeleteKey);
- d->act->input.delete_key_fingerprint = key_fingerprint;
- d->act->start();
+ d->make_act(DeleteKey);
+ d->act->input.delete_key_fingerprint = key_fingerprint;
+ d->act->start();
}
#ifdef QPIPE_SECURE
void GpgOp::submitPassphrase(const QCA::SecureArray &a)
#else
void GpgOp::submitPassphrase(const QByteArray &a)
#endif
{
- d->act->submitPassphrase(a);
+ d->act->submitPassphrase(a);
}
void GpgOp::cardOkay()
{
- d->act->cardOkay();
+ d->act->cardOkay();
}
QByteArray GpgOp::read()
{
- if(d->act)
- {
- return d->act->read();
- }
- else
- {
- QByteArray a = d->result;
- d->result.clear();
- return a;
- }
+ if (d->act) {
+ return d->act->read();
+ } else {
+ QByteArray a = d->result;
+ d->result.clear();
+ return a;
+ }
}
void GpgOp::write(const QByteArray &in)
{
- d->act->write(in);
+ d->act->write(in);
}
void GpgOp::endWrite()
{
- d->act->endWrite();
+ d->act->endWrite();
}
QString GpgOp::readDiagnosticText()
{
- QString s = d->diagnosticText;
- d->diagnosticText = QString();
- return s;
+ QString s = d->diagnosticText;
+ d->diagnosticText = QString();
+ return s;
}
GpgOp::Event GpgOp::waitForEvent(int msecs)
{
- if(!d->eventList.isEmpty())
- return d->eventList.takeFirst();
+ if (!d->eventList.isEmpty()) {
+ return d->eventList.takeFirst();
+ }
- if(!d->act)
- return GpgOp::Event();
+ if (!d->act) {
+ return GpgOp::Event();
+ }
- d->waiting = true;
- d->sync.waitForCondition(msecs);
- d->waiting = false;
- if(!d->eventList.isEmpty())
- return d->eventList.takeFirst();
- else
- return GpgOp::Event();
+ d->waiting = true;
+ d->sync.waitForCondition(msecs);
+ d->waiting = false;
+ if (!d->eventList.isEmpty()) {
+ return d->eventList.takeFirst();
+ } else {
+ return GpgOp::Event();
+ }
}
bool GpgOp::success() const
{
- return d->output.success;
+ return d->output.success;
}
GpgOp::Error GpgOp::errorCode() const
{
- return d->output.errorCode;
+ return d->output.errorCode;
}
GpgOp::KeyList GpgOp::keys() const
{
- return d->output.keys;
+ return d->output.keys;
}
QString GpgOp::keyringFile() const
{
- return d->output.keyringFile;
+ return d->output.keyringFile;
}
QString GpgOp::homeDir() const
{
- return d->output.homeDir;
+ return d->output.homeDir;
}
QString GpgOp::encryptedToId() const
{
- return d->output.encryptedToId;
+ return d->output.encryptedToId;
}
bool GpgOp::wasSigned() const
{
- return d->output.wasSigned;
+ return d->output.wasSigned;
}
QString GpgOp::signerId() const
{
- return d->output.signerId;
+ return d->output.signerId;
}
QDateTime GpgOp::timestamp() const
{
- return d->output.timestamp;
+ return d->output.timestamp;
}
GpgOp::VerifyResult GpgOp::verifyResult() const
{
- return d->output.verifyResult;
+ return d->output.verifyResult;
}
}
diff --git a/plugins/qca-gnupg/gpgop.h b/plugins/qca-gnupg/gpgop.h
index 7b11c6ea..5d46800f 100644
--- a/plugins/qca-gnupg/gpgop.h
+++ b/plugins/qca-gnupg/gpgop.h
@@ -1,212 +1,207 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#ifndef GPGOP_H
#define GPGOP_H
#include <QtCrypto>
#include "qpipe.h"
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
class GpgOp : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum Type
- {
- Check, // --version
- SecretKeyringFile, // --list-secret-keys
- PublicKeyringFile, // --list-public-keys
- SecretKeys, // --fixed-list-mode --with-colons --list-secret-keys
- PublicKeys, // --fixed-list-mode --with-colons --list-public-keys
- Encrypt, // --encrypt
- Decrypt, // --decrypt
- Sign, // --sign
- SignAndEncrypt, // --sign --encrypt
- SignClearsign, // --clearsign
- SignDetached, // --detach-sign
- Verify, // --verify
- VerifyDetached, // --verify
- Import, // --import
- Export, // --export
- DeleteKey // --delete-key
- };
-
- enum VerifyResult
- {
- VerifyGood, // good sig
- VerifyBad, // bad sig
- VerifyNoKey // we don't have signer's public key
- };
-
- enum Error
- {
- ErrorProcess, // startup, process, or ipc error
- ErrorPassphrase, // passphrase was either wrong or not provided
- ErrorFormat, // input format was bad
- ErrorSignerExpired, // signing key is expired
- ErrorEncryptExpired, // encrypting key is expired
- ErrorEncryptUntrusted, // encrypting key is untrusted
- ErrorEncryptInvalid, // encrypting key is invalid in some way
- ErrorDecryptNoKey, // missing decrypt key
- ErrorUnknown, // other error
- ErrorSignerRevoked, // signing key is revoked
- ErrorSignatureExpired, // signature is expired
- ErrorEncryptRevoked // encrypting key is revoked
- };
-
- class Event
- {
- public:
- enum Type
- {
- None,
- ReadyRead,
- BytesWritten,
- Finished,
- NeedPassphrase,
- NeedCard,
- ReadyReadDiagnosticText
- };
-
- Type type;
- int written; // BytesWritten
- QString keyId; // NeedPassphrase
-
- Event() : type(None), written(0) {}
- };
-
- class KeyItem
- {
- public:
- enum Type
- {
- RSA,
- DSA,
- ElGamal,
- Unknown
- };
-
- enum Caps
- {
- Encrypt = 0x01,
- Sign = 0x02,
- Certify = 0x04,
- Auth = 0x08
- };
-
- QString id;
- Type type;
- int bits;
- QDateTime creationDate;
- QDateTime expirationDate;
- int caps; // flags OR'd together
- QString fingerprint;
-
- KeyItem() : type(Unknown), bits(0), caps(0) {}
- };
-
- class Key
- {
- public:
- QList<KeyItem> keyItems; // first item is primary
- QStringList userIds;
- bool isTrusted;
-
- Key() : isTrusted(false) {}
- };
- typedef QList<Key> KeyList;
-
- explicit GpgOp(const QString &bin, QObject *parent = 0);
- ~GpgOp();
-
- void reset();
-
- bool isActive() const;
- Type op() const;
-
- void setAsciiFormat(bool b);
- void setDisableAgent(bool b);
- void setAlwaysTrust(bool b);
- void setKeyrings(const QString &pubfile, const QString &secfile); // for keylists and import
-
- void doCheck();
- void doSecretKeyringFile();
- void doPublicKeyringFile();
- void doSecretKeys();
- void doPublicKeys();
- void doEncrypt(const QStringList &recip_ids);
- void doDecrypt();
- void doSign(const QString &signer_id);
- void doSignAndEncrypt(const QString &signer_id, const QStringList &recip_ids);
- void doSignClearsign(const QString &signer_id);
- void doSignDetached(const QString &signer_id);
- void doVerify();
- void doVerifyDetached(const QByteArray &sig);
- void doImport(const QByteArray &in);
- void doExport(const QString &key_id);
- void doDeleteKey(const QString &key_fingerprint);
+ enum Type {
+ Check, // --version
+ SecretKeyringFile, // --list-secret-keys
+ PublicKeyringFile, // --list-public-keys
+ SecretKeys, // --fixed-list-mode --with-colons --list-secret-keys
+ PublicKeys, // --fixed-list-mode --with-colons --list-public-keys
+ Encrypt, // --encrypt
+ Decrypt, // --decrypt
+ Sign, // --sign
+ SignAndEncrypt, // --sign --encrypt
+ SignClearsign, // --clearsign
+ SignDetached, // --detach-sign
+ Verify, // --verify
+ VerifyDetached, // --verify
+ Import, // --import
+ Export, // --export
+ DeleteKey // --delete-key
+ };
+
+ enum VerifyResult {
+ VerifyGood, // good sig
+ VerifyBad, // bad sig
+ VerifyNoKey // we don't have signer's public key
+ };
+
+ enum Error {
+ ErrorProcess, // startup, process, or ipc error
+ ErrorPassphrase, // passphrase was either wrong or not provided
+ ErrorFormat, // input format was bad
+ ErrorSignerExpired, // signing key is expired
+ ErrorEncryptExpired, // encrypting key is expired
+ ErrorEncryptUntrusted, // encrypting key is untrusted
+ ErrorEncryptInvalid, // encrypting key is invalid in some way
+ ErrorDecryptNoKey, // missing decrypt key
+ ErrorUnknown, // other error
+ ErrorSignerRevoked, // signing key is revoked
+ ErrorSignatureExpired, // signature is expired
+ ErrorEncryptRevoked // encrypting key is revoked
+ };
+
+ class Event
+ {
+ public:
+ enum Type {
+ None,
+ ReadyRead,
+ BytesWritten,
+ Finished,
+ NeedPassphrase,
+ NeedCard,
+ ReadyReadDiagnosticText
+ };
+
+ Type type;
+ int written; // BytesWritten
+ QString keyId; // NeedPassphrase
+
+ Event() : type(None), written(0) {}
+ };
+
+ class KeyItem
+ {
+ public:
+ enum Type {
+ RSA,
+ DSA,
+ ElGamal,
+ Unknown
+ };
+
+ enum Caps {
+ Encrypt = 0x01,
+ Sign = 0x02,
+ Certify = 0x04,
+ Auth = 0x08
+ };
+
+ QString id;
+ Type type;
+ int bits;
+ QDateTime creationDate;
+ QDateTime expirationDate;
+ int caps; // flags OR'd together
+ QString fingerprint;
+
+ KeyItem() : type(Unknown), bits(0), caps(0) {}
+ };
+
+ class Key
+ {
+ public:
+ QList<KeyItem> keyItems; // first item is primary
+ QStringList userIds;
+ bool isTrusted;
+
+ Key() : isTrusted(false) {}
+ };
+ typedef QList<Key> KeyList;
+
+ explicit GpgOp(const QString &bin, QObject *parent = 0);
+ ~GpgOp();
+
+ void reset();
+
+ bool isActive() const;
+ Type op() const;
+
+ void setAsciiFormat(bool b);
+ void setDisableAgent(bool b);
+ void setAlwaysTrust(bool b);
+ void setKeyrings(const QString &pubfile, const QString &secfile); // for keylists and import
+
+ void doCheck();
+ void doSecretKeyringFile();
+ void doPublicKeyringFile();
+ void doSecretKeys();
+ void doPublicKeys();
+ void doEncrypt(const QStringList &recip_ids);
+ void doDecrypt();
+ void doSign(const QString &signer_id);
+ void doSignAndEncrypt(const QString &signer_id, const QStringList &recip_ids);
+ void doSignClearsign(const QString &signer_id);
+ void doSignDetached(const QString &signer_id);
+ void doVerify();
+ void doVerifyDetached(const QByteArray &sig);
+ void doImport(const QByteArray &in);
+ void doExport(const QString &key_id);
+ void doDeleteKey(const QString &key_fingerprint);
#ifdef QPIPE_SECURE
- void submitPassphrase(const QCA::SecureArray &a);
+ void submitPassphrase(const QCA::SecureArray &a);
#else
- void submitPassphrase(const QByteArray &a);
+ void submitPassphrase(const QByteArray &a);
#endif
- void cardOkay();
-
- // for encrypt, decrypt, sign, verify, export
- QByteArray read();
- void write(const QByteArray &in);
- void endWrite();
-
- QString readDiagnosticText();
-
- // for synchronous operation
- Event waitForEvent(int msecs = -1);
-
- // results
- bool success() const;
- Error errorCode() const;
- KeyList keys() const; // Keys
- QString keyringFile() const; // KeyringFile
- QString homeDir() const; // GnuPG home directory
- QString encryptedToId() const; // Decrypt (for ErrorDecryptNoKey)
- bool wasSigned() const; // Decrypt
- QString signerId() const; // Verify
- QDateTime timestamp() const; // Verify
- VerifyResult verifyResult() const; // Verify
+ void cardOkay();
+
+ // for encrypt, decrypt, sign, verify, export
+ QByteArray read();
+ void write(const QByteArray &in);
+ void endWrite();
+
+ QString readDiagnosticText();
+
+ // for synchronous operation
+ Event waitForEvent(int msecs = -1);
+
+ // results
+ bool success() const;
+ Error errorCode() const;
+ KeyList keys() const; // Keys
+ QString keyringFile() const; // KeyringFile
+ QString homeDir() const; // GnuPG home directory
+ QString encryptedToId() const; // Decrypt (for ErrorDecryptNoKey)
+ bool wasSigned() const; // Decrypt
+ QString signerId() const; // Verify
+ QDateTime timestamp() const; // Verify
+ VerifyResult verifyResult() const; // Verify
Q_SIGNALS:
- void readyRead();
- void bytesWritten(int bytes);
- void finished();
- void needPassphrase(const QString &keyId);
- void needCard();
- void readyReadDiagnosticText();
+ void readyRead();
+ void bytesWritten(int bytes);
+ void finished();
+ void needPassphrase(const QString &keyId);
+ void needCard();
+ void readyReadDiagnosticText();
private:
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
}
#endif
diff --git a/plugins/qca-gnupg/gpgop_p.h b/plugins/qca-gnupg/gpgop_p.h
index 541f5947..52a8d022 100644
--- a/plugins/qca-gnupg/gpgop_p.h
+++ b/plugins/qca-gnupg/gpgop_p.h
@@ -1,75 +1,75 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#pragma once
#include "gpgop.h"
#include "gpgaction.h"
#include <QObject>
-namespace gpgQCAPlugin {
-
-enum ResetMode
+namespace gpgQCAPlugin
{
- ResetSession = 0,
- ResetSessionAndData = 1,
- ResetAll = 2
+
+enum ResetMode {
+ ResetSession = 0,
+ ResetSessionAndData = 1,
+ ResetAll = 2
};
class GpgOp::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- QCA::Synchronizer sync;
- GpgOp *q;
- GpgAction *act;
- QString bin;
- GpgOp::Type op;
- GpgAction::Output output;
- QByteArray result;
- QString diagnosticText;
- QList<GpgOp::Event> eventList;
- bool waiting;
+ QCA::Synchronizer sync;
+ GpgOp *q;
+ GpgAction *act;
+ QString bin;
+ GpgOp::Type op;
+ GpgAction::Output output;
+ QByteArray result;
+ QString diagnosticText;
+ QList<GpgOp::Event> eventList;
+ bool waiting;
- bool opt_ascii, opt_noagent, opt_alwaystrust;
- QString opt_pubfile, opt_secfile;
+ bool opt_ascii, opt_noagent, opt_alwaystrust;
+ QString opt_pubfile, opt_secfile;
#ifdef GPG_PROFILE
- QTime timer;
+ QTime timer;
#endif
- Private(GpgOp *_q);
- ~Private();
- void reset(ResetMode mode);
- void make_act(GpgOp::Type _op);
- void eventReady(const GpgOp::Event &e);
- void eventReady(GpgOp::Event::Type type);
- void eventReady(GpgOp::Event::Type type, int written);
- void eventReady(GpgOp::Event::Type type, const QString &keyId);
+ Private(GpgOp *_q);
+ ~Private();
+ void reset(ResetMode mode);
+ void make_act(GpgOp::Type _op);
+ void eventReady(const GpgOp::Event &e);
+ void eventReady(GpgOp::Event::Type type);
+ void eventReady(GpgOp::Event::Type type, int written);
+ void eventReady(GpgOp::Event::Type type, const QString &keyId);
public slots:
- void act_readyRead();
- void act_bytesWritten(int bytes);
- void act_needPassphrase(const QString &keyId);
- void act_needCard();
- void act_readyReadDiagnosticText();
- void act_finished();
+ void act_readyRead();
+ void act_bytesWritten(int bytes);
+ void act_needPassphrase(const QString &keyId);
+ void act_needCard();
+ void act_readyReadDiagnosticText();
+ void act_finished();
};
} // namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/gpgproc/gpgproc.cpp b/plugins/qca-gnupg/gpgproc/gpgproc.cpp
index 8ce6739f..09c7829e 100644
--- a/plugins/qca-gnupg/gpgproc/gpgproc.cpp
+++ b/plugins/qca-gnupg/gpgproc/gpgproc.cpp
@@ -1,682 +1,689 @@
/*
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include "gpgproc_p.h"
#ifdef Q_OS_MAC
#define QT_PIPE_HACK
#endif
-
using namespace QCA;
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
void releaseAndDeleteLater(QObject *owner, QObject *obj)
{
- obj->disconnect(owner);
- obj->setParent(0);
- obj->deleteLater();
+ obj->disconnect(owner);
+ obj->setParent(0);
+ obj->deleteLater();
}
-
GPGProc::Private::Private(GPGProc *_q)
- : QObject(_q)
- , q(_q)
- , pipeAux(this)
- , pipeCommand(this)
- , pipeStatus(this)
- , startTrigger(this)
- , doneTrigger(this)
+ : QObject(_q)
+ , q(_q)
+ , pipeAux(this)
+ , pipeCommand(this)
+ , pipeStatus(this)
+ , startTrigger(this)
+ , doneTrigger(this)
{
- qRegisterMetaType<gpgQCAPlugin::GPGProc::Error>("gpgQCAPlugin::GPGProc::Error");
+ qRegisterMetaType<gpgQCAPlugin::GPGProc::Error>("gpgQCAPlugin::GPGProc::Error");
- proc = 0;
+ proc = 0;
#ifdef QPROC_SIGNAL_RELAY
- proc_relay = 0;
+ proc_relay = 0;
#endif
- startTrigger.setSingleShot(true);
- doneTrigger.setSingleShot(true);
+ startTrigger.setSingleShot(true);
+ doneTrigger.setSingleShot(true);
- connect(&pipeAux.writeEnd(), SIGNAL(bytesWritten(int)), SLOT(aux_written(int)));
- connect(&pipeAux.writeEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(aux_error(QCA::QPipeEnd::Error)));
- connect(&pipeCommand.writeEnd(), SIGNAL(bytesWritten(int)), SLOT(command_written(int)));
- connect(&pipeCommand.writeEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(command_error(QCA::QPipeEnd::Error)));
- connect(&pipeStatus.readEnd(), SIGNAL(readyRead()), SLOT(status_read()));
- connect(&pipeStatus.readEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(status_error(QCA::QPipeEnd::Error)));
- connect(&startTrigger, SIGNAL(timeout()), SLOT(doStart()));
- connect(&doneTrigger, SIGNAL(timeout()), SLOT(doTryDone()));
+ connect(&pipeAux.writeEnd(), SIGNAL(bytesWritten(int)), SLOT(aux_written(int)));
+ connect(&pipeAux.writeEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(aux_error(QCA::QPipeEnd::Error)));
+ connect(&pipeCommand.writeEnd(), SIGNAL(bytesWritten(int)), SLOT(command_written(int)));
+ connect(&pipeCommand.writeEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(command_error(QCA::QPipeEnd::Error)));
+ connect(&pipeStatus.readEnd(), SIGNAL(readyRead()), SLOT(status_read()));
+ connect(&pipeStatus.readEnd(), SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(status_error(QCA::QPipeEnd::Error)));
+ connect(&startTrigger, SIGNAL(timeout()), SLOT(doStart()));
+ connect(&doneTrigger, SIGNAL(timeout()), SLOT(doTryDone()));
- reset(ResetSessionAndData);
+ reset(ResetSessionAndData);
}
GPGProc::Private::~Private()
{
- reset(ResetSession);
+ reset(ResetSession);
}
void GPGProc::Private::closePipes()
{
#ifdef QT_PIPE_HACK
- pipeAux.readEnd().reset();
- pipeCommand.readEnd().reset();
- pipeStatus.writeEnd().reset();
+ pipeAux.readEnd().reset();
+ pipeCommand.readEnd().reset();
+ pipeStatus.writeEnd().reset();
#endif
- pipeAux.reset();
- pipeCommand.reset();
- pipeStatus.reset();
+ pipeAux.reset();
+ pipeCommand.reset();
+ pipeStatus.reset();
}
void GPGProc::Private::reset(ResetMode mode)
{
#ifndef QT_PIPE_HACK
- closePipes();
+ closePipes();
#endif
- if(proc)
- {
- proc->disconnect(this);
-
- if(proc->state() != QProcess::NotRunning)
- {
- // Before try to correct end proccess
- // Terminate if failed
- proc->close();
- bool finished = proc->waitForFinished(5000);
- if (!finished)
- proc->terminate();
- }
-
- proc->setParent(0);
+ if (proc) {
+ proc->disconnect(this);
+
+ if (proc->state() != QProcess::NotRunning) {
+ // Before try to correct end proccess
+ // Terminate if failed
+ proc->close();
+ bool finished = proc->waitForFinished(5000);
+ if (!finished) {
+ proc->terminate();
+ }
+ }
+
+ proc->setParent(0);
#ifdef QPROC_SIGNAL_RELAY
- releaseAndDeleteLater(this, proc_relay);
- proc_relay = 0;
- delete proc; // should be safe to do thanks to relay
+ releaseAndDeleteLater(this, proc_relay);
+ proc_relay = 0;
+ delete proc; // should be safe to do thanks to relay
#else
- proc->deleteLater();
+ proc->deleteLater();
#endif
- proc = 0;
- }
+ proc = 0;
+ }
#ifdef QT_PIPE_HACK
- closePipes();
+ closePipes();
#endif
- startTrigger.stop();
- doneTrigger.stop();
+ startTrigger.stop();
+ doneTrigger.stop();
- pre_stdin.clear();
- pre_aux.clear();
- pre_command.clear();
- pre_stdin_close = false;
- pre_aux_close = false;
- pre_command_close = false;
+ pre_stdin.clear();
+ pre_aux.clear();
+ pre_command.clear();
+ pre_stdin_close = false;
+ pre_aux_close = false;
+ pre_command_close = false;
- need_status = false;
- fin_process = false;
- fin_status = false;
+ need_status = false;
+ fin_process = false;
+ fin_status = false;
- if(mode >= ResetSessionAndData)
- {
- statusBuf.clear();
- statusLines.clear();
- leftover_stdout.clear();
- leftover_stderr.clear();
- error = GPGProc::FailedToStart;
- exitCode = -1;
- }
+ if (mode >= ResetSessionAndData) {
+ statusBuf.clear();
+ statusLines.clear();
+ leftover_stdout.clear();
+ leftover_stderr.clear();
+ error = GPGProc::FailedToStart;
+ exitCode = -1;
+ }
}
bool GPGProc::Private::setupPipes(bool makeAux)
{
- if(makeAux && !pipeAux.create())
- {
- closePipes();
- emit q->debug("Error creating pipeAux");
- return false;
- }
+ if (makeAux && !pipeAux.create()) {
+ closePipes();
+ emit q->debug("Error creating pipeAux");
+ return false;
+ }
#ifdef QPIPE_SECURE
- if(!pipeCommand.create(true)) // secure
+ if (!pipeCommand.create(true)) // secure
#else
- if(!pipeCommand.create())
+ if (!pipeCommand.create())
#endif
- {
- closePipes();
- emit q->debug("Error creating pipeCommand");
- return false;
- }
+ {
+ closePipes();
+ emit q->debug("Error creating pipeCommand");
+ return false;
+ }
- if(!pipeStatus.create())
- {
- closePipes();
- emit q->debug("Error creating pipeStatus");
- return false;
- }
+ if (!pipeStatus.create()) {
+ closePipes();
+ emit q->debug("Error creating pipeStatus");
+ return false;
+ }
- return true;
+ return true;
}
void GPGProc::Private::setupArguments()
{
- QStringList fullargs;
- fullargs += "--no-tty";
+ QStringList fullargs;
+ fullargs += "--no-tty";
- if(mode == ExtendedMode)
- {
- fullargs += "--enable-special-filenames";
+ if (mode == ExtendedMode) {
+ fullargs += "--enable-special-filenames";
- fullargs += "--status-fd";
- fullargs += QString::number(pipeStatus.writeEnd().idAsInt());
+ fullargs += "--status-fd";
+ fullargs += QString::number(pipeStatus.writeEnd().idAsInt());
- fullargs += "--command-fd";
- fullargs += QString::number(pipeCommand.readEnd().idAsInt());
- }
+ fullargs += "--command-fd";
+ fullargs += QString::number(pipeCommand.readEnd().idAsInt());
+ }
- for(int n = 0; n < args.count(); ++n)
- {
- QString a = args[n];
- if(mode == ExtendedMode && a == "-&?")
- fullargs += QString("-&") + QString::number(pipeAux.readEnd().idAsInt());
- else
- fullargs += a;
- }
+ for (int n = 0; n < args.count(); ++n) {
+ QString a = args[n];
+ if (mode == ExtendedMode && a == "-&?") {
+ fullargs += QString("-&") + QString::number(pipeAux.readEnd().idAsInt());
+ } else {
+ fullargs += a;
+ }
+ }
- QString fullcmd = fullargs.join(" ");
- emit q->debug(QString("Running: [") + bin + ' ' + fullcmd + ']');
+ QString fullcmd = fullargs.join(" ");
+ emit q->debug(QString("Running: [") + bin + ' ' + fullcmd + ']');
- args = fullargs;
+ args = fullargs;
}
void GPGProc::Private::doStart()
{
#ifdef Q_OS_WIN
- // Note: for unix, inheritability is set in SProcess
- if(pipeAux.readEnd().isValid())
- pipeAux.readEnd().setInheritable(true);
- if(pipeCommand.readEnd().isValid())
- pipeCommand.readEnd().setInheritable(true);
- if(pipeStatus.writeEnd().isValid())
- pipeStatus.writeEnd().setInheritable(true);
+ // Note: for unix, inheritability is set in SProcess
+ if (pipeAux.readEnd().isValid()) {
+ pipeAux.readEnd().setInheritable(true);
+ }
+ if (pipeCommand.readEnd().isValid()) {
+ pipeCommand.readEnd().setInheritable(true);
+ }
+ if (pipeStatus.writeEnd().isValid()) {
+ pipeStatus.writeEnd().setInheritable(true);
+ }
#endif
- setupArguments();
+ setupArguments();
- proc->start(bin, args);
- proc->waitForStarted();
+ proc->start(bin, args);
+ proc->waitForStarted();
- pipeAux.readEnd().close();
- pipeCommand.readEnd().close();
- pipeStatus.writeEnd().close();
+ pipeAux.readEnd().close();
+ pipeCommand.readEnd().close();
+ pipeStatus.writeEnd().close();
}
void GPGProc::Private::aux_written(int x)
{
- emit q->bytesWrittenAux(x);
+ emit q->bytesWrittenAux(x);
}
void GPGProc::Private::aux_error(QCA::QPipeEnd::Error)
{
- emit q->debug("Aux: Pipe error");
- reset(ResetSession);
- emit q->error(GPGProc::ErrorWrite);
+ emit q->debug("Aux: Pipe error");
+ reset(ResetSession);
+ emit q->error(GPGProc::ErrorWrite);
}
void GPGProc::Private::command_written(int x)
{
- emit q->bytesWrittenCommand(x);
+ emit q->bytesWrittenCommand(x);
}
void GPGProc::Private::command_error(QCA::QPipeEnd::Error)
{
- emit q->debug("Command: Pipe error");
- reset(ResetSession);
- emit q->error(GPGProc::ErrorWrite);
+ emit q->debug("Command: Pipe error");
+ reset(ResetSession);
+ emit q->error(GPGProc::ErrorWrite);
}
void GPGProc::Private::status_read()
{
- if(readAndProcessStatusData())
- emit q->readyReadStatusLines();
+ if (readAndProcessStatusData()) {
+ emit q->readyReadStatusLines();
+ }
}
void GPGProc::Private::status_error(QCA::QPipeEnd::Error e)
{
- if(e == QPipeEnd::ErrorEOF)
- emit q->debug("Status: Closed (EOF)");
- else
- emit q->debug("Status: Closed (gone)");
+ if (e == QPipeEnd::ErrorEOF) {
+ emit q->debug("Status: Closed (EOF)");
+ } else {
+ emit q->debug("Status: Closed (gone)");
+ }
- fin_status = true;
- doTryDone();
+ fin_status = true;
+ doTryDone();
}
void GPGProc::Private::proc_started()
{
- emit q->debug("Process started");
-
- // Note: we don't close these here anymore. instead we
- // do it just after calling proc->start().
- // close these, we don't need them
- /*pipeAux.readEnd().close();
- pipeCommand.readEnd().close();
- pipeStatus.writeEnd().close();*/
-
- // do the pre* stuff
- if(!pre_stdin.isEmpty())
- {
- proc->write(pre_stdin);
- pre_stdin.clear();
- }
- if(!pre_aux.isEmpty())
- {
- pipeAux.writeEnd().write(pre_aux);
- pre_aux.clear();
- }
- if(!pre_command.isEmpty())
- {
+ emit q->debug("Process started");
+
+ // Note: we don't close these here anymore. instead we
+ // do it just after calling proc->start().
+ // close these, we don't need them
+ /*pipeAux.readEnd().close();
+ pipeCommand.readEnd().close();
+ pipeStatus.writeEnd().close();*/
+
+ // do the pre* stuff
+ if (!pre_stdin.isEmpty()) {
+ proc->write(pre_stdin);
+ pre_stdin.clear();
+ }
+ if (!pre_aux.isEmpty()) {
+ pipeAux.writeEnd().write(pre_aux);
+ pre_aux.clear();
+ }
+ if (!pre_command.isEmpty()) {
#ifdef QPIPE_SECURE
- pipeCommand.writeEnd().writeSecure(pre_command);
+ pipeCommand.writeEnd().writeSecure(pre_command);
#else
- pipeCommand.writeEnd().write(pre_command);
+ pipeCommand.writeEnd().write(pre_command);
#endif
- pre_command.clear();
- }
+ pre_command.clear();
+ }
- if(pre_stdin_close)
- {
- proc->waitForBytesWritten();
- proc->closeWriteChannel();
- }
+ if (pre_stdin_close) {
+ proc->waitForBytesWritten();
+ proc->closeWriteChannel();
+ }
- if(pre_aux_close)
- pipeAux.writeEnd().close();
- if(pre_command_close)
- pipeCommand.writeEnd().close();
+ if (pre_aux_close) {
+ pipeAux.writeEnd().close();
+ }
+ if (pre_command_close) {
+ pipeCommand.writeEnd().close();
+ }
}
void GPGProc::Private::proc_readyReadStandardOutput()
{
- emit q->readyReadStdout();
+ emit q->readyReadStdout();
}
void GPGProc::Private::proc_readyReadStandardError()
{
- emit q->readyReadStderr();
+ emit q->readyReadStderr();
}
void GPGProc::Private::proc_bytesWritten(qint64 lx)
{
- int x = (int)lx;
- emit q->bytesWrittenStdin(x);
+ int x = (int)lx;
+ emit q->bytesWrittenStdin(x);
}
void GPGProc::Private::proc_finished(int x)
{
- emit q->debug(QString("Process finished: %1").arg(x));
- exitCode = x;
+ emit q->debug(QString("Process finished: %1").arg(x));
+ exitCode = x;
- fin_process = true;
- fin_process_success = true;
+ fin_process = true;
+ fin_process_success = true;
- if(need_status && !fin_status)
- {
- pipeStatus.readEnd().finalize();
- fin_status = true;
- if(readAndProcessStatusData())
- {
- doneTrigger.start();
- emit q->readyReadStatusLines();
- return;
- }
- }
+ if (need_status && !fin_status) {
+ pipeStatus.readEnd().finalize();
+ fin_status = true;
+ if (readAndProcessStatusData()) {
+ doneTrigger.start();
+ emit q->readyReadStatusLines();
+ return;
+ }
+ }
- doTryDone();
+ doTryDone();
}
void GPGProc::Private::proc_error(QProcess::ProcessError x)
{
- QMap<int, QString> errmap;
- errmap[QProcess::FailedToStart] = "FailedToStart";
- errmap[QProcess::Crashed] = "Crashed";
- errmap[QProcess::Timedout] = "Timedout";
- errmap[QProcess::WriteError] = "WriteError";
- errmap[QProcess::ReadError] = "ReadError";
- errmap[QProcess::UnknownError] = "UnknownError";
+ QMap<int, QString> errmap;
+ errmap[QProcess::FailedToStart] = "FailedToStart";
+ errmap[QProcess::Crashed] = "Crashed";
+ errmap[QProcess::Timedout] = "Timedout";
+ errmap[QProcess::WriteError] = "WriteError";
+ errmap[QProcess::ReadError] = "ReadError";
+ errmap[QProcess::UnknownError] = "UnknownError";
- emit q->debug(QString("Process error: %1").arg(errmap[x]));
+ emit q->debug(QString("Process error: %1").arg(errmap[x]));
- if(x == QProcess::FailedToStart)
- error = GPGProc::FailedToStart;
- else if(x == QProcess::WriteError)
- error = GPGProc::ErrorWrite;
- else
- error = GPGProc::UnexpectedExit;
+ if (x == QProcess::FailedToStart) {
+ error = GPGProc::FailedToStart;
+ } else if (x == QProcess::WriteError) {
+ error = GPGProc::ErrorWrite;
+ } else {
+ error = GPGProc::UnexpectedExit;
+ }
- fin_process = true;
- fin_process_success = false;
+ fin_process = true;
+ fin_process_success = false;
#ifdef QT_PIPE_HACK
- // If the process fails to start, then the ends of the pipes
- // intended for the child process are still open. Some Mac
- // users experience a lockup if we close our ends of the pipes
- // when the child's ends are still open. If we ensure the
- // child's ends are closed, we prevent this lockup. I have no
- // idea why the problem even happens or why this fix should
- // work.
- pipeAux.readEnd().reset();
- pipeCommand.readEnd().reset();
- pipeStatus.writeEnd().reset();
+ // If the process fails to start, then the ends of the pipes
+ // intended for the child process are still open. Some Mac
+ // users experience a lockup if we close our ends of the pipes
+ // when the child's ends are still open. If we ensure the
+ // child's ends are closed, we prevent this lockup. I have no
+ // idea why the problem even happens or why this fix should
+ // work.
+ pipeAux.readEnd().reset();
+ pipeCommand.readEnd().reset();
+ pipeStatus.writeEnd().reset();
#endif
- if(need_status && !fin_status)
- {
- pipeStatus.readEnd().finalize();
- fin_status = true;
- if(readAndProcessStatusData())
- {
- doneTrigger.start();
- emit q->readyReadStatusLines();
- return;
- }
- }
+ if (need_status && !fin_status) {
+ pipeStatus.readEnd().finalize();
+ fin_status = true;
+ if (readAndProcessStatusData()) {
+ doneTrigger.start();
+ emit q->readyReadStatusLines();
+ return;
+ }
+ }
- doTryDone();
+ doTryDone();
}
void GPGProc::Private::doTryDone()
{
- if(!fin_process)
- return;
+ if (!fin_process) {
+ return;
+ }
- if(need_status && !fin_status)
- return;
+ if (need_status && !fin_status) {
+ return;
+ }
- emit q->debug("Done");
+ emit q->debug("Done");
- // get leftover data
- proc->setReadChannel(QProcess::StandardOutput);
- leftover_stdout = proc->readAll();
+ // get leftover data
+ proc->setReadChannel(QProcess::StandardOutput);
+ leftover_stdout = proc->readAll();
- proc->setReadChannel(QProcess::StandardError);
- leftover_stderr = proc->readAll();
+ proc->setReadChannel(QProcess::StandardError);
+ leftover_stderr = proc->readAll();
- reset(ResetSession);
- if(fin_process_success)
- emit q->finished(exitCode);
- else
- emit q->error(error);
+ reset(ResetSession);
+ if (fin_process_success) {
+ emit q->finished(exitCode);
+ } else {
+ emit q->error(error);
+ }
}
bool GPGProc::Private::readAndProcessStatusData()
{
- QByteArray buf = pipeStatus.readEnd().read();
- if(buf.isEmpty())
- return false;
+ QByteArray buf = pipeStatus.readEnd().read();
+ if (buf.isEmpty()) {
+ return false;
+ }
- return processStatusData(buf);
+ return processStatusData(buf);
}
// return true if there are newly parsed lines available
bool GPGProc::Private::processStatusData(const QByteArray &buf)
{
- statusBuf.append(buf);
+ statusBuf.append(buf);
- // extract all lines
- QStringList list;
- while(1)
- {
- int n = statusBuf.indexOf('\n');
- if(n == -1)
- break;
+ // extract all lines
+ QStringList list;
+ while (1) {
+ int n = statusBuf.indexOf('\n');
+ if (n == -1) {
+ break;
+ }
- // extract the string from statusbuf
- ++n;
- char *p = (char *)statusBuf.data();
- QByteArray cs(p, n);
- int newsize = statusBuf.size() - n;
- memmove(p, p + n, newsize);
- statusBuf.resize(newsize);
+ // extract the string from statusbuf
+ ++n;
+ char *p = (char *)statusBuf.data();
+ QByteArray cs(p, n);
+ int newsize = statusBuf.size() - n;
+ memmove(p, p + n, newsize);
+ statusBuf.resize(newsize);
- // convert to string without newline
- QString str = QString::fromUtf8(cs);
- str.truncate(str.length() - 1);
+ // convert to string without newline
+ QString str = QString::fromUtf8(cs);
+ str.truncate(str.length() - 1);
- // ensure it has a proper header
- if(str.left(9) != "[GNUPG:] ")
- continue;
+ // ensure it has a proper header
+ if (str.left(9) != "[GNUPG:] ") {
+ continue;
+ }
- // take it off
- str = str.mid(9);
+ // take it off
+ str = str.mid(9);
- // add to the list
- list += str;
- }
+ // add to the list
+ list += str;
+ }
- if(list.isEmpty())
- return false;
+ if (list.isEmpty()) {
+ return false;
+ }
- statusLines += list;
- return true;
+ statusLines += list;
+ return true;
}
GPGProc::GPGProc(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
GPGProc::~GPGProc()
{
- delete d;
+ delete d;
}
void GPGProc::reset()
{
- d->reset(ResetAll);
+ d->reset(ResetAll);
}
bool GPGProc::isActive() const
{
- return (d->proc ? true : false);
+ return (d->proc ? true : false);
}
void GPGProc::start(const QString &bin, const QStringList &args, Mode mode)
{
- if(isActive())
- d->reset(ResetSessionAndData);
+ if (isActive()) {
+ d->reset(ResetSessionAndData);
+ }
- if(mode == ExtendedMode)
- {
- if(!d->setupPipes(args.contains("-&?")))
- {
- d->error = FailedToStart;
+ if (mode == ExtendedMode) {
+ if (!d->setupPipes(args.contains("-&?"))) {
+ d->error = FailedToStart;
- // emit later
- QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection, Q_ARG(gpgQCAPlugin::GPGProc::Error, d->error));
- return;
- }
+ // emit later
+ QMetaObject::invokeMethod(this, "error", Qt::QueuedConnection, Q_ARG(gpgQCAPlugin::GPGProc::Error, d->error));
+ return;
+ }
- d->need_status = true;
+ d->need_status = true;
- emit debug("Pipe setup complete");
- }
+ emit debug("Pipe setup complete");
+ }
- d->proc = new SProcess(d);
+ d->proc = new SProcess(d);
#ifdef Q_OS_UNIX
- QList<int> plist;
- if(d->pipeAux.readEnd().isValid())
- plist += d->pipeAux.readEnd().id();
- if(d->pipeCommand.readEnd().isValid())
- plist += d->pipeCommand.readEnd().id();
- if(d->pipeStatus.writeEnd().isValid())
- plist += d->pipeStatus.writeEnd().id();
- d->proc->setInheritPipeList(plist);
+ QList<int> plist;
+ if (d->pipeAux.readEnd().isValid()) {
+ plist += d->pipeAux.readEnd().id();
+ }
+ if (d->pipeCommand.readEnd().isValid()) {
+ plist += d->pipeCommand.readEnd().id();
+ }
+ if (d->pipeStatus.writeEnd().isValid()) {
+ plist += d->pipeStatus.writeEnd().id();
+ }
+ d->proc->setInheritPipeList(plist);
#endif
- // enable the pipes we want
- if(d->pipeAux.writeEnd().isValid())
- d->pipeAux.writeEnd().enable();
- if(d->pipeCommand.writeEnd().isValid())
- d->pipeCommand.writeEnd().enable();
- if(d->pipeStatus.readEnd().isValid())
- d->pipeStatus.readEnd().enable();
+ // enable the pipes we want
+ if (d->pipeAux.writeEnd().isValid()) {
+ d->pipeAux.writeEnd().enable();
+ }
+ if (d->pipeCommand.writeEnd().isValid()) {
+ d->pipeCommand.writeEnd().enable();
+ }
+ if (d->pipeStatus.readEnd().isValid()) {
+ d->pipeStatus.readEnd().enable();
+ }
#ifdef QPROC_SIGNAL_RELAY
- d->proc_relay = new QProcessSignalRelay(d->proc, d);
- connect(d->proc_relay, SIGNAL(started()), d, SLOT(proc_started()));
- connect(d->proc_relay, SIGNAL(readyReadStandardOutput()), d, SLOT(proc_readyReadStandardOutput()));
- connect(d->proc_relay, SIGNAL(readyReadStandardError()), d, SLOT(proc_readyReadStandardError()));
- connect(d->proc_relay, SIGNAL(bytesWritten(qint64)), d, SLOT(proc_bytesWritten(qint64)));
- connect(d->proc_relay, SIGNAL(finished(int)), d, SLOT(proc_finished(int)));
- connect(d->proc_relay, SIGNAL(error(QProcess::ProcessError)), d, SLOT(proc_error(QProcess::ProcessError)));
+ d->proc_relay = new QProcessSignalRelay(d->proc, d);
+ connect(d->proc_relay, SIGNAL(started()), d, SLOT(proc_started()));
+ connect(d->proc_relay, SIGNAL(readyReadStandardOutput()), d, SLOT(proc_readyReadStandardOutput()));
+ connect(d->proc_relay, SIGNAL(readyReadStandardError()), d, SLOT(proc_readyReadStandardError()));
+ connect(d->proc_relay, SIGNAL(bytesWritten(qint64)), d, SLOT(proc_bytesWritten(qint64)));
+ connect(d->proc_relay, SIGNAL(finished(int)), d, SLOT(proc_finished(int)));
+ connect(d->proc_relay, SIGNAL(error(QProcess::ProcessError)), d, SLOT(proc_error(QProcess::ProcessError)));
#else
- connect(d->proc, SIGNAL(started()), d, SLOT(proc_started()));
- connect(d->proc, SIGNAL(readyReadStandardOutput()), d, SLOT(proc_readyReadStandardOutput()));
- connect(d->proc, SIGNAL(readyReadStandardError()), d, SLOT(proc_readyReadStandardError()));
- connect(d->proc, SIGNAL(bytesWritten(qint64)), d, SLOT(proc_bytesWritten(qint64)));
- connect(d->proc, SIGNAL(finished(int)), d, SLOT(proc_finished(int)));
- connect(d->proc, SIGNAL(error(QProcess::ProcessError)), d, SLOT(proc_error(QProcess::ProcessError)));
+ connect(d->proc, SIGNAL(started()), d, SLOT(proc_started()));
+ connect(d->proc, SIGNAL(readyReadStandardOutput()), d, SLOT(proc_readyReadStandardOutput()));
+ connect(d->proc, SIGNAL(readyReadStandardError()), d, SLOT(proc_readyReadStandardError()));
+ connect(d->proc, SIGNAL(bytesWritten(qint64)), d, SLOT(proc_bytesWritten(qint64)));
+ connect(d->proc, SIGNAL(finished(int)), d, SLOT(proc_finished(int)));
+ connect(d->proc, SIGNAL(error(QProcess::ProcessError)), d, SLOT(proc_error(QProcess::ProcessError)));
#endif
- d->bin = bin;
- d->args = args;
- d->mode = mode;
- d->startTrigger.start();
+ d->bin = bin;
+ d->args = args;
+ d->mode = mode;
+ d->startTrigger.start();
}
QByteArray GPGProc::readStdout()
{
- if(d->proc)
- {
- d->proc->setReadChannel(QProcess::StandardOutput);
- return d->proc->readAll();
- }
- else
- {
- QByteArray a = d->leftover_stdout;
- d->leftover_stdout.clear();
- return a;
- }
+ if (d->proc) {
+ d->proc->setReadChannel(QProcess::StandardOutput);
+ return d->proc->readAll();
+ } else {
+ QByteArray a = d->leftover_stdout;
+ d->leftover_stdout.clear();
+ return a;
+ }
}
QByteArray GPGProc::readStderr()
{
- if(d->proc)
- {
- d->proc->setReadChannel(QProcess::StandardError);
- return d->proc->readAll();
- }
- else
- {
- QByteArray a = d->leftover_stderr;
- d->leftover_stderr.clear();
- return a;
- }
+ if (d->proc) {
+ d->proc->setReadChannel(QProcess::StandardError);
+ return d->proc->readAll();
+ } else {
+ QByteArray a = d->leftover_stderr;
+ d->leftover_stderr.clear();
+ return a;
+ }
}
QStringList GPGProc::readStatusLines()
{
- QStringList out = d->statusLines;
- d->statusLines.clear();
- return out;
+ QStringList out = d->statusLines;
+ d->statusLines.clear();
+ return out;
}
void GPGProc::writeStdin(const QByteArray &a)
{
- if(!d->proc || a.isEmpty())
- return;
+ if (!d->proc || a.isEmpty()) {
+ return;
+ }
- if(d->proc->state() == QProcess::Running)
- d->proc->write(a);
- else
- d->pre_stdin += a;
+ if (d->proc->state() == QProcess::Running) {
+ d->proc->write(a);
+ } else {
+ d->pre_stdin += a;
+ }
}
void GPGProc::writeAux(const QByteArray &a)
{
- if(!d->proc || a.isEmpty())
- return;
+ if (!d->proc || a.isEmpty()) {
+ return;
+ }
- if(d->proc->state() == QProcess::Running)
- d->pipeAux.writeEnd().write(a);
- else
- d->pre_aux += a;
+ if (d->proc->state() == QProcess::Running) {
+ d->pipeAux.writeEnd().write(a);
+ } else {
+ d->pre_aux += a;
+ }
}
#ifdef QPIPE_SECURE
void GPGProc::writeCommand(const SecureArray &a)
#else
void GPGProc::writeCommand(const QByteArray &a)
#endif
{
- if(!d->proc || a.isEmpty())
- return;
+ if (!d->proc || a.isEmpty()) {
+ return;
+ }
- if(d->proc->state() == QProcess::Running)
+ if (d->proc->state() == QProcess::Running)
#ifdef QPIPE_SECURE
- d->pipeCommand.writeEnd().writeSecure(a);
+ d->pipeCommand.writeEnd().writeSecure(a);
#else
- d->pipeCommand.writeEnd().write(a);
+ d->pipeCommand.writeEnd().write(a);
#endif
- else
- d->pre_command += a;
+ else {
+ d->pre_command += a;
+ }
}
void GPGProc::closeStdin()
{
- if(!d->proc)
- return;
+ if (!d->proc) {
+ return;
+ }
- if(d->proc->state() == QProcess::Running)
- {
- d->proc->waitForBytesWritten();
- d->proc->closeWriteChannel();
- }
- else
- {
- d->pre_stdin_close = true;
- }
+ if (d->proc->state() == QProcess::Running) {
+ d->proc->waitForBytesWritten();
+ d->proc->closeWriteChannel();
+ } else {
+ d->pre_stdin_close = true;
+ }
}
void GPGProc::closeAux()
{
- if(!d->proc)
- return;
+ if (!d->proc) {
+ return;
+ }
- if(d->proc->state() == QProcess::Running)
- d->pipeAux.writeEnd().close();
- else
- d->pre_aux_close = true;
+ if (d->proc->state() == QProcess::Running) {
+ d->pipeAux.writeEnd().close();
+ } else {
+ d->pre_aux_close = true;
+ }
}
void GPGProc::closeCommand()
{
- if(!d->proc)
- return;
+ if (!d->proc) {
+ return;
+ }
- if(d->proc->state() == QProcess::Running)
- d->pipeCommand.writeEnd().close();
- else
- d->pre_command_close = true;
+ if (d->proc->state() == QProcess::Running) {
+ d->pipeCommand.writeEnd().close();
+ } else {
+ d->pre_command_close = true;
+ }
}
}
diff --git a/plugins/qca-gnupg/gpgproc/gpgproc.h b/plugins/qca-gnupg/gpgproc/gpgproc.h
index a9f38c34..96db110c 100644
--- a/plugins/qca-gnupg/gpgproc/gpgproc.h
+++ b/plugins/qca-gnupg/gpgproc/gpgproc.h
@@ -1,78 +1,79 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#ifndef GPGPROC_H
#define GPGPROC_H
#include "qpipe.h"
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
// GPGProc - executes gpg and provides access to all 6 channels. NormalMode
// enables stdout, stderr, and stdin. ExtendedMode has those 3 plus status
// aux, and command. The aux channel is connected to the '-&?' argument.
// The debug() signal, as well as stderr, can be used for diagnostic text.
class GPGProc : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum Error { FailedToStart, UnexpectedExit, ErrorWrite };
- enum Mode { NormalMode, ExtendedMode };
- GPGProc(QObject *parent = 0);
- ~GPGProc();
+ enum Error { FailedToStart, UnexpectedExit, ErrorWrite };
+ enum Mode { NormalMode, ExtendedMode };
+ GPGProc(QObject *parent = 0);
+ ~GPGProc();
- void reset();
+ void reset();
- bool isActive() const;
- void start(const QString &bin, const QStringList &args, Mode m = ExtendedMode);
+ bool isActive() const;
+ void start(const QString &bin, const QStringList &args, Mode m = ExtendedMode);
- QByteArray readStdout();
- QByteArray readStderr();
- QStringList readStatusLines();
- void writeStdin(const QByteArray &a);
- void writeAux(const QByteArray &a);
+ QByteArray readStdout();
+ QByteArray readStderr();
+ QStringList readStatusLines();
+ void writeStdin(const QByteArray &a);
+ void writeAux(const QByteArray &a);
#ifdef QPIPE_SECURE
- void writeCommand(const QCA::SecureArray &a);
+ void writeCommand(const QCA::SecureArray &a);
#else
- void writeCommand(const QByteArray &a);
+ void writeCommand(const QByteArray &a);
#endif
- void closeStdin();
- void closeAux();
- void closeCommand();
+ void closeStdin();
+ void closeAux();
+ void closeCommand();
Q_SIGNALS:
- void error(gpgQCAPlugin::GPGProc::Error error);
- void finished(int exitCode);
- void readyReadStdout();
- void readyReadStderr();
- void readyReadStatusLines();
- void bytesWrittenStdin(int bytes);
- void bytesWrittenAux(int bytes);
- void bytesWrittenCommand(int bytes);
- void debug(const QString &str); // not signal-safe
+ void error(gpgQCAPlugin::GPGProc::Error error);
+ void finished(int exitCode);
+ void readyReadStdout();
+ void readyReadStderr();
+ void readyReadStatusLines();
+ void bytesWrittenStdin(int bytes);
+ void bytesWrittenAux(int bytes);
+ void bytesWrittenCommand(int bytes);
+ void debug(const QString &str); // not signal-safe
private:
- class Private;
- friend class Private;
- Private *d;
+ class Private;
+ friend class Private;
+ Private *d;
};
}
#endif
diff --git a/plugins/qca-gnupg/gpgproc/gpgproc_p.h b/plugins/qca-gnupg/gpgproc/gpgproc_p.h
index 882054b2..5eff6bd7 100644
--- a/plugins/qca-gnupg/gpgproc/gpgproc_p.h
+++ b/plugins/qca-gnupg/gpgproc/gpgproc_p.h
@@ -1,156 +1,155 @@
/*
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#pragma once
#define QPROC_SIGNAL_RELAY
#include "qpipe.h"
#include "sprocess.h"
#include "gpgproc.h"
#include <QObject>
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
class QProcessSignalRelay : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- QProcessSignalRelay(QProcess *proc, QObject *parent = 0)
- :QObject(parent)
- {
- qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError");
- connect(proc, SIGNAL(started()), SLOT(proc_started()), Qt::QueuedConnection);
- connect(proc, SIGNAL(readyReadStandardOutput()), SLOT(proc_readyReadStandardOutput()), Qt::QueuedConnection);
- connect(proc, SIGNAL(readyReadStandardError()), SLOT(proc_readyReadStandardError()), Qt::QueuedConnection);
- connect(proc, SIGNAL(bytesWritten(qint64)), SLOT(proc_bytesWritten(qint64)), Qt::QueuedConnection);
- connect(proc, SIGNAL(finished(int)), SLOT(proc_finished(int)), Qt::QueuedConnection);
- connect(proc, SIGNAL(error(QProcess::ProcessError)), SLOT(proc_error(QProcess::ProcessError)), Qt::QueuedConnection);
- }
+ QProcessSignalRelay(QProcess *proc, QObject *parent = 0)
+ : QObject(parent)
+ {
+ qRegisterMetaType<QProcess::ProcessError>("QProcess::ProcessError");
+ connect(proc, SIGNAL(started()), SLOT(proc_started()), Qt::QueuedConnection);
+ connect(proc, SIGNAL(readyReadStandardOutput()), SLOT(proc_readyReadStandardOutput()), Qt::QueuedConnection);
+ connect(proc, SIGNAL(readyReadStandardError()), SLOT(proc_readyReadStandardError()), Qt::QueuedConnection);
+ connect(proc, SIGNAL(bytesWritten(qint64)), SLOT(proc_bytesWritten(qint64)), Qt::QueuedConnection);
+ connect(proc, SIGNAL(finished(int)), SLOT(proc_finished(int)), Qt::QueuedConnection);
+ connect(proc, SIGNAL(error(QProcess::ProcessError)), SLOT(proc_error(QProcess::ProcessError)), Qt::QueuedConnection);
+ }
signals:
- void started();
- void readyReadStandardOutput();
- void readyReadStandardError();
- void bytesWritten(qint64);
- void finished(int);
- void error(QProcess::ProcessError);
+ void started();
+ void readyReadStandardOutput();
+ void readyReadStandardError();
+ void bytesWritten(qint64);
+ void finished(int);
+ void error(QProcess::ProcessError);
public slots:
- void proc_started()
- {
- emit started();
- }
-
- void proc_readyReadStandardOutput()
- {
- emit readyReadStandardOutput();
- }
-
- void proc_readyReadStandardError()
- {
- emit readyReadStandardError();
- }
-
- void proc_bytesWritten(qint64 x)
- {
- emit bytesWritten(x);
- }
-
- void proc_finished(int x)
- {
- emit finished(x);
- }
-
- void proc_error(QProcess::ProcessError x)
- {
- emit error(x);
- }
+ void proc_started()
+ {
+ emit started();
+ }
+
+ void proc_readyReadStandardOutput()
+ {
+ emit readyReadStandardOutput();
+ }
+
+ void proc_readyReadStandardError()
+ {
+ emit readyReadStandardError();
+ }
+
+ void proc_bytesWritten(qint64 x)
+ {
+ emit bytesWritten(x);
+ }
+
+ void proc_finished(int x)
+ {
+ emit finished(x);
+ }
+
+ void proc_error(QProcess::ProcessError x)
+ {
+ emit error(x);
+ }
};
-enum ResetMode
-{
- ResetSession = 0,
- ResetSessionAndData = 1,
- ResetAll = 2
+enum ResetMode {
+ ResetSession = 0,
+ ResetSessionAndData = 1,
+ ResetAll = 2
};
class GPGProc::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- GPGProc *q;
- QString bin;
- QStringList args;
- GPGProc::Mode mode;
- SProcess *proc;
+ GPGProc *q;
+ QString bin;
+ QStringList args;
+ GPGProc::Mode mode;
+ SProcess *proc;
#ifdef QPROC_SIGNAL_RELAY
- QProcessSignalRelay *proc_relay;
+ QProcessSignalRelay *proc_relay;
#endif
- QCA::QPipe pipeAux, pipeCommand, pipeStatus;
- QByteArray statusBuf;
- QStringList statusLines;
- GPGProc::Error error;
- int exitCode;
- QCA::SafeTimer startTrigger, doneTrigger;
-
- QByteArray pre_stdin, pre_aux;
+ QCA::QPipe pipeAux, pipeCommand, pipeStatus;
+ QByteArray statusBuf;
+ QStringList statusLines;
+ GPGProc::Error error;
+ int exitCode;
+ QCA::SafeTimer startTrigger, doneTrigger;
+
+ QByteArray pre_stdin, pre_aux;
#ifdef QPIPE_SECURE
- QCA::SecureArray pre_command;
+ QCA::SecureArray pre_command;
#else
- QByteArray pre_command;
+ QByteArray pre_command;
#endif
- bool pre_stdin_close, pre_aux_close, pre_command_close;
+ bool pre_stdin_close, pre_aux_close, pre_command_close;
- bool need_status, fin_process, fin_process_success, fin_status;
- QByteArray leftover_stdout;
- QByteArray leftover_stderr;
+ bool need_status, fin_process, fin_process_success, fin_status;
+ QByteArray leftover_stdout;
+ QByteArray leftover_stderr;
- Private(GPGProc *_q);
- ~Private();
- void closePipes();
- void reset(ResetMode mode);
- bool setupPipes(bool makeAux);
- void setupArguments();
+ Private(GPGProc *_q);
+ ~Private();
+ void closePipes();
+ void reset(ResetMode mode);
+ bool setupPipes(bool makeAux);
+ void setupArguments();
public slots:
- void doStart();
- void aux_written(int x);
- void aux_error(QCA::QPipeEnd::Error);
- void command_written(int x);
- void command_error(QCA::QPipeEnd::Error);
- void status_read();
- void status_error(QCA::QPipeEnd::Error e);
- void proc_started();
- void proc_readyReadStandardOutput();
- void proc_readyReadStandardError();
- void proc_bytesWritten(qint64 lx);
- void proc_finished(int x);
- void proc_error(QProcess::ProcessError x);
- void doTryDone();
+ void doStart();
+ void aux_written(int x);
+ void aux_error(QCA::QPipeEnd::Error);
+ void command_written(int x);
+ void command_error(QCA::QPipeEnd::Error);
+ void status_read();
+ void status_error(QCA::QPipeEnd::Error e);
+ void proc_started();
+ void proc_readyReadStandardOutput();
+ void proc_readyReadStandardError();
+ void proc_bytesWritten(qint64 lx);
+ void proc_finished(int x);
+ void proc_error(QProcess::ProcessError x);
+ void doTryDone();
private:
- bool readAndProcessStatusData();
- // return true if there are newly parsed lines available
- bool processStatusData(const QByteArray &buf);
-
-
+ bool readAndProcessStatusData();
+ // return true if there are newly parsed lines available
+ bool processStatusData(const QByteArray &buf);
+
};
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/gpgproc/sprocess.cpp b/plugins/qca-gnupg/gpgproc/sprocess.cpp
index ebbd7c6d..94068704 100644
--- a/plugins/qca-gnupg/gpgproc/sprocess.cpp
+++ b/plugins/qca-gnupg/gpgproc/sprocess.cpp
@@ -1,55 +1,57 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include "sprocess.h"
#ifdef Q_OS_UNIX
# include <unistd.h>
# include <fcntl.h>
#endif
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
//----------------------------------------------------------------------------
// SProcess
//----------------------------------------------------------------------------
SProcess::SProcess(QObject *parent)
-:QProcess(parent)
+ : QProcess(parent)
{
}
SProcess::~SProcess()
{
}
#ifdef Q_OS_UNIX
void SProcess::setInheritPipeList(const QList<int> &list)
{
- pipeList = list;
+ pipeList = list;
}
void SProcess::setupChildProcess()
{
- // set the pipes to be inheritable
- for(int n = 0; n < pipeList.count(); ++n)
- ::fcntl(pipeList[n], F_SETFD, (::fcntl(pipeList[n], F_GETFD) & ~FD_CLOEXEC));
+ // set the pipes to be inheritable
+ for (int n = 0; n < pipeList.count(); ++n) {
+ ::fcntl(pipeList[n], F_SETFD, (::fcntl(pipeList[n], F_GETFD) & ~FD_CLOEXEC));
+ }
}
#endif
}
diff --git a/plugins/qca-gnupg/gpgproc/sprocess.h b/plugins/qca-gnupg/gpgproc/sprocess.h
index e56cfe52..114760d6 100644
--- a/plugins/qca-gnupg/gpgproc/sprocess.h
+++ b/plugins/qca-gnupg/gpgproc/sprocess.h
@@ -1,47 +1,48 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#ifndef SPROCESS_H
#define SPROCESS_H
#include <QProcess>
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
class SProcess : public QProcess
{
- Q_OBJECT
+ Q_OBJECT
public:
- SProcess(QObject *parent = 0);
- ~SProcess();
+ SProcess(QObject *parent = 0);
+ ~SProcess();
#ifdef Q_OS_UNIX
- void setInheritPipeList(const QList<int> &);
+ void setInheritPipeList(const QList<int> &);
protected:
- virtual void setupChildProcess();
+ virtual void setupChildProcess();
private:
- QList<int> pipeList;
+ QList<int> pipeList;
#endif
};
}
#endif
diff --git a/plugins/qca-gnupg/lineconverter.cpp b/plugins/qca-gnupg/lineconverter.cpp
index e7dd5259..7757fc6b 100644
--- a/plugins/qca-gnupg/lineconverter.cpp
+++ b/plugins/qca-gnupg/lineconverter.cpp
@@ -1,183 +1,164 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include "lineconverter.h"
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
void LineConverter::setup(LineConverter::Mode m)
{
- state = Normal;
- mode = m;
- prebytes = 0;
- list.clear();
+ state = Normal;
+ mode = m;
+ prebytes = 0;
+ list.clear();
}
QByteArray LineConverter::update(const QByteArray &buf)
{
- if(mode == Read)
- {
- // Convert buf to UNIX line ending style
- // If buf ends with '\r' set state to Partival
-
- QByteArray out;
-
- if(state == Normal)
- {
- out = buf;
- }
- else
- {
- out.resize(buf.size() + 1);
- out[0] = '\r';
- memcpy(out.data() + 1, buf.data(), buf.size());
- }
-
- int n = 0;
- while(1)
- {
- n = out.indexOf('\r', n);
- // not found
- if(n == -1)
- {
- break;
- }
- // found, not last character
- if(n < (buf.size() - 1))
- {
- // found windows line ending "\r\n"
- if(out[n + 1] == '\n')
- {
- // clip out the '\r'
- memmove(out.data() + n, out.data() + n + 1, out.size() - n - 1);
- out.resize(out.size() - 1);
- }
- }
- // found, last character
- else
- {
- state = Partial;
- break;
- }
- ++n;
- }
-
- return out;
- }
- else
- {
- // On Windows use DOS line ending style.
- // On UNIX don't do any convertation. Return buf as is.
+ if (mode == Read) {
+ // Convert buf to UNIX line ending style
+ // If buf ends with '\r' set state to Partival
+
+ QByteArray out;
+
+ if (state == Normal) {
+ out = buf;
+ } else {
+ out.resize(buf.size() + 1);
+ out[0] = '\r';
+ memcpy(out.data() + 1, buf.data(), buf.size());
+ }
+
+ int n = 0;
+ while (1) {
+ n = out.indexOf('\r', n);
+ // not found
+ if (n == -1) {
+ break;
+ }
+ // found, not last character
+ if (n < (buf.size() - 1)) {
+ // found windows line ending "\r\n"
+ if (out[n + 1] == '\n') {
+ // clip out the '\r'
+ memmove(out.data() + n, out.data() + n + 1, out.size() - n - 1);
+ out.resize(out.size() - 1);
+ }
+ }
+ // found, last character
+ else {
+ state = Partial;
+ break;
+ }
+ ++n;
+ }
+
+ return out;
+ } else {
+ // On Windows use DOS line ending style.
+ // On UNIX don't do any convertation. Return buf as is.
#ifdef Q_OS_WIN
- QByteArray out;
- int prev = 0;
- int at = 0;
-
- while(1)
- {
- int n = buf.indexOf('\n', at);
- if(n == -1)
- break;
-
- int chunksize = n - at;
- int oldsize = out.size();
- out.resize(oldsize + chunksize + 2);
- memcpy(out.data() + oldsize, buf.data() + at, chunksize);
- memcpy(out.data() + oldsize + chunksize, "\r\n", 2);
-
- list.append(prebytes + n + 1 - prev);
- prebytes = 0;
- prev = n;
-
- at = n + 1;
- }
- if(at < buf.size())
- {
- int chunksize = buf.size() - at;
- int oldsize = out.size();
- out.resize(oldsize + chunksize);
- memcpy(out.data() + oldsize, buf.data() + at, chunksize);
- }
-
- prebytes += buf.size() - prev;
- return out;
+ QByteArray out;
+ int prev = 0;
+ int at = 0;
+
+ while (1) {
+ int n = buf.indexOf('\n', at);
+ if (n == -1) {
+ break;
+ }
+
+ int chunksize = n - at;
+ int oldsize = out.size();
+ out.resize(oldsize + chunksize + 2);
+ memcpy(out.data() + oldsize, buf.data() + at, chunksize);
+ memcpy(out.data() + oldsize + chunksize, "\r\n", 2);
+
+ list.append(prebytes + n + 1 - prev);
+ prebytes = 0;
+ prev = n;
+
+ at = n + 1;
+ }
+ if (at < buf.size()) {
+ int chunksize = buf.size() - at;
+ int oldsize = out.size();
+ out.resize(oldsize + chunksize);
+ memcpy(out.data() + oldsize, buf.data() + at, chunksize);
+ }
+
+ prebytes += buf.size() - prev;
+ return out;
#else
- return buf;
+ return buf;
#endif
- }
+ }
}
QByteArray LineConverter::final()
{
- if(mode == Read)
- {
- QByteArray out;
- if(state == Partial)
- {
- out.resize(1);
- out[0] = '\n';
- }
- return out;
- }
- else
- {
- return QByteArray();
- }
+ if (mode == Read) {
+ QByteArray out;
+ if (state == Partial) {
+ out.resize(1);
+ out[0] = '\n';
+ }
+ return out;
+ } else {
+ return QByteArray();
+ }
}
QByteArray LineConverter::process(const QByteArray &buf)
{
- return update(buf) + final();
+ return update(buf) + final();
}
int LineConverter::writtenToActual(int bytes)
{
#ifdef Q_OS_WIN
- int n = 0;
- int counter = bytes;
- while(counter > 0)
- {
- if(!list.isEmpty() && bytes >= list.first())
- {
- ++n;
- counter -= list.takeFirst();
- }
- else
- {
- if(list.isEmpty())
- prebytes -= counter;
- else
- list.first() -= counter;
-
- if(prebytes < 0)
- {
- bytes += prebytes;
- prebytes = 0;
- }
-
- break;
- }
- }
- return bytes - n;
+ int n = 0;
+ int counter = bytes;
+ while (counter > 0) {
+ if (!list.isEmpty() && bytes >= list.first()) {
+ ++n;
+ counter -= list.takeFirst();
+ } else {
+ if (list.isEmpty()) {
+ prebytes -= counter;
+ } else {
+ list.first() -= counter;
+ }
+
+ if (prebytes < 0) {
+ bytes += prebytes;
+ prebytes = 0;
+ }
+
+ break;
+ }
+ }
+ return bytes - n;
#else
- return bytes;
+ return bytes;
#endif
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/lineconverter.h b/plugins/qca-gnupg/lineconverter.h
index 493bee98..4338dfb0 100644
--- a/plugins/qca-gnupg/lineconverter.h
+++ b/plugins/qca-gnupg/lineconverter.h
@@ -1,46 +1,47 @@
/*
* Copyright (C) 2003-2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#pragma once
#include <QList>
#include <QByteArray>
-namespace gpgQCAPlugin {
+namespace gpgQCAPlugin
+{
class LineConverter
{
public:
- enum Mode { Read, Write };
+ enum Mode { Read, Write };
- void setup(Mode m);
- QByteArray update(const QByteArray &buf);
- QByteArray final();
- QByteArray process(const QByteArray &buf);
- int writtenToActual(int bytes);
+ void setup(Mode m);
+ QByteArray update(const QByteArray &buf);
+ QByteArray final();
+ QByteArray process(const QByteArray &buf);
+ int writtenToActual(int bytes);
private:
- enum State { Normal, Partial };
- Mode mode;
- State state;
- int prebytes;
- QList<int> list;
+ enum State { Normal, Partial };
+ Mode mode;
+ State state;
+ int prebytes;
+ QList<int> list;
};
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mykeystoreentry.cpp b/plugins/qca-gnupg/mykeystoreentry.cpp
index 4a6b82a2..8a4849a0 100644
--- a/plugins/qca-gnupg/mykeystoreentry.cpp
+++ b/plugins/qca-gnupg/mykeystoreentry.cpp
@@ -1,95 +1,96 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "mykeystoreentry.h"
#include "utils.h"
using namespace QCA;
namespace gpgQCAPlugin
{
MyKeyStoreEntry::MyKeyStoreEntry(const PGPKey &_pub, const PGPKey &_sec, Provider *p) : KeyStoreEntryContext(p)
{
- pub = _pub;
- sec = _sec;
- if(!sec.isNull())
- item_type = KeyStoreEntry::TypePGPSecretKey;
- else
- item_type = KeyStoreEntry::TypePGPPublicKey;
+ pub = _pub;
+ sec = _sec;
+ if (!sec.isNull()) {
+ item_type = KeyStoreEntry::TypePGPSecretKey;
+ } else {
+ item_type = KeyStoreEntry::TypePGPPublicKey;
+ }
}
MyKeyStoreEntry::MyKeyStoreEntry(const MyKeyStoreEntry &from) : KeyStoreEntryContext(from)
{
}
MyKeyStoreEntry::~MyKeyStoreEntry()
{
}
Provider::Context *MyKeyStoreEntry::clone() const
{
- return new MyKeyStoreEntry(*this);
+ return new MyKeyStoreEntry(*this);
}
KeyStoreEntry::Type MyKeyStoreEntry::type() const
{
- return item_type;
+ return item_type;
}
QString MyKeyStoreEntry::name() const
{
- return pub.primaryUserId();
+ return pub.primaryUserId();
}
QString MyKeyStoreEntry::id() const
{
- return pub.keyId();
+ return pub.keyId();
}
QString MyKeyStoreEntry::storeId() const
{
- return _storeId;
+ return _storeId;
}
QString MyKeyStoreEntry::storeName() const
{
- return _storeName;
+ return _storeName;
}
PGPKey MyKeyStoreEntry::pgpSecretKey() const
{
- return sec;
+ return sec;
}
PGPKey MyKeyStoreEntry::pgpPublicKey() const
{
- return pub;
+ return pub;
}
QString MyKeyStoreEntry::serialize() const
{
- // we only serialize the key id. this means the keyring
- // must be available to restore the data
- QStringList out;
- out += escape_string("qca-gnupg-1");
- out += escape_string(pub.keyId());
- return out.join(":");
+ // we only serialize the key id. this means the keyring
+ // must be available to restore the data
+ QStringList out;
+ out += escape_string("qca-gnupg-1");
+ out += escape_string(pub.keyId());
+ return out.join(":");
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mykeystoreentry.h b/plugins/qca-gnupg/mykeystoreentry.h
index e060c7a3..872afa2d 100644
--- a/plugins/qca-gnupg/mykeystoreentry.h
+++ b/plugins/qca-gnupg/mykeystoreentry.h
@@ -1,53 +1,53 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#pragma once
#include "qcaprovider.h"
namespace gpgQCAPlugin
{
class MyKeyStoreList;
class MyKeyStoreEntry : public QCA::KeyStoreEntryContext
{
public:
- QCA::KeyStoreEntry::Type item_type;
- QCA::PGPKey pub, sec;
- QString _storeId, _storeName;
-
- MyKeyStoreEntry(const QCA::PGPKey &_pub, const QCA::PGPKey &_sec, QCA::Provider *p);
- MyKeyStoreEntry(const MyKeyStoreEntry &from);
- ~MyKeyStoreEntry();
-
- // reimplemented Provider::Context
- QCA::Provider::Context *clone() const;
-
- // reimplemented KeyStoreEntryContext
- QCA::KeyStoreEntry::Type type() const;
- QString name() const;
- QString id() const;
- QString storeId() const;
- QString storeName() const;
- QCA::PGPKey pgpSecretKey() const;
- QCA::PGPKey pgpPublicKey() const;
- QString serialize() const;
+ QCA::KeyStoreEntry::Type item_type;
+ QCA::PGPKey pub, sec;
+ QString _storeId, _storeName;
+
+ MyKeyStoreEntry(const QCA::PGPKey &_pub, const QCA::PGPKey &_sec, QCA::Provider *p);
+ MyKeyStoreEntry(const MyKeyStoreEntry &from);
+ ~MyKeyStoreEntry();
+
+ // reimplemented Provider::Context
+ QCA::Provider::Context *clone() const;
+
+ // reimplemented KeyStoreEntryContext
+ QCA::KeyStoreEntry::Type type() const;
+ QString name() const;
+ QString id() const;
+ QString storeId() const;
+ QString storeName() const;
+ QCA::PGPKey pgpSecretKey() const;
+ QCA::PGPKey pgpPublicKey() const;
+ QString serialize() const;
};
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mykeystorelist.cpp b/plugins/qca-gnupg/mykeystorelist.cpp
index 81e30e7e..7b19ebe4 100644
--- a/plugins/qca-gnupg/mykeystorelist.cpp
+++ b/plugins/qca-gnupg/mykeystorelist.cpp
@@ -1,487 +1,477 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "mykeystorelist.h"
#include "utils.h"
#include "mypgpkeycontext.h"
#include <QMutexLocker>
#include <QFileInfo>
using namespace QCA;
namespace gpgQCAPlugin
{
Q_GLOBAL_STATIC(QMutex, ksl_mutex)
static MyKeyStoreList *keyStoreList = 0;
MyKeyStoreList::MyKeyStoreList(Provider *p)
- : KeyStoreListContext(p)
- , initialized(false)
- , gpg(find_bin(), this)
- , pubdirty(false)
- , secdirty(false)
- , ringWatch(this)
+ : KeyStoreListContext(p)
+ , initialized(false)
+ , gpg(find_bin(), this)
+ , pubdirty(false)
+ , secdirty(false)
+ , ringWatch(this)
{
- QMutexLocker locker(ksl_mutex());
- keyStoreList = this;
+ QMutexLocker locker(ksl_mutex());
+ keyStoreList = this;
- connect(&gpg, SIGNAL(finished()), SLOT(gpg_finished()));
- connect(&ringWatch, SIGNAL(changed(const QString &)), SLOT(ring_changed(const QString &)));
+ connect(&gpg, SIGNAL(finished()), SLOT(gpg_finished()));
+ connect(&ringWatch, SIGNAL(changed(QString)), SLOT(ring_changed(QString)));
}
MyKeyStoreList::~MyKeyStoreList()
{
- QMutexLocker locker(ksl_mutex());
- keyStoreList = 0;
+ QMutexLocker locker(ksl_mutex());
+ keyStoreList = 0;
}
Provider::Context *MyKeyStoreList::clone() const
{
- return 0;
+ return 0;
}
QString MyKeyStoreList::name(int) const
{
- return "GnuPG Keyring";
+ return "GnuPG Keyring";
}
KeyStore::Type MyKeyStoreList::type(int) const
{
- return KeyStore::PGPKeyring;
+ return KeyStore::PGPKeyring;
}
QString MyKeyStoreList::storeId(int) const
{
- return "qca-gnupg";
+ return "qca-gnupg";
}
QList<int> MyKeyStoreList::keyStores()
{
- // we just support one fixed keyring, if any
- QList<int> list;
- if(initialized)
- list += 0;
- return list;
+ // we just support one fixed keyring, if any
+ QList<int> list;
+ if (initialized) {
+ list += 0;
+ }
+ return list;
}
void MyKeyStoreList::start()
{
- // kick start our init procedure:
- // ensure gpg is installed
- // obtain keyring file names for monitoring
- // cache initial keyrings
+ // kick start our init procedure:
+ // ensure gpg is installed
+ // obtain keyring file names for monitoring
+ // cache initial keyrings
- init_step = 0;
- gpg.doCheck();
+ init_step = 0;
+ gpg.doCheck();
}
bool MyKeyStoreList::isReadOnly(int) const
{
- return false;
+ return false;
}
QList<KeyStoreEntry::Type> MyKeyStoreList::entryTypes(int) const
{
- QList<KeyStoreEntry::Type> list;
- list += KeyStoreEntry::TypePGPSecretKey;
- list += KeyStoreEntry::TypePGPPublicKey;
- return list;
+ QList<KeyStoreEntry::Type> list;
+ list += KeyStoreEntry::TypePGPSecretKey;
+ list += KeyStoreEntry::TypePGPPublicKey;
+ return list;
}
-QList<KeyStoreEntryContext*> MyKeyStoreList::entryList(int)
+QList<KeyStoreEntryContext *> MyKeyStoreList::entryList(int)
{
- QMutexLocker locker(&ringMutex);
+ QMutexLocker locker(&ringMutex);
- QList<KeyStoreEntryContext*> out;
+ QList<KeyStoreEntryContext *> out;
- foreach(const GpgOp::Key &pkey, pubkeys)
- {
- PGPKey pub, sec;
+ foreach (const GpgOp::Key &pkey, pubkeys) {
+ PGPKey pub, sec;
- QString id = pkey.keyItems.first().id;
+ QString id = pkey.keyItems.first().id;
- MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
- // not secret, in keyring
- kc->set(pkey, false, true, pkey.isTrusted);
- pub.change(kc);
+ MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
+ // not secret, in keyring
+ kc->set(pkey, false, true, pkey.isTrusted);
+ pub.change(kc);
- // optional
- sec = getSecKey(id, pkey.userIds);
+ // optional
+ sec = getSecKey(id, pkey.userIds);
- MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider());
- c->_storeId = storeId(0);
- c->_storeName = name(0);
- out.append(c);
- }
+ MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider());
+ c->_storeId = storeId(0);
+ c->_storeName = name(0);
+ out.append(c);
+ }
- return out;
+ return out;
}
KeyStoreEntryContext *MyKeyStoreList::entry(int, const QString &entryId)
{
- QMutexLocker locker(&ringMutex);
+ QMutexLocker locker(&ringMutex);
- PGPKey pub = getPubKey(entryId);
- if(pub.isNull())
- return 0;
+ PGPKey pub = getPubKey(entryId);
+ if (pub.isNull()) {
+ return 0;
+ }
- // optional
- PGPKey sec = getSecKey(entryId, static_cast<MyPGPKeyContext *>(pub.context())->_props.userIds);
+ // optional
+ PGPKey sec = getSecKey(entryId, static_cast<MyPGPKeyContext *>(pub.context())->_props.userIds);
- MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider());
- c->_storeId = storeId(0);
- c->_storeName = name(0);
- return c;
+ MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider());
+ c->_storeId = storeId(0);
+ c->_storeName = name(0);
+ return c;
}
KeyStoreEntryContext *MyKeyStoreList::entryPassive(const QString &serialized)
{
- QMutexLocker locker(&ringMutex);
-
- QStringList parts = serialized.split(':');
- if(parts.count() < 2)
- return 0;
- if(unescape_string(parts[0]) != "qca-gnupg-1")
- return 0;
-
- QString entryId = unescape_string(parts[1]);
- if(entryId.isEmpty())
- return 0;
-
- PGPKey pub = getPubKey(entryId);
- if(pub.isNull())
- return 0;
-
- // optional
- PGPKey sec = getSecKey(entryId, static_cast<MyPGPKeyContext *>(pub.context())->_props.userIds);
-
- MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider());
- c->_storeId = storeId(0);
- c->_storeName = name(0);
- return c;
+ QMutexLocker locker(&ringMutex);
+
+ QStringList parts = serialized.split(':');
+ if (parts.count() < 2) {
+ return 0;
+ }
+ if (unescape_string(parts[0]) != "qca-gnupg-1") {
+ return 0;
+ }
+
+ QString entryId = unescape_string(parts[1]);
+ if (entryId.isEmpty()) {
+ return 0;
+ }
+
+ PGPKey pub = getPubKey(entryId);
+ if (pub.isNull()) {
+ return 0;
+ }
+
+ // optional
+ PGPKey sec = getSecKey(entryId, static_cast<MyPGPKeyContext *>(pub.context())->_props.userIds);
+
+ MyKeyStoreEntry *c = new MyKeyStoreEntry(pub, sec, provider());
+ c->_storeId = storeId(0);
+ c->_storeName = name(0);
+ return c;
}
// TODO: cache should reflect this change immediately
QString MyKeyStoreList::writeEntry(int, const PGPKey &key)
{
- const MyPGPKeyContext *kc = static_cast<const MyPGPKeyContext *>(key.context());
- QByteArray buf = kc->toBinary();
-
- GpgOp gpg(find_bin());
- gpg.doImport(buf);
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- if(!gpg.success())
- return QString();
-
- return kc->_props.keyId;
+ const MyPGPKeyContext *kc = static_cast<const MyPGPKeyContext *>(key.context());
+ QByteArray buf = kc->toBinary();
+
+ GpgOp gpg(find_bin());
+ gpg.doImport(buf);
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ if (!gpg.success()) {
+ return QString();
+ }
+
+ return kc->_props.keyId;
}
// TODO: cache should reflect this change immediately
bool MyKeyStoreList::removeEntry(int, const QString &entryId)
{
- ringMutex.lock();
- PGPKey pub = getPubKey(entryId);
- ringMutex.unlock();
-
- const MyPGPKeyContext *kc = static_cast<const MyPGPKeyContext *>(pub.context());
- QString fingerprint = kc->_props.fingerprint;
-
- GpgOp gpg(find_bin());
- gpg.doDeleteKey(fingerprint);
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- return gpg.success();
+ ringMutex.lock();
+ PGPKey pub = getPubKey(entryId);
+ ringMutex.unlock();
+
+ const MyPGPKeyContext *kc = static_cast<const MyPGPKeyContext *>(pub.context());
+ QString fingerprint = kc->_props.fingerprint;
+
+ GpgOp gpg(find_bin());
+ gpg.doDeleteKey(fingerprint);
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ return gpg.success();
}
MyKeyStoreList *MyKeyStoreList::instance()
{
- QMutexLocker locker(ksl_mutex());
- return keyStoreList;
+ QMutexLocker locker(ksl_mutex());
+ return keyStoreList;
}
void MyKeyStoreList::ext_keyStoreLog(const QString &str)
{
- if(str.isEmpty())
- return;
+ if (str.isEmpty()) {
+ return;
+ }
- // FIXME: collect and emit in one pass
- QMetaObject::invokeMethod(this, "diagnosticText", Qt::QueuedConnection, Q_ARG(QString, str));
+ // FIXME: collect and emit in one pass
+ QMetaObject::invokeMethod(this, "diagnosticText", Qt::QueuedConnection, Q_ARG(QString, str));
}
PGPKey MyKeyStoreList::getPubKey(const QString &keyId) const
{
- int at = -1;
- for(int n = 0; n < pubkeys.count(); ++n)
- {
- if(pubkeys[n].keyItems.first().id == keyId)
- {
- at = n;
- break;
- }
- }
- if(at == -1)
- return PGPKey();
-
- const GpgOp::Key &pkey = pubkeys[at];
-
- PGPKey pub;
- MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
- // not secret, in keyring
- kc->set(pkey, false, true, pkey.isTrusted);
- pub.change(kc);
-
- return pub;
+ int at = -1;
+ for (int n = 0; n < pubkeys.count(); ++n) {
+ if (pubkeys[n].keyItems.first().id == keyId) {
+ at = n;
+ break;
+ }
+ }
+ if (at == -1) {
+ return PGPKey();
+ }
+
+ const GpgOp::Key &pkey = pubkeys[at];
+
+ PGPKey pub;
+ MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
+ // not secret, in keyring
+ kc->set(pkey, false, true, pkey.isTrusted);
+ pub.change(kc);
+
+ return pub;
}
PGPKey MyKeyStoreList::getSecKey(const QString &keyId, const QStringList &userIdsOverride) const
{
- Q_UNUSED(userIdsOverride);
-
- int at = -1;
- for(int n = 0; n < seckeys.count(); ++n)
- {
- if(seckeys[n].keyItems.first().id == keyId)
- {
- at = n;
- break;
- }
- }
- if(at == -1)
- return PGPKey();
-
- const GpgOp::Key &skey = seckeys[at];
-
- PGPKey sec;
- MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
- // secret, in keyring, trusted
- kc->set(skey, true, true, true);
- //kc->_props.userIds = userIdsOverride;
- sec.change(kc);
-
- return sec;
+ Q_UNUSED(userIdsOverride);
+
+ int at = -1;
+ for (int n = 0; n < seckeys.count(); ++n) {
+ if (seckeys[n].keyItems.first().id == keyId) {
+ at = n;
+ break;
+ }
+ }
+ if (at == -1) {
+ return PGPKey();
+ }
+
+ const GpgOp::Key &skey = seckeys[at];
+
+ PGPKey sec;
+ MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
+ // secret, in keyring, trusted
+ kc->set(skey, true, true, true);
+ //kc->_props.userIds = userIdsOverride;
+ sec.change(kc);
+
+ return sec;
}
PGPKey MyKeyStoreList::publicKeyFromId(const QString &keyId)
{
- QMutexLocker locker(&ringMutex);
-
- int at = -1;
- for(int n = 0; n < pubkeys.count(); ++n)
- {
- const GpgOp::Key &pkey = pubkeys[n];
- for(int k = 0; k < pkey.keyItems.count(); ++k)
- {
- const GpgOp::KeyItem &ki = pkey.keyItems[k];
- if(ki.id == keyId)
- {
- at = n;
- break;
- }
- }
- if(at != -1)
- break;
- }
- if(at == -1)
- return PGPKey();
-
- const GpgOp::Key &pkey = pubkeys[at];
-
- PGPKey pub;
- MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
- // not secret, in keyring
- kc->set(pkey, false, true, pkey.isTrusted);
- pub.change(kc);
-
- return pub;
+ QMutexLocker locker(&ringMutex);
+
+ int at = -1;
+ for (int n = 0; n < pubkeys.count(); ++n) {
+ const GpgOp::Key &pkey = pubkeys[n];
+ for (int k = 0; k < pkey.keyItems.count(); ++k) {
+ const GpgOp::KeyItem &ki = pkey.keyItems[k];
+ if (ki.id == keyId) {
+ at = n;
+ break;
+ }
+ }
+ if (at != -1) {
+ break;
+ }
+ }
+ if (at == -1) {
+ return PGPKey();
+ }
+
+ const GpgOp::Key &pkey = pubkeys[at];
+
+ PGPKey pub;
+ MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
+ // not secret, in keyring
+ kc->set(pkey, false, true, pkey.isTrusted);
+ pub.change(kc);
+
+ return pub;
}
PGPKey MyKeyStoreList::secretKeyFromId(const QString &keyId)
{
- QMutexLocker locker(&ringMutex);
-
- int at = -1;
- for(int n = 0; n < seckeys.count(); ++n)
- {
- const GpgOp::Key &skey = seckeys[n];
- for(int k = 0; k < skey.keyItems.count(); ++k)
- {
- const GpgOp::KeyItem &ki = skey.keyItems[k];
- if(ki.id == keyId)
- {
- at = n;
- break;
- }
- }
- if(at != -1)
- break;
- }
- if(at == -1)
- return PGPKey();
-
- const GpgOp::Key &skey = seckeys[at];
-
- PGPKey sec;
- MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
- // secret, in keyring, trusted
- kc->set(skey, true, true, true);
- sec.change(kc);
-
- return sec;
+ QMutexLocker locker(&ringMutex);
+
+ int at = -1;
+ for (int n = 0; n < seckeys.count(); ++n) {
+ const GpgOp::Key &skey = seckeys[n];
+ for (int k = 0; k < skey.keyItems.count(); ++k) {
+ const GpgOp::KeyItem &ki = skey.keyItems[k];
+ if (ki.id == keyId) {
+ at = n;
+ break;
+ }
+ }
+ if (at != -1) {
+ break;
+ }
+ }
+ if (at == -1) {
+ return PGPKey();
+ }
+
+ const GpgOp::Key &skey = seckeys[at];
+
+ PGPKey sec;
+ MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
+ // secret, in keyring, trusted
+ kc->set(skey, true, true, true);
+ sec.change(kc);
+
+ return sec;
}
void MyKeyStoreList::gpg_finished()
{
- gpg_keyStoreLog(gpg.readDiagnosticText());
-
- if(!initialized)
- {
- // any steps that fail during init, just give up completely
- if(!gpg.success())
- {
- ringWatch.clear();
- emit busyEnd();
- return;
- }
-
- // check
- if(init_step == 0)
- {
- // obtain keyring file names for monitoring
- init_step = 1;
- homeDir = gpg.homeDir();
- gpg.doSecretKeyringFile();
- }
- // secret keyring filename
- else if(init_step == 1)
- {
- secring = QFileInfo(gpg.keyringFile()).canonicalFilePath();
-
- if(secring.isEmpty())
- {
- secring = homeDir + "/secring.gpg";
- }
- ringWatch.add(secring);
-
- // obtain keyring file names for monitoring
- init_step = 2;
- gpg.doPublicKeyringFile();
- }
- // public keyring filename
- else if(init_step == 2)
- {
- pubring = QFileInfo(gpg.keyringFile()).canonicalFilePath();
- if(pubring.isEmpty())
- {
- pubring = homeDir + "/pubring.gpg";
- }
- ringWatch.add(pubring);
-
- // cache initial keyrings
- init_step = 3;
- gpg.doSecretKeys();
- }
- else if(init_step == 3)
- {
- ringMutex.lock();
- seckeys = gpg.keys();
- ringMutex.unlock();
-
- // cache initial keyrings
- init_step = 4;
- gpg.doPublicKeys();
- }
- else if(init_step == 4)
- {
- ringMutex.lock();
- pubkeys = gpg.keys();
- ringMutex.unlock();
-
- initialized = true;
- handleDirtyRings();
- emit busyEnd();
- }
- }
- else
- {
- if(!gpg.success())
- return;
-
- GpgOp::Type op = gpg.op();
- if(op == GpgOp::SecretKeys)
- {
- ringMutex.lock();
- seckeys = gpg.keys();
- ringMutex.unlock();
-
- secdirty = false;
- }
- else if(op == GpgOp::PublicKeys)
- {
- ringMutex.lock();
- pubkeys = gpg.keys();
- ringMutex.unlock();
-
- pubdirty = false;
- }
-
- if(!secdirty && !pubdirty)
- {
- emit storeUpdated(0);
- return;
- }
-
- handleDirtyRings();
- }
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+
+ if (!initialized) {
+ // any steps that fail during init, just give up completely
+ if (!gpg.success()) {
+ ringWatch.clear();
+ emit busyEnd();
+ return;
+ }
+
+ // check
+ if (init_step == 0) {
+ // obtain keyring file names for monitoring
+ init_step = 1;
+ homeDir = gpg.homeDir();
+ gpg.doSecretKeyringFile();
+ }
+ // secret keyring filename
+ else if (init_step == 1) {
+ secring = QFileInfo(gpg.keyringFile()).canonicalFilePath();
+
+ if (secring.isEmpty()) {
+ secring = homeDir + "/secring.gpg";
+ }
+ ringWatch.add(secring);
+
+ // obtain keyring file names for monitoring
+ init_step = 2;
+ gpg.doPublicKeyringFile();
+ }
+ // public keyring filename
+ else if (init_step == 2) {
+ pubring = QFileInfo(gpg.keyringFile()).canonicalFilePath();
+ if (pubring.isEmpty()) {
+ pubring = homeDir + "/pubring.gpg";
+ }
+ ringWatch.add(pubring);
+
+ // cache initial keyrings
+ init_step = 3;
+ gpg.doSecretKeys();
+ } else if (init_step == 3) {
+ ringMutex.lock();
+ seckeys = gpg.keys();
+ ringMutex.unlock();
+
+ // cache initial keyrings
+ init_step = 4;
+ gpg.doPublicKeys();
+ } else if (init_step == 4) {
+ ringMutex.lock();
+ pubkeys = gpg.keys();
+ ringMutex.unlock();
+
+ initialized = true;
+ handleDirtyRings();
+ emit busyEnd();
+ }
+ } else {
+ if (!gpg.success()) {
+ return;
+ }
+
+ GpgOp::Type op = gpg.op();
+ if (op == GpgOp::SecretKeys) {
+ ringMutex.lock();
+ seckeys = gpg.keys();
+ ringMutex.unlock();
+
+ secdirty = false;
+ } else if (op == GpgOp::PublicKeys) {
+ ringMutex.lock();
+ pubkeys = gpg.keys();
+ ringMutex.unlock();
+
+ pubdirty = false;
+ }
+
+ if (!secdirty && !pubdirty) {
+ emit storeUpdated(0);
+ return;
+ }
+
+ handleDirtyRings();
+ }
}
void MyKeyStoreList::ring_changed(const QString &filePath)
{
- ext_keyStoreLog(QString("ring_changed: [%1]\n").arg(filePath));
+ ext_keyStoreLog(QString("ring_changed: [%1]\n").arg(filePath));
- if(filePath == secring)
- sec_changed();
- else if(filePath == pubring)
- pub_changed();
+ if (filePath == secring) {
+ sec_changed();
+ } else if (filePath == pubring) {
+ pub_changed();
+ }
}
void MyKeyStoreList::pub_changed()
{
- pubdirty = true;
- handleDirtyRings();
+ pubdirty = true;
+ handleDirtyRings();
}
void MyKeyStoreList::sec_changed()
{
- secdirty = true;
- handleDirtyRings();
+ secdirty = true;
+ handleDirtyRings();
}
void MyKeyStoreList::handleDirtyRings()
{
- if(!initialized || gpg.isActive())
- return;
-
- if(secdirty)
- gpg.doSecretKeys();
- else if(pubdirty)
- gpg.doPublicKeys();
+ if (!initialized || gpg.isActive()) {
+ return;
+ }
+
+ if (secdirty) {
+ gpg.doSecretKeys();
+ } else if (pubdirty) {
+ gpg.doPublicKeys();
+ }
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mykeystorelist.h b/plugins/qca-gnupg/mykeystorelist.h
index 859da691..ec74e95a 100644
--- a/plugins/qca-gnupg/mykeystorelist.h
+++ b/plugins/qca-gnupg/mykeystorelist.h
@@ -1,84 +1,84 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#pragma once
#include "ringwatch.h"
#include "gpgop.h"
#include "qcaprovider.h"
#include "mykeystoreentry.h"
#include <QMutex>
namespace gpgQCAPlugin
{
class MyKeyStoreList : public QCA::KeyStoreListContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- int init_step;
- bool initialized;
- GpgOp gpg;
- GpgOp::KeyList pubkeys, seckeys;
- QString pubring, secring, homeDir;
- bool pubdirty, secdirty;
- RingWatch ringWatch;
- QMutex ringMutex;
+ int init_step;
+ bool initialized;
+ GpgOp gpg;
+ GpgOp::KeyList pubkeys, seckeys;
+ QString pubring, secring, homeDir;
+ bool pubdirty, secdirty;
+ RingWatch ringWatch;
+ QMutex ringMutex;
- MyKeyStoreList(QCA::Provider *p);
- ~MyKeyStoreList();
+ MyKeyStoreList(QCA::Provider *p);
+ ~MyKeyStoreList();
- // reimplemented Provider::Context
- QCA::Provider::Context *clone() const;
+ // reimplemented Provider::Context
+ QCA::Provider::Context *clone() const;
- // reimplemented KeyStoreListContext
- QString name(int) const;
- QCA::KeyStore::Type type(int) const;
- QString storeId(int) const;
- QList<int> keyStores();
+ // reimplemented KeyStoreListContext
+ QString name(int) const;
+ QCA::KeyStore::Type type(int) const;
+ QString storeId(int) const;
+ QList<int> keyStores();
- void start();
+ void start();
- bool isReadOnly(int) const;
+ bool isReadOnly(int) const;
- QList<QCA::KeyStoreEntry::Type> entryTypes(int) const;
- QList<QCA::KeyStoreEntryContext*> entryList(int);
- QCA::KeyStoreEntryContext *entry(int, const QString &entryId);
- QCA::KeyStoreEntryContext *entryPassive(const QString &serialized);
- QString writeEntry(int, const QCA::PGPKey &key);
- bool removeEntry(int, const QString &entryId);
+ QList<QCA::KeyStoreEntry::Type> entryTypes(int) const;
+ QList<QCA::KeyStoreEntryContext *> entryList(int);
+ QCA::KeyStoreEntryContext *entry(int, const QString &entryId);
+ QCA::KeyStoreEntryContext *entryPassive(const QString &serialized);
+ QString writeEntry(int, const QCA::PGPKey &key);
+ bool removeEntry(int, const QString &entryId);
- static MyKeyStoreList *instance();
- void ext_keyStoreLog(const QString &str);
+ static MyKeyStoreList *instance();
+ void ext_keyStoreLog(const QString &str);
- QCA::PGPKey getPubKey(const QString &keyId) const;
- QCA::PGPKey getSecKey(const QString &keyId, const QStringList &userIdsOverride) const;
- QCA::PGPKey publicKeyFromId(const QString &keyId);
- QCA::PGPKey secretKeyFromId(const QString &keyId);
+ QCA::PGPKey getPubKey(const QString &keyId) const;
+ QCA::PGPKey getSecKey(const QString &keyId, const QStringList &userIdsOverride) const;
+ QCA::PGPKey publicKeyFromId(const QString &keyId);
+ QCA::PGPKey secretKeyFromId(const QString &keyId);
private slots:
- void gpg_finished();
- void ring_changed(const QString &filePath);
+ void gpg_finished();
+ void ring_changed(const QString &filePath);
private:
- void pub_changed();
- void sec_changed();
- void handleDirtyRings();
+ void pub_changed();
+ void sec_changed();
+ void handleDirtyRings();
};
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mymessagecontext.cpp b/plugins/qca-gnupg/mymessagecontext.cpp
index ec6253b6..ec35e8bb 100644
--- a/plugins/qca-gnupg/mymessagecontext.cpp
+++ b/plugins/qca-gnupg/mymessagecontext.cpp
@@ -1,436 +1,416 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "mymessagecontext.h"
#include "utils.h"
#include "mypgpkeycontext.h"
#include "mykeystorelist.h"
using namespace QCA;
namespace gpgQCAPlugin
{
MyMessageContext::MyMessageContext(MyOpenPGPContext *_sms, Provider *p)
- : MessageContext(p, "pgpmsg")
- , sms(_sms)
- , op(Sign)
- , signMode(SecureMessage::Detached)
- , format(SecureMessage::Ascii)
- , wrote(0)
- , ok(false)
- , wasSigned(false)
- , op_err(GpgOp::ErrorUnknown), gpg(find_bin()) ,_finished(false)
-{
- connect(&gpg, SIGNAL(readyRead()), SLOT(gpg_readyRead()));
- connect(&gpg, SIGNAL(bytesWritten(int)), SLOT(gpg_bytesWritten(int)));
- connect(&gpg, SIGNAL(finished()), SLOT(gpg_finished()));
- connect(&gpg, SIGNAL(needPassphrase(const QString &)), SLOT(gpg_needPassphrase(const QString &)));
- connect(&gpg, SIGNAL(needCard()), SLOT(gpg_needCard()));
- connect(&gpg, SIGNAL(readyReadDiagnosticText()), SLOT(gpg_readyReadDiagnosticText()));
-
- connect(&asker, SIGNAL(responseReady()), SLOT(asker_responseReady()));
- connect(&tokenAsker, SIGNAL(responseReady()), SLOT(tokenAsker_responseReady()));
+ : MessageContext(p, "pgpmsg")
+ , sms(_sms)
+ , op(Sign)
+ , signMode(SecureMessage::Detached)
+ , format(SecureMessage::Ascii)
+ , wrote(0)
+ , ok(false)
+ , wasSigned(false)
+ , op_err(GpgOp::ErrorUnknown), gpg(find_bin()), _finished(false)
+{
+ connect(&gpg, SIGNAL(readyRead()), SLOT(gpg_readyRead()));
+ connect(&gpg, SIGNAL(bytesWritten(int)), SLOT(gpg_bytesWritten(int)));
+ connect(&gpg, SIGNAL(finished()), SLOT(gpg_finished()));
+ connect(&gpg, SIGNAL(needPassphrase(QString)), SLOT(gpg_needPassphrase(QString)));
+ connect(&gpg, SIGNAL(needCard()), SLOT(gpg_needCard()));
+ connect(&gpg, SIGNAL(readyReadDiagnosticText()), SLOT(gpg_readyReadDiagnosticText()));
+
+ connect(&asker, SIGNAL(responseReady()), SLOT(asker_responseReady()));
+ connect(&tokenAsker, SIGNAL(responseReady()), SLOT(tokenAsker_responseReady()));
}
Provider::Context *MyMessageContext::clone() const
{
- return 0;
+ return 0;
}
bool MyMessageContext::canSignMultiple() const
{
- return false;
+ return false;
}
SecureMessage::Type MyMessageContext::type() const
{
- return SecureMessage::OpenPGP;
+ return SecureMessage::OpenPGP;
}
void MyMessageContext::reset()
{
- wrote = 0;
- ok = false;
- wasSigned = false;
+ wrote = 0;
+ ok = false;
+ wasSigned = false;
}
void MyMessageContext::setupEncrypt(const SecureMessageKeyList &keys)
{
- recipIds.clear();
- for(int n = 0; n < keys.count(); ++n)
- recipIds += keys[n].pgpPublicKey().keyId();
+ recipIds.clear();
+ for (int n = 0; n < keys.count(); ++n) {
+ recipIds += keys[n].pgpPublicKey().keyId();
+ }
}
void MyMessageContext::setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool, bool)
{
- signerId = keys.first().pgpSecretKey().keyId();
- signMode = m;
+ signerId = keys.first().pgpSecretKey().keyId();
+ signMode = m;
}
void MyMessageContext::setupVerify(const QByteArray &detachedSig)
{
- sig = detachedSig;
+ sig = detachedSig;
}
void MyMessageContext::start(SecureMessage::Format f, Operation op)
{
- _finished = false;
- format = f;
- this->op = op;
-
- if(getProperty("pgp-always-trust").toBool())
- gpg.setAlwaysTrust(true);
-
- if(format == SecureMessage::Ascii)
- gpg.setAsciiFormat(true);
- else
- gpg.setAsciiFormat(false);
-
- if(op == Encrypt)
- {
- gpg.doEncrypt(recipIds);
- }
- else if(op == Decrypt)
- {
- gpg.doDecrypt();
- }
- else if(op == Sign)
- {
- if(signMode == SecureMessage::Message)
- {
- gpg.doSign(signerId);
- }
- else if(signMode == SecureMessage::Clearsign)
- {
- gpg.doSignClearsign(signerId);
- }
- else // SecureMessage::Detached
- {
- gpg.doSignDetached(signerId);
- }
- }
- else if(op == Verify)
- {
- if(!sig.isEmpty())
- gpg.doVerifyDetached(sig);
- else
- gpg.doDecrypt();
- }
- else if(op == SignAndEncrypt)
- {
- gpg.doSignAndEncrypt(signerId, recipIds);
- }
+ _finished = false;
+ format = f;
+ this->op = op;
+
+ if (getProperty("pgp-always-trust").toBool()) {
+ gpg.setAlwaysTrust(true);
+ }
+
+ if (format == SecureMessage::Ascii) {
+ gpg.setAsciiFormat(true);
+ } else {
+ gpg.setAsciiFormat(false);
+ }
+
+ if (op == Encrypt) {
+ gpg.doEncrypt(recipIds);
+ } else if (op == Decrypt) {
+ gpg.doDecrypt();
+ } else if (op == Sign) {
+ if (signMode == SecureMessage::Message) {
+ gpg.doSign(signerId);
+ } else if (signMode == SecureMessage::Clearsign) {
+ gpg.doSignClearsign(signerId);
+ } else { // SecureMessage::Detached
+ gpg.doSignDetached(signerId);
+ }
+ } else if (op == Verify) {
+ if (!sig.isEmpty()) {
+ gpg.doVerifyDetached(sig);
+ } else {
+ gpg.doDecrypt();
+ }
+ } else if (op == SignAndEncrypt) {
+ gpg.doSignAndEncrypt(signerId, recipIds);
+ }
}
void MyMessageContext::update(const QByteArray &in)
{
- gpg.write(in);
- //this->in.append(in);
+ gpg.write(in);
+ //this->in.append(in);
}
QByteArray MyMessageContext::read()
{
- QByteArray a = out;
- out.clear();
- return a;
+ QByteArray a = out;
+ out.clear();
+ return a;
}
int MyMessageContext::written()
{
- int x = wrote;
- wrote = 0;
- return x;
+ int x = wrote;
+ wrote = 0;
+ return x;
}
void MyMessageContext::end()
{
- gpg.endWrite();
+ gpg.endWrite();
}
void MyMessageContext::seterror()
{
- gpg.reset();
- _finished = true;
- ok = false;
- op_err = GpgOp::ErrorUnknown;
+ gpg.reset();
+ _finished = true;
+ ok = false;
+ op_err = GpgOp::ErrorUnknown;
}
void MyMessageContext::complete()
{
- _finished = true;
-
- dtext = gpg.readDiagnosticText();
-
- ok = gpg.success();
- if(ok)
- {
- if(op == Sign && signMode == SecureMessage::Detached)
- sig = gpg.read();
- else
- out = gpg.read();
- }
-
- if(ok)
- {
- if(gpg.wasSigned())
- {
- QString signerId = gpg.signerId();
- QDateTime ts = gpg.timestamp();
- GpgOp::VerifyResult vr = gpg.verifyResult();
-
- SecureMessageSignature::IdentityResult ir;
- Validity v;
- if(vr == GpgOp::VerifyGood)
- {
- ir = SecureMessageSignature::Valid;
- v = ValidityGood;
- }
- else if(vr == GpgOp::VerifyBad)
- {
- ir = SecureMessageSignature::InvalidSignature;
- v = ValidityGood; // good key, bad sig
- }
- else // GpgOp::VerifyNoKey
- {
- ir = SecureMessageSignature::NoKey;
- v = ErrorValidityUnknown;
- }
-
- SecureMessageKey key;
- PGPKey pub = publicKeyFromId(signerId);
- if(pub.isNull())
- {
- MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
- kc->_props.keyId = signerId;
- pub.change(kc);
- }
- key.setPGPPublicKey(pub);
-
- signer = SecureMessageSignature(ir, v, key, ts);
- wasSigned = true;
- }
- }
- else
- op_err = gpg.errorCode();
+ _finished = true;
+
+ dtext = gpg.readDiagnosticText();
+
+ ok = gpg.success();
+ if (ok) {
+ if (op == Sign && signMode == SecureMessage::Detached) {
+ sig = gpg.read();
+ } else {
+ out = gpg.read();
+ }
+ }
+
+ if (ok) {
+ if (gpg.wasSigned()) {
+ QString signerId = gpg.signerId();
+ QDateTime ts = gpg.timestamp();
+ GpgOp::VerifyResult vr = gpg.verifyResult();
+
+ SecureMessageSignature::IdentityResult ir;
+ Validity v;
+ if (vr == GpgOp::VerifyGood) {
+ ir = SecureMessageSignature::Valid;
+ v = ValidityGood;
+ } else if (vr == GpgOp::VerifyBad) {
+ ir = SecureMessageSignature::InvalidSignature;
+ v = ValidityGood; // good key, bad sig
+ } else { // GpgOp::VerifyNoKey
+ ir = SecureMessageSignature::NoKey;
+ v = ErrorValidityUnknown;
+ }
+
+ SecureMessageKey key;
+ PGPKey pub = publicKeyFromId(signerId);
+ if (pub.isNull()) {
+ MyPGPKeyContext *kc = new MyPGPKeyContext(provider());
+ kc->_props.keyId = signerId;
+ pub.change(kc);
+ }
+ key.setPGPPublicKey(pub);
+
+ signer = SecureMessageSignature(ir, v, key, ts);
+ wasSigned = true;
+ }
+ } else {
+ op_err = gpg.errorCode();
+ }
}
bool MyMessageContext::finished() const
{
- return _finished;
+ return _finished;
}
bool MyMessageContext::waitForFinished(int msecs)
{
- // FIXME
- Q_UNUSED(msecs);
- MyKeyStoreList *keyStoreList = MyKeyStoreList::instance();
-
- while(1)
- {
- // TODO: handle token prompt events
-
- GpgOp::Event e = gpg.waitForEvent(-1);
- if(e.type == GpgOp::Event::NeedPassphrase)
- {
- // TODO
-
- QString keyId;
- PGPKey sec = secretKeyFromId(e.keyId);
- if(!sec.isNull())
- keyId = sec.keyId();
- else
- keyId = e.keyId;
- QStringList out;
- out += escape_string("qca-gnupg-1");
- out += escape_string(keyId);
- QString serialized = out.join(":");
-
- KeyStoreEntry kse;
- KeyStoreEntryContext *c = keyStoreList->entryPassive(serialized);
- if(c)
- kse.change(c);
-
- asker.ask(Event::StylePassphrase, KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), kse, 0);
- asker.waitForResponse();
-
- if(!asker.accepted())
- {
- seterror();
- return true;
- }
-
- gpg.submitPassphrase(asker.password());
- }
- else if(e.type == GpgOp::Event::NeedCard)
- {
- tokenAsker.ask(KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), KeyStoreEntry(), 0);
-
- if(!tokenAsker.accepted())
- {
- seterror();
- return true;
- }
-
- gpg.cardOkay();
- }
- else if(e.type == GpgOp::Event::Finished)
- break;
- }
-
- complete();
- return true;
+ // FIXME
+ Q_UNUSED(msecs);
+ MyKeyStoreList *keyStoreList = MyKeyStoreList::instance();
+
+ while (1) {
+ // TODO: handle token prompt events
+
+ GpgOp::Event e = gpg.waitForEvent(-1);
+ if (e.type == GpgOp::Event::NeedPassphrase) {
+ // TODO
+
+ QString keyId;
+ PGPKey sec = secretKeyFromId(e.keyId);
+ if (!sec.isNull()) {
+ keyId = sec.keyId();
+ } else {
+ keyId = e.keyId;
+ }
+ QStringList out;
+ out += escape_string("qca-gnupg-1");
+ out += escape_string(keyId);
+ QString serialized = out.join(":");
+
+ KeyStoreEntry kse;
+ KeyStoreEntryContext *c = keyStoreList->entryPassive(serialized);
+ if (c) {
+ kse.change(c);
+ }
+
+ asker.ask(Event::StylePassphrase, KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), kse, 0);
+ asker.waitForResponse();
+
+ if (!asker.accepted()) {
+ seterror();
+ return true;
+ }
+
+ gpg.submitPassphrase(asker.password());
+ } else if (e.type == GpgOp::Event::NeedCard) {
+ tokenAsker.ask(KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), KeyStoreEntry(), 0);
+
+ if (!tokenAsker.accepted()) {
+ seterror();
+ return true;
+ }
+
+ gpg.cardOkay();
+ } else if (e.type == GpgOp::Event::Finished) {
+ break;
+ }
+ }
+
+ complete();
+ return true;
}
bool MyMessageContext::success() const
{
- return ok;
+ return ok;
}
SecureMessage::Error MyMessageContext::errorCode() const
{
- SecureMessage::Error e = SecureMessage::ErrorUnknown;
- if(op_err == GpgOp::ErrorProcess)
- e = SecureMessage::ErrorUnknown;
- else if(op_err == GpgOp::ErrorPassphrase)
- e = SecureMessage::ErrorPassphrase;
- else if(op_err == GpgOp::ErrorFormat)
- e = SecureMessage::ErrorFormat;
- else if(op_err == GpgOp::ErrorSignerExpired)
- e = SecureMessage::ErrorSignerExpired;
- else if(op_err == GpgOp::ErrorSignerRevoked)
- e = SecureMessage::ErrorSignerRevoked;
- else if(op_err == GpgOp::ErrorSignatureExpired)
- e = SecureMessage::ErrorSignatureExpired;
- else if(op_err == GpgOp::ErrorEncryptExpired)
- e = SecureMessage::ErrorEncryptExpired;
- else if(op_err == GpgOp::ErrorEncryptRevoked)
- e = SecureMessage::ErrorEncryptRevoked;
- else if(op_err == GpgOp::ErrorEncryptUntrusted)
- e = SecureMessage::ErrorEncryptUntrusted;
- else if(op_err == GpgOp::ErrorEncryptInvalid)
- e = SecureMessage::ErrorEncryptInvalid;
- else if(op_err == GpgOp::ErrorDecryptNoKey)
- e = SecureMessage::ErrorUnknown;
- else if(op_err == GpgOp::ErrorUnknown)
- e = SecureMessage::ErrorUnknown;
- return e;
+ SecureMessage::Error e = SecureMessage::ErrorUnknown;
+ if (op_err == GpgOp::ErrorProcess) {
+ e = SecureMessage::ErrorUnknown;
+ } else if (op_err == GpgOp::ErrorPassphrase) {
+ e = SecureMessage::ErrorPassphrase;
+ } else if (op_err == GpgOp::ErrorFormat) {
+ e = SecureMessage::ErrorFormat;
+ } else if (op_err == GpgOp::ErrorSignerExpired) {
+ e = SecureMessage::ErrorSignerExpired;
+ } else if (op_err == GpgOp::ErrorSignerRevoked) {
+ e = SecureMessage::ErrorSignerRevoked;
+ } else if (op_err == GpgOp::ErrorSignatureExpired) {
+ e = SecureMessage::ErrorSignatureExpired;
+ } else if (op_err == GpgOp::ErrorEncryptExpired) {
+ e = SecureMessage::ErrorEncryptExpired;
+ } else if (op_err == GpgOp::ErrorEncryptRevoked) {
+ e = SecureMessage::ErrorEncryptRevoked;
+ } else if (op_err == GpgOp::ErrorEncryptUntrusted) {
+ e = SecureMessage::ErrorEncryptUntrusted;
+ } else if (op_err == GpgOp::ErrorEncryptInvalid) {
+ e = SecureMessage::ErrorEncryptInvalid;
+ } else if (op_err == GpgOp::ErrorDecryptNoKey) {
+ e = SecureMessage::ErrorUnknown;
+ } else if (op_err == GpgOp::ErrorUnknown) {
+ e = SecureMessage::ErrorUnknown;
+ }
+ return e;
}
QByteArray MyMessageContext::signature() const
{
- return sig;
+ return sig;
}
QString MyMessageContext::hashName() const
{
- // TODO
- return "sha1";
+ // TODO
+ return "sha1";
}
SecureMessageSignatureList MyMessageContext::signers() const
{
- SecureMessageSignatureList list;
- if(ok && wasSigned)
- list += signer;
- return list;
+ SecureMessageSignatureList list;
+ if (ok && wasSigned) {
+ list += signer;
+ }
+ return list;
}
QString MyMessageContext::diagnosticText() const
{
- return dtext;
+ return dtext;
}
void MyMessageContext::gpg_readyRead()
{
- emit updated();
+ emit updated();
}
void MyMessageContext::gpg_bytesWritten(int bytes)
{
- wrote += bytes;
+ wrote += bytes;
}
void MyMessageContext::gpg_finished()
{
- complete();
- emit updated();
+ complete();
+ emit updated();
}
void MyMessageContext::gpg_needPassphrase(const QString &in_keyId)
{
- // FIXME: copied from above, clean up later
-
- QString keyId;
- PGPKey sec = secretKeyFromId(in_keyId);
- if(!sec.isNull())
- keyId = sec.keyId();
- else
- keyId = in_keyId;
- //emit keyStoreList->storeNeedPassphrase(0, 0, keyId);
- QStringList out;
- out += escape_string("qca-gnupg-1");
- out += escape_string(keyId);
- QString serialized = out.join(":");
-
- KeyStoreEntry kse;
- MyKeyStoreList *keyStoreList = MyKeyStoreList::instance();
- KeyStoreEntryContext *c = keyStoreList->entryPassive(serialized);
- if(c)
- kse.change(c);
-
- asker.ask(Event::StylePassphrase, KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), kse, 0);
+ // FIXME: copied from above, clean up later
+
+ QString keyId;
+ PGPKey sec = secretKeyFromId(in_keyId);
+ if (!sec.isNull()) {
+ keyId = sec.keyId();
+ } else {
+ keyId = in_keyId;
+ }
+ //emit keyStoreList->storeNeedPassphrase(0, 0, keyId);
+ QStringList out;
+ out += escape_string("qca-gnupg-1");
+ out += escape_string(keyId);
+ QString serialized = out.join(":");
+
+ KeyStoreEntry kse;
+ MyKeyStoreList *keyStoreList = MyKeyStoreList::instance();
+ KeyStoreEntryContext *c = keyStoreList->entryPassive(serialized);
+ if (c) {
+ kse.change(c);
+ }
+
+ asker.ask(Event::StylePassphrase, KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), kse, 0);
}
void MyMessageContext::gpg_needCard()
{
- MyKeyStoreList *keyStoreList = MyKeyStoreList::instance();
- tokenAsker.ask(KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), KeyStoreEntry(), 0);
+ MyKeyStoreList *keyStoreList = MyKeyStoreList::instance();
+ tokenAsker.ask(KeyStoreInfo(KeyStore::PGPKeyring, keyStoreList->storeId(0), keyStoreList->name(0)), KeyStoreEntry(), 0);
}
void MyMessageContext::gpg_readyReadDiagnosticText()
{
- // TODO ?
+ // TODO ?
}
void MyMessageContext::asker_responseReady()
{
- if(!asker.accepted())
- {
- seterror();
- emit updated();
- return;
- }
+ if (!asker.accepted()) {
+ seterror();
+ emit updated();
+ return;
+ }
- SecureArray a = asker.password();
- gpg.submitPassphrase(a);
+ SecureArray a = asker.password();
+ gpg.submitPassphrase(a);
}
void MyMessageContext::tokenAsker_responseReady()
{
- if(!tokenAsker.accepted())
- {
- seterror();
- emit updated();
- return;
- }
+ if (!tokenAsker.accepted()) {
+ seterror();
+ emit updated();
+ return;
+ }
- gpg.cardOkay();
+ gpg.cardOkay();
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mymessagecontext.h b/plugins/qca-gnupg/mymessagecontext.h
index 5d98a292..0b79c26d 100644
--- a/plugins/qca-gnupg/mymessagecontext.h
+++ b/plugins/qca-gnupg/mymessagecontext.h
@@ -1,92 +1,92 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#pragma once
#include "qcaprovider.h"
#include "gpgop.h"
namespace gpgQCAPlugin
{
class MyOpenPGPContext;
class MyMessageContext : public QCA::MessageContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- MyOpenPGPContext *sms;
+ MyOpenPGPContext *sms;
- QString signerId;
- QStringList recipIds;
- QCA::MessageContext::Operation op;
- QCA::SecureMessage::SignMode signMode;
- QCA::SecureMessage::Format format;
- QByteArray in, out, sig;
- int wrote;
- bool ok, wasSigned;
- GpgOp::Error op_err;
- QCA::SecureMessageSignature signer;
- GpgOp gpg;
- bool _finished;
- QString dtext;
+ QString signerId;
+ QStringList recipIds;
+ QCA::MessageContext::Operation op;
+ QCA::SecureMessage::SignMode signMode;
+ QCA::SecureMessage::Format format;
+ QByteArray in, out, sig;
+ int wrote;
+ bool ok, wasSigned;
+ GpgOp::Error op_err;
+ QCA::SecureMessageSignature signer;
+ GpgOp gpg;
+ bool _finished;
+ QString dtext;
- QCA::PasswordAsker asker;
- QCA::TokenAsker tokenAsker;
+ QCA::PasswordAsker asker;
+ QCA::TokenAsker tokenAsker;
- MyMessageContext(MyOpenPGPContext *_sms, QCA::Provider *p);
+ MyMessageContext(MyOpenPGPContext *_sms, QCA::Provider *p);
- // reimplemented Provider::Context
- QCA::Provider::Context *clone() const;
+ // reimplemented Provider::Context
+ QCA::Provider::Context *clone() const;
- // reimplemented MessageContext
- bool canSignMultiple() const;
- QCA::SecureMessage::Type type() const;
- void reset();
- void setupEncrypt(const QCA::SecureMessageKeyList &keys);
- void setupSign(const QCA::SecureMessageKeyList &keys, QCA::SecureMessage::SignMode m, bool, bool);
- void setupVerify(const QByteArray &detachedSig);
- void start(QCA::SecureMessage::Format f, QCA::MessageContext::Operation op);
- void update(const QByteArray &in);
- QByteArray read();
- int written();
- void end();
- bool finished() const;
- bool waitForFinished(int msecs);
- bool success() const;
- QCA::SecureMessage::Error errorCode() const;
- QByteArray signature() const;
- QString hashName() const;
- QCA::SecureMessageSignatureList signers() const;
- QString diagnosticText() const;
+ // reimplemented MessageContext
+ bool canSignMultiple() const;
+ QCA::SecureMessage::Type type() const;
+ void reset();
+ void setupEncrypt(const QCA::SecureMessageKeyList &keys);
+ void setupSign(const QCA::SecureMessageKeyList &keys, QCA::SecureMessage::SignMode m, bool, bool);
+ void setupVerify(const QByteArray &detachedSig);
+ void start(QCA::SecureMessage::Format f, QCA::MessageContext::Operation op);
+ void update(const QByteArray &in);
+ QByteArray read();
+ int written();
+ void end();
+ bool finished() const;
+ bool waitForFinished(int msecs);
+ bool success() const;
+ QCA::SecureMessage::Error errorCode() const;
+ QByteArray signature() const;
+ QString hashName() const;
+ QCA::SecureMessageSignatureList signers() const;
+ QString diagnosticText() const;
- void seterror();
- void complete();
+ void seterror();
+ void complete();
private slots:
- void gpg_readyRead();
- void gpg_bytesWritten(int bytes);
- void gpg_finished();
- void gpg_needPassphrase(const QString &in_keyId);
- void gpg_needCard();
- void gpg_readyReadDiagnosticText();
- void asker_responseReady();
- void tokenAsker_responseReady();
+ void gpg_readyRead();
+ void gpg_bytesWritten(int bytes);
+ void gpg_finished();
+ void gpg_needPassphrase(const QString &in_keyId);
+ void gpg_needCard();
+ void gpg_readyReadDiagnosticText();
+ void asker_responseReady();
+ void tokenAsker_responseReady();
};
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/myopenpgpcontext.cpp b/plugins/qca-gnupg/myopenpgpcontext.cpp
index 73f791fd..e57061a9 100644
--- a/plugins/qca-gnupg/myopenpgpcontext.cpp
+++ b/plugins/qca-gnupg/myopenpgpcontext.cpp
@@ -1,43 +1,43 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "myopenpgpcontext.h"
#include "mymessagecontext.h"
using namespace QCA;
namespace gpgQCAPlugin
{
MyOpenPGPContext::MyOpenPGPContext(QCA::Provider *p)
- : SMSContext(p, "openpgp")
+ : SMSContext(p, "openpgp")
{
- // TODO
+ // TODO
}
Provider::Context *MyOpenPGPContext::clone() const
{
- return 0;
+ return 0;
}
MessageContext *MyOpenPGPContext::createMessage()
{
- return new MyMessageContext(this, provider());
+ return new MyMessageContext(this, provider());
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/myopenpgpcontext.h b/plugins/qca-gnupg/myopenpgpcontext.h
index fcf91dcc..b52eb261 100644
--- a/plugins/qca-gnupg/myopenpgpcontext.h
+++ b/plugins/qca-gnupg/myopenpgpcontext.h
@@ -1,39 +1,38 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#pragma once
#include "qcaprovider.h"
namespace gpgQCAPlugin
{
class MyOpenPGPContext : public QCA::SMSContext
{
public:
- MyOpenPGPContext(QCA::Provider *p);
+ MyOpenPGPContext(QCA::Provider *p);
- // reimplemented Provider::Context
- QCA::Provider::Context *clone() const;
+ // reimplemented Provider::Context
+ QCA::Provider::Context *clone() const;
- // reimplemented SMSContext
- QCA::MessageContext *createMessage();
+ // reimplemented SMSContext
+ QCA::MessageContext *createMessage();
};
-
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mypgpkeycontext.cpp b/plugins/qca-gnupg/mypgpkeycontext.cpp
index 07a6e8f0..8570329c 100644
--- a/plugins/qca-gnupg/mypgpkeycontext.cpp
+++ b/plugins/qca-gnupg/mypgpkeycontext.cpp
@@ -1,218 +1,208 @@
#include "mypgpkeycontext.h"
#include "utils.h"
#include "gpgop.h"
#include <QTemporaryFile>
#include <QDir>
using namespace QCA;
namespace gpgQCAPlugin
{
MyPGPKeyContext::MyPGPKeyContext(Provider *p)
- : PGPKeyContext(p)
+ : PGPKeyContext(p)
{
- // zero out the props
- _props.isSecret = false;
- _props.inKeyring = true;
- _props.isTrusted = false;
+ // zero out the props
+ _props.isSecret = false;
+ _props.inKeyring = true;
+ _props.isTrusted = false;
}
Provider::Context *MyPGPKeyContext::clone() const
{
- return new MyPGPKeyContext(*this);
+ return new MyPGPKeyContext(*this);
}
const PGPKeyContextProps *MyPGPKeyContext::props() const
{
- return &_props;
+ return &_props;
}
QByteArray MyPGPKeyContext::toBinary() const
{
- if(_props.inKeyring)
- {
- GpgOp gpg(find_bin());
- gpg.setAsciiFormat(false);
- gpg.doExport(_props.keyId);
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- if(!gpg.success())
- return QByteArray();
- return gpg.read();
- }
- else
- return cacheExportBinary;
+ if (_props.inKeyring) {
+ GpgOp gpg(find_bin());
+ gpg.setAsciiFormat(false);
+ gpg.doExport(_props.keyId);
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ if (!gpg.success()) {
+ return QByteArray();
+ }
+ return gpg.read();
+ } else {
+ return cacheExportBinary;
+ }
}
ConvertResult MyPGPKeyContext::fromBinary(const QByteArray &a)
{
- GpgOp::Key key;
- bool sec = false;
-
- // temporary keyrings
- QString pubname, secname;
-
- QTemporaryFile pubtmp(QDir::tempPath() + QLatin1String("/qca_gnupg_tmp.XXXXXX.gpg"));
- if(!pubtmp.open())
- return ErrorDecode;
-
- QTemporaryFile sectmp(QDir::tempPath() + QLatin1String("/qca_gnupg_tmp.XXXXXX.gpg"));
- if(!sectmp.open())
- return ErrorDecode;
-
- pubname = pubtmp.fileName();
- secname = sectmp.fileName();
-
- // we turn off autoRemove so that we can close the files
- // without them getting deleted
- pubtmp.setAutoRemove(false);
- sectmp.setAutoRemove(false);
- pubtmp.close();
- sectmp.close();
-
- // import key into temporary keyring
- GpgOp gpg(find_bin());
- gpg.setKeyrings(pubname, secname);
- gpg.doImport(a);
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- // comment this out. apparently gpg will report failure for
- // an import if there are trust issues, even though the
- // key actually did get imported
- /*if(!gpg.success())
- {
- cleanup_temp_keyring(pubname);
- cleanup_temp_keyring(secname);
- return ErrorDecode;
- }*/
-
- // now extract the key from gpg like normal
-
- // is it a public key?
- gpg.doPublicKeys();
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- if(!gpg.success())
- {
- cleanup_temp_keyring(pubname);
- cleanup_temp_keyring(secname);
- return ErrorDecode;
- }
-
- GpgOp::KeyList pubkeys = gpg.keys();
- if(!pubkeys.isEmpty())
- {
- key = pubkeys.first();
- }
- else
- {
- // is it a secret key?
- gpg.doSecretKeys();
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- if(!gpg.success())
- {
- cleanup_temp_keyring(pubname);
- cleanup_temp_keyring(secname);
- return ErrorDecode;
- }
-
- GpgOp::KeyList seckeys = gpg.keys();
- if(!seckeys.isEmpty())
- {
- key = seckeys.first();
- sec = true;
- }
- else
- {
- // no keys found
- cleanup_temp_keyring(pubname);
- cleanup_temp_keyring(secname);
- return ErrorDecode;
- }
- }
-
- // export binary/ascii and cache
-
- gpg.setAsciiFormat(false);
- gpg.doExport(key.keyItems.first().id);
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- if(!gpg.success())
- {
- cleanup_temp_keyring(pubname);
- cleanup_temp_keyring(secname);
- return ErrorDecode;
- }
- cacheExportBinary = gpg.read();
-
- gpg.setAsciiFormat(true);
- gpg.doExport(key.keyItems.first().id);
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- if(!gpg.success())
- {
- cleanup_temp_keyring(pubname);
- cleanup_temp_keyring(secname);
- return ErrorDecode;
- }
- cacheExportAscii = QString::fromLocal8Bit(gpg.read());
-
- // all done
-
- cleanup_temp_keyring(pubname);
- cleanup_temp_keyring(secname);
-
- set(key, sec, false, false);
- return ConvertGood;
+ GpgOp::Key key;
+ bool sec = false;
+
+ // temporary keyrings
+ QString pubname, secname;
+
+ QTemporaryFile pubtmp(QDir::tempPath() + QLatin1String("/qca_gnupg_tmp.XXXXXX.gpg"));
+ if (!pubtmp.open()) {
+ return ErrorDecode;
+ }
+
+ QTemporaryFile sectmp(QDir::tempPath() + QLatin1String("/qca_gnupg_tmp.XXXXXX.gpg"));
+ if (!sectmp.open()) {
+ return ErrorDecode;
+ }
+
+ pubname = pubtmp.fileName();
+ secname = sectmp.fileName();
+
+ // we turn off autoRemove so that we can close the files
+ // without them getting deleted
+ pubtmp.setAutoRemove(false);
+ sectmp.setAutoRemove(false);
+ pubtmp.close();
+ sectmp.close();
+
+ // import key into temporary keyring
+ GpgOp gpg(find_bin());
+ gpg.setKeyrings(pubname, secname);
+ gpg.doImport(a);
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ // comment this out. apparently gpg will report failure for
+ // an import if there are trust issues, even though the
+ // key actually did get imported
+ /*if(!gpg.success())
+ {
+ cleanup_temp_keyring(pubname);
+ cleanup_temp_keyring(secname);
+ return ErrorDecode;
+ }*/
+
+ // now extract the key from gpg like normal
+
+ // is it a public key?
+ gpg.doPublicKeys();
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ if (!gpg.success()) {
+ cleanup_temp_keyring(pubname);
+ cleanup_temp_keyring(secname);
+ return ErrorDecode;
+ }
+
+ GpgOp::KeyList pubkeys = gpg.keys();
+ if (!pubkeys.isEmpty()) {
+ key = pubkeys.first();
+ } else {
+ // is it a secret key?
+ gpg.doSecretKeys();
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ if (!gpg.success()) {
+ cleanup_temp_keyring(pubname);
+ cleanup_temp_keyring(secname);
+ return ErrorDecode;
+ }
+
+ GpgOp::KeyList seckeys = gpg.keys();
+ if (!seckeys.isEmpty()) {
+ key = seckeys.first();
+ sec = true;
+ } else {
+ // no keys found
+ cleanup_temp_keyring(pubname);
+ cleanup_temp_keyring(secname);
+ return ErrorDecode;
+ }
+ }
+
+ // export binary/ascii and cache
+
+ gpg.setAsciiFormat(false);
+ gpg.doExport(key.keyItems.first().id);
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ if (!gpg.success()) {
+ cleanup_temp_keyring(pubname);
+ cleanup_temp_keyring(secname);
+ return ErrorDecode;
+ }
+ cacheExportBinary = gpg.read();
+
+ gpg.setAsciiFormat(true);
+ gpg.doExport(key.keyItems.first().id);
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ if (!gpg.success()) {
+ cleanup_temp_keyring(pubname);
+ cleanup_temp_keyring(secname);
+ return ErrorDecode;
+ }
+ cacheExportAscii = QString::fromLocal8Bit(gpg.read());
+
+ // all done
+
+ cleanup_temp_keyring(pubname);
+ cleanup_temp_keyring(secname);
+
+ set(key, sec, false, false);
+ return ConvertGood;
}
QString MyPGPKeyContext::toAscii() const
{
- if(_props.inKeyring)
- {
- GpgOp gpg(find_bin());
- gpg.setAsciiFormat(true);
- gpg.doExport(_props.keyId);
- gpg_waitForFinished(&gpg);
- gpg_keyStoreLog(gpg.readDiagnosticText());
- if(!gpg.success())
- return QString();
- return QString::fromLocal8Bit(gpg.read());
- }
- else
- {
- return cacheExportAscii;
- }
+ if (_props.inKeyring) {
+ GpgOp gpg(find_bin());
+ gpg.setAsciiFormat(true);
+ gpg.doExport(_props.keyId);
+ gpg_waitForFinished(&gpg);
+ gpg_keyStoreLog(gpg.readDiagnosticText());
+ if (!gpg.success()) {
+ return QString();
+ }
+ return QString::fromLocal8Bit(gpg.read());
+ } else {
+ return cacheExportAscii;
+ }
}
ConvertResult MyPGPKeyContext::fromAscii(const QString &s)
{
- // GnuPG does ascii/binary detection for imports, so for
- // simplicity we consider an ascii import to just be a
- // binary import that happens to be comprised of ascii
- return fromBinary(s.toLocal8Bit());
+ // GnuPG does ascii/binary detection for imports, so for
+ // simplicity we consider an ascii import to just be a
+ // binary import that happens to be comprised of ascii
+ return fromBinary(s.toLocal8Bit());
}
void MyPGPKeyContext::set(const GpgOp::Key &i, bool isSecret, bool inKeyring, bool isTrusted)
{
- const GpgOp::KeyItem &ki = i.keyItems.first();
-
- _props.keyId = ki.id;
- _props.userIds = i.userIds;
- _props.isSecret = isSecret;
- _props.creationDate = ki.creationDate;
- _props.expirationDate = ki.expirationDate;
- _props.fingerprint = ki.fingerprint.toLower();
- _props.inKeyring = inKeyring;
- _props.isTrusted = isTrusted;
+ const GpgOp::KeyItem &ki = i.keyItems.first();
+
+ _props.keyId = ki.id;
+ _props.userIds = i.userIds;
+ _props.isSecret = isSecret;
+ _props.creationDate = ki.creationDate;
+ _props.expirationDate = ki.expirationDate;
+ _props.fingerprint = ki.fingerprint.toLower();
+ _props.inKeyring = inKeyring;
+ _props.isTrusted = isTrusted;
}
void MyPGPKeyContext::cleanup_temp_keyring(const QString &name)
{
- QFile::remove(name);
- QFile::remove(name + '~'); // remove possible backup file
+ QFile::remove(name);
+ QFile::remove(name + '~'); // remove possible backup file
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/mypgpkeycontext.h b/plugins/qca-gnupg/mypgpkeycontext.h
index 925951d7..885a8e70 100644
--- a/plugins/qca-gnupg/mypgpkeycontext.h
+++ b/plugins/qca-gnupg/mypgpkeycontext.h
@@ -1,56 +1,56 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#pragma once
#include "qcaprovider.h"
#include "ringwatch.h"
#include "gpgop.h"
namespace gpgQCAPlugin
{
class MyPGPKeyContext : public QCA::PGPKeyContext
{
public:
- QCA::PGPKeyContextProps _props;
+ QCA::PGPKeyContextProps _props;
- // keys loaded externally (not from the keyring) need to have these
- // values cached, since we can't extract them later
- QByteArray cacheExportBinary;
- QString cacheExportAscii;
+ // keys loaded externally (not from the keyring) need to have these
+ // values cached, since we can't extract them later
+ QByteArray cacheExportBinary;
+ QString cacheExportAscii;
- MyPGPKeyContext(QCA::Provider *p);
+ MyPGPKeyContext(QCA::Provider *p);
- // reimplemented Provider::Context
- QCA::Provider::Context *clone() const;
+ // reimplemented Provider::Context
+ QCA::Provider::Context *clone() const;
- // reimplemented PGPKeyContext
- const QCA::PGPKeyContextProps *props() const;
+ // reimplemented PGPKeyContext
+ const QCA::PGPKeyContextProps *props() const;
- QByteArray toBinary() const;
- QCA::ConvertResult fromBinary(const QByteArray &a);
+ QByteArray toBinary() const;
+ QCA::ConvertResult fromBinary(const QByteArray &a);
- QString toAscii() const;
- QCA::ConvertResult fromAscii(const QString &s);
+ QString toAscii() const;
+ QCA::ConvertResult fromAscii(const QString &s);
- void set(const GpgOp::Key &i, bool isSecret, bool inKeyring, bool isTrusted);
- static void cleanup_temp_keyring(const QString &name);
+ void set(const GpgOp::Key &i, bool isSecret, bool inKeyring, bool isTrusted);
+ static void cleanup_temp_keyring(const QString &name);
};
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/qca-gnupg.cpp b/plugins/qca-gnupg/qca-gnupg.cpp
index 748af80f..697e9add 100644
--- a/plugins/qca-gnupg/qca-gnupg.cpp
+++ b/plugins/qca-gnupg/qca-gnupg.cpp
@@ -1,80 +1,84 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "mypgpkeycontext.h"
#include "myopenpgpcontext.h"
#include "mykeystorelist.h"
#include "qcaprovider.h"
#include <QtPlugin>
using namespace gpgQCAPlugin;
class gnupgProvider : public QCA::Provider
{
public:
- virtual void init()
- {
- }
+ virtual void init()
+ {
+ }
- virtual int qcaVersion() const
- {
- return QCA_VERSION;
- }
+ virtual int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
- virtual QString name() const
- {
- return "qca-gnupg";
- }
+ virtual QString name() const
+ {
+ return "qca-gnupg";
+ }
- virtual QStringList features() const
- {
- QStringList list;
- list += "pgpkey";
- list += "openpgp";
- list += "keystorelist";
- return list;
- }
+ virtual QStringList features() const
+ {
+ QStringList list;
+ list += "pgpkey";
+ list += "openpgp";
+ list += "keystorelist";
+ return list;
+ }
- virtual Context *createContext(const QString &type)
- {
- if(type == "pgpkey")
- return new MyPGPKeyContext(this);
- else if(type == "openpgp")
- return new MyOpenPGPContext(this);
- else if(type == "keystorelist")
- return new MyKeyStoreList(this);
- else
- return 0;
- }
+ virtual Context *createContext(const QString &type)
+ {
+ if (type == "pgpkey") {
+ return new MyPGPKeyContext(this);
+ } else if (type == "openpgp") {
+ return new MyOpenPGPContext(this);
+ } else if (type == "keystorelist") {
+ return new MyKeyStoreList(this);
+ } else {
+ return 0;
+ }
+ }
};
class gnupgPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual QCA::Provider *createProvider() { return new gnupgProvider; }
+ virtual QCA::Provider *createProvider()
+ {
+ return new gnupgProvider;
+ }
};
#include "qca-gnupg.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_gnupg, gnupgPlugin)
#endif
diff --git a/plugins/qca-gnupg/ringwatch.cpp b/plugins/qca-gnupg/ringwatch.cpp
index 96abf077..1011647f 100644
--- a/plugins/qca-gnupg/ringwatch.cpp
+++ b/plugins/qca-gnupg/ringwatch.cpp
@@ -1,185 +1,179 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
// since keyring files are often modified by creating a new copy and
// overwriting the original file, this messes up Qt's file watching
// capability since the original file goes away. to work around this
// problem, we'll watch the directories containing the keyring files
// instead of watching the actual files themselves.
//
// FIXME: qca 2.0.1 FileWatch has this logic already, so we can probably
// simplify this class.
#include "qca_safetimer.h"
#include "qca_support.h"
#include "ringwatch.h"
#include <QFileInfo>
using namespace QCA;
namespace gpgQCAPlugin
{
RingWatch::RingWatch(QObject *parent)
- : QObject(parent)
+ : QObject(parent)
{
}
RingWatch::~RingWatch()
{
- clear();
+ clear();
}
void RingWatch::add(const QString &filePath)
{
- QFileInfo fi(filePath);
- // Try to avoid symbolic links
- QString path = fi.canonicalPath();
- if (path.isEmpty())
- path = fi.absolutePath();
-
- // watching this path already?
- DirWatch *dirWatch = 0;
- foreach(const DirItem &di, dirs)
- {
- if(di.dirWatch->dirName() == path)
- {
- dirWatch = di.dirWatch;
- break;
- }
- }
-
- // if not, make a watcher
- if(!dirWatch)
- {
- //printf("creating dirwatch for [%s]\n", qPrintable(path));
-
- DirItem di;
- di.dirWatch = new DirWatch(path, this);
- connect(di.dirWatch, SIGNAL(changed()), SLOT(dirChanged()));
-
- di.changeTimer = new SafeTimer(this);
- di.changeTimer->setSingleShot(true);
- connect(di.changeTimer, SIGNAL(timeout()), SLOT(handleChanged()));
-
- dirWatch = di.dirWatch;
- dirs += di;
- }
-
- FileItem i;
- i.dirWatch = dirWatch;
- i.fileName = fi.fileName();
- i.exists = fi.exists();
- if(i.exists)
- {
- i.size = fi.size();
- i.lastModified = fi.lastModified();
- }
- files += i;
-
- //printf("watching [%s] in [%s]\n", qPrintable(fi.fileName()), qPrintable(i.dirWatch->dirName()));
+ QFileInfo fi(filePath);
+ // Try to avoid symbolic links
+ QString path = fi.canonicalPath();
+ if (path.isEmpty()) {
+ path = fi.absolutePath();
+ }
+
+ // watching this path already?
+ DirWatch *dirWatch = 0;
+ foreach (const DirItem &di, dirs) {
+ if (di.dirWatch->dirName() == path) {
+ dirWatch = di.dirWatch;
+ break;
+ }
+ }
+
+ // if not, make a watcher
+ if (!dirWatch) {
+ //printf("creating dirwatch for [%s]\n", qPrintable(path));
+
+ DirItem di;
+ di.dirWatch = new DirWatch(path, this);
+ connect(di.dirWatch, SIGNAL(changed()), SLOT(dirChanged()));
+
+ di.changeTimer = new SafeTimer(this);
+ di.changeTimer->setSingleShot(true);
+ connect(di.changeTimer, SIGNAL(timeout()), SLOT(handleChanged()));
+
+ dirWatch = di.dirWatch;
+ dirs += di;
+ }
+
+ FileItem i;
+ i.dirWatch = dirWatch;
+ i.fileName = fi.fileName();
+ i.exists = fi.exists();
+ if (i.exists) {
+ i.size = fi.size();
+ i.lastModified = fi.lastModified();
+ }
+ files += i;
+
+ //printf("watching [%s] in [%s]\n", qPrintable(fi.fileName()), qPrintable(i.dirWatch->dirName()));
}
void RingWatch::clear()
{
- files.clear();
+ files.clear();
- foreach(const DirItem &di, dirs)
- {
- delete di.changeTimer;
- delete di.dirWatch;
- }
+ foreach (const DirItem &di, dirs) {
+ delete di.changeTimer;
+ delete di.dirWatch;
+ }
- dirs.clear();
+ dirs.clear();
}
void RingWatch::dirChanged()
{
- DirWatch *dirWatch = (DirWatch *)sender();
-
- int at = -1;
- for(int n = 0; n < dirs.count(); ++n)
- {
- if(dirs[n].dirWatch == dirWatch)
- {
- at = n;
- break;
- }
- }
- if(at == -1)
- return;
-
- // we get a ton of change notifications for the dir when
- // something happens.. let's collect them and only
- // report after 100ms
-
- if(!dirs[at].changeTimer->isActive())
- dirs[at].changeTimer->start(100);
+ DirWatch *dirWatch = (DirWatch *)sender();
+
+ int at = -1;
+ for (int n = 0; n < dirs.count(); ++n) {
+ if (dirs[n].dirWatch == dirWatch) {
+ at = n;
+ break;
+ }
+ }
+ if (at == -1) {
+ return;
+ }
+
+ // we get a ton of change notifications for the dir when
+ // something happens.. let's collect them and only
+ // report after 100ms
+
+ if (!dirs[at].changeTimer->isActive()) {
+ dirs[at].changeTimer->start(100);
+ }
}
void RingWatch::handleChanged()
{
- SafeTimer *t = (SafeTimer *)sender();
-
- int at = -1;
- for(int n = 0; n < dirs.count(); ++n)
- {
- if(dirs[n].changeTimer == t)
- {
- at = n;
- break;
- }
- }
- if(at == -1)
- return;
-
- DirWatch *dirWatch = dirs[at].dirWatch;
- QString dir = dirWatch->dirName();
-
- // see which files changed
- QStringList changeList;
- for(int n = 0; n < files.count(); ++n)
- {
- FileItem &i = files[n];
- QString filePath = dir + '/' + i.fileName;
- QFileInfo fi(filePath);
-
- // if the file didn't exist, and still doesn't, skip
- if(!i.exists && !fi.exists())
- continue;
-
- // size/lastModified should only get checked here if
- // the file existed and still exists
- if(fi.exists() != i.exists || fi.size() != i.size || fi.lastModified() != i.lastModified)
- {
- changeList += filePath;
-
- i.exists = fi.exists();
- if(i.exists)
- {
- i.size = fi.size();
- i.lastModified = fi.lastModified();
- }
- }
- }
-
- foreach(const QString &s, changeList)
- emit changed(s);
+ SafeTimer *t = (SafeTimer *)sender();
+
+ int at = -1;
+ for (int n = 0; n < dirs.count(); ++n) {
+ if (dirs[n].changeTimer == t) {
+ at = n;
+ break;
+ }
+ }
+ if (at == -1) {
+ return;
+ }
+
+ DirWatch *dirWatch = dirs[at].dirWatch;
+ QString dir = dirWatch->dirName();
+
+ // see which files changed
+ QStringList changeList;
+ for (int n = 0; n < files.count(); ++n) {
+ FileItem &i = files[n];
+ QString filePath = dir + '/' + i.fileName;
+ QFileInfo fi(filePath);
+
+ // if the file didn't exist, and still doesn't, skip
+ if (!i.exists && !fi.exists()) {
+ continue;
+ }
+
+ // size/lastModified should only get checked here if
+ // the file existed and still exists
+ if (fi.exists() != i.exists || fi.size() != i.size || fi.lastModified() != i.lastModified) {
+ changeList += filePath;
+
+ i.exists = fi.exists();
+ if (i.exists) {
+ i.size = fi.size();
+ i.lastModified = fi.lastModified();
+ }
+ }
+ }
+
+ foreach (const QString &s, changeList) {
+ emit changed(s);
+ }
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/ringwatch.h b/plugins/qca-gnupg/ringwatch.h
index cb3fa342..5adf1b54 100644
--- a/plugins/qca-gnupg/ringwatch.h
+++ b/plugins/qca-gnupg/ringwatch.h
@@ -1,74 +1,74 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#pragma once
#include <QObject>
#include <QDateTime>
#include <QList>
namespace QCA
{
class SafeTimer;
class DirWatch;
}
namespace gpgQCAPlugin
{
class RingWatch : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- class DirItem
- {
- public:
- QCA::DirWatch *dirWatch;
- QCA::SafeTimer *changeTimer;
- };
+ class DirItem
+ {
+ public:
+ QCA::DirWatch *dirWatch;
+ QCA::SafeTimer *changeTimer;
+ };
- class FileItem
- {
- public:
- QCA::DirWatch *dirWatch;
- QString fileName;
- bool exists;
- qint64 size;
- QDateTime lastModified;
- };
+ class FileItem
+ {
+ public:
+ QCA::DirWatch *dirWatch;
+ QString fileName;
+ bool exists;
+ qint64 size;
+ QDateTime lastModified;
+ };
- QList<DirItem> dirs;
- QList<FileItem> files;
+ QList<DirItem> dirs;
+ QList<FileItem> files;
- RingWatch(QObject *parent = 0);
- ~RingWatch();
+ RingWatch(QObject *parent = 0);
+ ~RingWatch();
- void add(const QString &filePath);
- void clear();
+ void add(const QString &filePath);
+ void clear();
signals:
- void changed(const QString &filePath);
+ void changed(const QString &filePath);
private slots:
- void dirChanged();
- void handleChanged();
+ void dirChanged();
+ void handleChanged();
};
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-gnupg/utils.cpp b/plugins/qca-gnupg/utils.cpp
index 166bff0a..f2680bbe 100644
--- a/plugins/qca-gnupg/utils.cpp
+++ b/plugins/qca-gnupg/utils.cpp
@@ -1,228 +1,219 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
* Copyright (C) 2014 Ivan Romanov <drizt@land.ru>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "utils.h"
#include "mykeystorelist.h"
#include <QFileInfo>
#include <QStringList>
#include <QCoreApplication>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
using namespace QCA;
namespace gpgQCAPlugin
{
void gpg_waitForFinished(GpgOp *gpg)
{
- while(1)
- {
- GpgOp::Event e = gpg->waitForEvent(-1);
- if(e.type == GpgOp::Event::Finished)
- break;
- }
+ while (1) {
+ GpgOp::Event e = gpg->waitForEvent(-1);
+ if (e.type == GpgOp::Event::Finished) {
+ break;
+ }
+ }
}
void gpg_keyStoreLog(const QString &str)
{
- MyKeyStoreList *ksl = MyKeyStoreList::instance();
- if(ksl)
- ksl->ext_keyStoreLog(str);
+ MyKeyStoreList *ksl = MyKeyStoreList::instance();
+ if (ksl) {
+ ksl->ext_keyStoreLog(str);
+ }
}
inline bool check_bin(const QString &bin)
{
- QFileInfo fi(bin);
- return fi.exists();
+ QFileInfo fi(bin);
+ return fi.exists();
}
#ifdef Q_OS_WIN
static bool get_reg_key(HKEY root, const char *path, QString &value)
{
- HKEY hkey = 0;
-
- char szValue[256];
- DWORD dwLen = 256;
-
- bool res = false;
-
- if(RegOpenKeyExA(root, path, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS)
- {
- if (RegQueryValueExA(hkey, "Install Directory", NULL, NULL, (LPBYTE)szValue, &dwLen) == ERROR_SUCCESS)
- {
- value = QString::fromLocal8Bit(szValue);
- res = true;
- }
- RegCloseKey(hkey);
- }
- return res;
-}
+ HKEY hkey = 0;
+
+ char szValue[256];
+ DWORD dwLen = 256;
+ bool res = false;
+
+ if (RegOpenKeyExA(root, path, 0, KEY_QUERY_VALUE, &hkey) == ERROR_SUCCESS) {
+ if (RegQueryValueExA(hkey, "Install Directory", NULL, NULL, (LPBYTE)szValue, &dwLen) == ERROR_SUCCESS) {
+ value = QString::fromLocal8Bit(szValue);
+ res = true;
+ }
+ RegCloseKey(hkey);
+ }
+ return res;
+}
static QString find_reg_gpgProgram()
{
- QStringList bins;
- bins << "gpg.exe" << "gpg2.exe";
-
- HKEY root;
- root = HKEY_CURRENT_USER;
-
- const char *path = "Software\\GNU\\GnuPG";
- const char *path2 = "Software\\Wow6432Node\\GNU\\GnuPG";
-
- QString dir;
- // check list of possible places in registry
- get_reg_key(HKEY_CURRENT_USER, path, dir) ||
- get_reg_key(HKEY_CURRENT_USER, path2, dir) ||
- get_reg_key(HKEY_LOCAL_MACHINE, path, dir) ||
- get_reg_key(HKEY_LOCAL_MACHINE, path2, dir);
-
- if (!dir.isEmpty())
- {
- foreach (const QString &bin, bins)
- {
- if (check_bin(dir + "\\" + bin))
- {
- return dir + "\\" + bin;
- }
- }
- }
- return QString();
+ QStringList bins;
+ bins << "gpg.exe" << "gpg2.exe";
+
+ HKEY root;
+ root = HKEY_CURRENT_USER;
+
+ const char *path = "Software\\GNU\\GnuPG";
+ const char *path2 = "Software\\Wow6432Node\\GNU\\GnuPG";
+
+ QString dir;
+ // check list of possible places in registry
+ get_reg_key(HKEY_CURRENT_USER, path, dir) ||
+ get_reg_key(HKEY_CURRENT_USER, path2, dir) ||
+ get_reg_key(HKEY_LOCAL_MACHINE, path, dir) ||
+ get_reg_key(HKEY_LOCAL_MACHINE, path2, dir);
+
+ if (!dir.isEmpty()) {
+ foreach (const QString &bin, bins) {
+ if (check_bin(dir + "\\" + bin)) {
+ return dir + "\\" + bin;
+ }
+ }
+ }
+ return QString();
}
#endif
QString find_bin()
{
- // gpg and gpg2 has identical semantics
- // so any from them can be used
- QStringList bins;
+ // gpg and gpg2 has identical semantics
+ // so any from them can be used
+ QStringList bins;
#ifdef Q_OS_WIN
- bins << "gpg.exe" << "gpg2.exe";
+ bins << "gpg.exe" << "gpg2.exe";
#else
- bins << "gpg" << "gpg2";
+ bins << "gpg" << "gpg2";
#endif
- // Prefer bundled gpg
- foreach (const QString &bin, bins)
- {
- if (check_bin(QCoreApplication::applicationDirPath() + "/" + bin))
- {
- return QCoreApplication::applicationDirPath() + "/" + bin;
- }
- }
+ // Prefer bundled gpg
+ foreach (const QString &bin, bins) {
+ if (check_bin(QCoreApplication::applicationDirPath() + "/" + bin)) {
+ return QCoreApplication::applicationDirPath() + "/" + bin;
+ }
+ }
#ifdef Q_OS_WIN
- // On Windows look up at registry
- QString bin = find_reg_gpgProgram();
- if (!bin.isEmpty())
- return bin;
+ // On Windows look up at registry
+ QString bin = find_reg_gpgProgram();
+ if (!bin.isEmpty()) {
+ return bin;
+ }
#endif
- // Look up at PATH environment
+ // Look up at PATH environment
#ifdef Q_OS_WIN
- QString pathSep = ";";
+ QString pathSep = ";";
#else
- QString pathSep = ":";
+ QString pathSep = ":";
#endif
- QStringList paths = QString::fromLocal8Bit(qgetenv("PATH")).split(pathSep, QString::SkipEmptyParts);
+ QStringList paths = QString::fromLocal8Bit(qgetenv("PATH")).split(pathSep, QString::SkipEmptyParts);
#ifdef Q_OS_MAC
- // On Mac OS bundled always uses system default PATH
- // so it need explicity add extra paths which can
- // contain gpg
- // Mac GPG and brew use /usr/local/bin
- // MacPorts uses /opt/local/bin
- paths << "/usr/local/bin" << "/opt/local/bin";
+ // On Mac OS bundled always uses system default PATH
+ // so it need explicity add extra paths which can
+ // contain gpg
+ // Mac GPG and brew use /usr/local/bin
+ // MacPorts uses /opt/local/bin
+ paths << "/usr/local/bin" << "/opt/local/bin";
#endif
- paths.removeDuplicates();
-
- foreach (const QString &path, paths)
- {
- foreach (const QString &bin, bins)
- {
- if (check_bin(path + "/" + bin))
- {
- return path + "/" + bin;
- }
- }
- }
-
- // Return nothing if gpg not found
- return QString();
+ paths.removeDuplicates();
+
+ foreach (const QString &path, paths) {
+ foreach (const QString &bin, bins) {
+ if (check_bin(path + "/" + bin)) {
+ return path + "/" + bin;
+ }
+ }
+ }
+
+ // Return nothing if gpg not found
+ return QString();
}
QString escape_string(const QString &in)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- out += "\\\\";
- else if(in[n] == ':')
- out += "\\c";
- else
- out += in[n];
- }
- return out;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ out += "\\\\";
+ } else if (in[n] == ':') {
+ out += "\\c";
+ } else {
+ out += in[n];
+ }
+ }
+ return out;
}
QString unescape_string(const QString &in)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- {
- if(n + 1 < in.length())
- {
- if(in[n + 1] == '\\')
- out += '\\';
- else if(in[n + 1] == 'c')
- out += ':';
- ++n;
- }
- }
- else
- out += in[n];
- }
- return out;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ if (n + 1 < in.length()) {
+ if (in[n + 1] == '\\') {
+ out += '\\';
+ } else if (in[n + 1] == 'c') {
+ out += ':';
+ }
+ ++n;
+ }
+ } else {
+ out += in[n];
+ }
+ }
+ return out;
}
PGPKey publicKeyFromId(const QString &id)
{
- MyKeyStoreList *ksl = MyKeyStoreList::instance();
- if(!ksl)
- return PGPKey();
+ MyKeyStoreList *ksl = MyKeyStoreList::instance();
+ if (!ksl) {
+ return PGPKey();
+ }
- return ksl->publicKeyFromId(id);
+ return ksl->publicKeyFromId(id);
}
PGPKey secretKeyFromId(const QString &id)
{
- MyKeyStoreList *ksl = MyKeyStoreList::instance();
- if(!ksl)
- return PGPKey();
+ MyKeyStoreList *ksl = MyKeyStoreList::instance();
+ if (!ksl) {
+ return PGPKey();
+ }
- return ksl->secretKeyFromId(id);
+ return ksl->secretKeyFromId(id);
}
} // end namespace gpgQCAPlugin
diff --git a/plugins/qca-logger/qca-logger.cpp b/plugins/qca-logger/qca-logger.cpp
index 12976717..ecb90e0f 100644
--- a/plugins/qca-logger/qca-logger.cpp
+++ b/plugins/qca-logger/qca-logger.cpp
@@ -1,227 +1,239 @@
/*
* Copyright (C) 2007 Alon Bar-Lev <alon.barlev@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <qcaprovider.h>
#include <QtPlugin>
#include <QTextStream>
#include <QFile>
#include <stdlib.h>
using namespace QCA;
-namespace loggerQCAPlugin {
+namespace loggerQCAPlugin
+{
class StreamLogger : public QCA::AbstractLogDevice
{
public:
- StreamLogger(QTextStream &stream) : QCA::AbstractLogDevice( "Stream logger" ), _stream(stream)
- {
- QCA::logger()->registerLogDevice (this);
- }
-
- ~StreamLogger()
- {
- QCA::logger()->unregisterLogDevice (name ());
- }
-
- void logTextMessage( const QString &message, enum QCA::Logger::Severity severity )
- {
- _stream << now () << " " << severityName (severity) << " " << message << endl;
- }
-
- void logBinaryMessage( const QByteArray &blob, enum QCA::Logger::Severity severity )
- {
- Q_UNUSED(blob);
- _stream << now () << " " << severityName (severity) << " " << "Binary blob not implemented yet" << endl;
- }
+ StreamLogger(QTextStream &stream) : QCA::AbstractLogDevice("Stream logger"), _stream(stream)
+ {
+ QCA::logger()->registerLogDevice(this);
+ }
+
+ ~StreamLogger()
+ {
+ QCA::logger()->unregisterLogDevice(name());
+ }
+
+ void logTextMessage(const QString &message, enum QCA::Logger::Severity severity)
+ {
+ _stream << now() << " " << severityName(severity) << " " << message << endl;
+ }
+
+ void logBinaryMessage(const QByteArray &blob, enum QCA::Logger::Severity severity)
+ {
+ Q_UNUSED(blob);
+ _stream << now() << " " << severityName(severity) << " " << "Binary blob not implemented yet" << endl;
+ }
private:
- inline const char *severityName( enum QCA::Logger::Severity severity )
- {
- if (severity <= QCA::Logger::Debug) {
- return s_severityNames[severity];
- }
- else {
- return s_severityNames[QCA::Logger::Debug+1];
- }
- }
-
- inline QString now() {
- static QString format = "yyyy-MM-dd hh:mm:ss";
- return QDateTime::currentDateTime ().toString (format);
- }
+ inline const char *severityName(enum QCA::Logger::Severity severity)
+ {
+ if (severity <= QCA::Logger::Debug) {
+ return s_severityNames[severity];
+ } else {
+ return s_severityNames[QCA::Logger::Debug + 1];
+ }
+ }
+
+ inline QString now()
+ {
+ static QString format = "yyyy-MM-dd hh:mm:ss";
+ return QDateTime::currentDateTime().toString(format);
+ }
private:
- static const char *s_severityNames[];
- QTextStream &_stream;
+ static const char *s_severityNames[];
+ QTextStream &_stream;
};
const char *StreamLogger::s_severityNames[] = {
- "Q",
- "M",
- "A",
- "C",
- "E",
- "W",
- "N",
- "I",
- "D",
- "U"
+ "Q",
+ "M",
+ "A",
+ "C",
+ "E",
+ "W",
+ "N",
+ "I",
+ "D",
+ "U"
};
}
using namespace loggerQCAPlugin;
class loggerProvider : public Provider
{
private:
- QFile _logFile;
- QTextStream _logStream;
- StreamLogger *_streamLogger;
- bool _externalConfig;
+ QFile _logFile;
+ QTextStream _logStream;
+ StreamLogger *_streamLogger;
+ bool _externalConfig;
public:
- loggerProvider () {
- _externalConfig = false;
- _streamLogger = NULL;
-
- QByteArray level = qgetenv ("QCALOGGER_LEVEL");
- QByteArray file = qgetenv ("QCALOGGER_FILE");
-
- if (!level.isEmpty ()) {
- printf ("XXXX %s %s\n", level.data (), file.data ());
- _externalConfig = true;
- createLogger (
- atoi (level),
- file.isEmpty () ? QString() : QString::fromUtf8 (file)
- );
- }
- }
-
- ~loggerProvider () {
- delete _streamLogger;
- _streamLogger = NULL;
- }
+ loggerProvider()
+ {
+ _externalConfig = false;
+ _streamLogger = NULL;
+
+ QByteArray level = qgetenv("QCALOGGER_LEVEL");
+ QByteArray file = qgetenv("QCALOGGER_FILE");
+
+ if (!level.isEmpty()) {
+ printf("XXXX %s %s\n", level.data(), file.data());
+ _externalConfig = true;
+ createLogger(
+ atoi(level),
+ file.isEmpty() ? QString() : QString::fromUtf8(file)
+ );
+ }
+ }
+
+ ~loggerProvider()
+ {
+ delete _streamLogger;
+ _streamLogger = NULL;
+ }
public:
- virtual
- int
- qcaVersion() const {
- return QCA_VERSION;
- }
-
- virtual
- void
- init () {}
-
- virtual
- QString
- name () const {
- return "qca-logger";
- }
-
- virtual
- QStringList
- features () const {
- QStringList list;
- list += "log";
- return list;
- }
-
- virtual
- Context *
- createContext (
- const QString &type
- ) {
- Q_UNUSED(type);
- return NULL;
- }
-
- virtual
- QVariantMap
- defaultConfig () const {
- QVariantMap mytemplate;
-
- mytemplate["formtype"] = "http://affinix.com/qca/forms/qca-logger#1.0";
- mytemplate["enabled"] = false;
- mytemplate["file"] = "";
- mytemplate["level"] = (int)Logger::Quiet;
-
- return mytemplate;
- }
-
- virtual
- void
- configChanged (const QVariantMap &config) {
- if (!_externalConfig) {
- delete _streamLogger;
- _streamLogger = NULL;
-
- if (config["enabled"].toBool ()) {
- createLogger (
- config["level"].toInt (),
- config["file"].toString ()
- );
- }
- }
- }
+ virtual
+ int
+ qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ virtual
+ void
+ init() {}
+
+ virtual
+ QString
+ name() const
+ {
+ return "qca-logger";
+ }
+
+ virtual
+ QStringList
+ features() const
+ {
+ QStringList list;
+ list += "log";
+ return list;
+ }
+
+ virtual
+ Context *
+ createContext(
+ const QString &type
+ )
+ {
+ Q_UNUSED(type);
+ return NULL;
+ }
+
+ virtual
+ QVariantMap
+ defaultConfig() const
+ {
+ QVariantMap mytemplate;
+
+ mytemplate["formtype"] = "http://affinix.com/qca/forms/qca-logger#1.0";
+ mytemplate["enabled"] = false;
+ mytemplate["file"] = "";
+ mytemplate["level"] = (int)Logger::Quiet;
+
+ return mytemplate;
+ }
+
+ virtual
+ void
+ configChanged(const QVariantMap &config)
+ {
+ if (!_externalConfig) {
+ delete _streamLogger;
+ _streamLogger = NULL;
+
+ if (config["enabled"].toBool()) {
+ createLogger(
+ config["level"].toInt(),
+ config["file"].toString()
+ );
+ }
+ }
+ }
private:
- void
- createLogger (
- const int level,
- const QString &file
- ) {
- bool success = false;
- if (file.isEmpty ()) {
- success = _logFile.open (stderr, QIODevice::WriteOnly | QIODevice::Text | QIODevice::Unbuffered);
- }
- else {
- _logFile.setFileName (file);
- success = _logFile.open (QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);
- }
-
- if (success) {
- _logStream.setDevice (&_logFile);
- logger ()->setLevel ((Logger::Severity)level);
- _streamLogger = new StreamLogger (_logStream);
- }
- }
+ void
+ createLogger(
+ const int level,
+ const QString &file
+ )
+ {
+ bool success = false;
+ if (file.isEmpty()) {
+ success = _logFile.open(stderr, QIODevice::WriteOnly | QIODevice::Text | QIODevice::Unbuffered);
+ } else {
+ _logFile.setFileName(file);
+ success = _logFile.open(QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);
+ }
+
+ if (success) {
+ _logStream.setDevice(&_logFile);
+ logger()->setLevel((Logger::Severity)level);
+ _streamLogger = new StreamLogger(_logStream);
+ }
+ }
};
class loggerPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { return new loggerProvider; }
+ virtual Provider *createProvider()
+ {
+ return new loggerProvider;
+ }
};
#include "qca-logger.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_logger, loggerPlugin)
#endif
diff --git a/plugins/qca-nss/qca-nss.cpp b/plugins/qca-nss/qca-nss.cpp
index db01eb02..7c4d108b 100644
--- a/plugins/qca-nss/qca-nss.cpp
+++ b/plugins/qca-nss/qca-nss.cpp
@@ -1,551 +1,551 @@
/*
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include "pk11func.h"
#include "nss.h"
#include "hasht.h"
#include <QtCrypto>
#include <QDebug>
#include <QtPlugin>
#include <QStringList>
-
//-----------------------------------------------------------
class nssHashContext : public QCA::HashContext
{
public:
- nssHashContext( QCA::Provider *p, const QString &type) : QCA::HashContext(p, type)
+ nssHashContext(QCA::Provider *p, const QString &type) : QCA::HashContext(p, type)
{
- SECStatus s;
-
- NSS_NoDB_Init(".");
-
- m_status = 0;
-
- /* Get a slot to use for the crypto operations */
- m_slot = PK11_GetInternalKeySlot();
- if (!m_slot)
- {
- qDebug() << "GetInternalKeySlot failed";
- m_status = 1;
- return;
- }
-
- if ( QString("md2") == type ) {
- m_hashAlgo = SEC_OID_MD2;
- }
- else if ( QString("md5") == type ) {
- m_hashAlgo = SEC_OID_MD5;
- }
- else if ( QString("sha1") == type ) {
- m_hashAlgo = SEC_OID_SHA1;
- }
- else if ( QString("sha256") == type ) {
- m_hashAlgo = SEC_OID_SHA256;
- }
- else if ( QString("sha384") == type ) {
- m_hashAlgo = SEC_OID_SHA384;
- }
- else if ( QString("sha512") == type ) {
- m_hashAlgo = SEC_OID_SHA512;
- } else {
- qDebug() << "Unknown provider type: " << type;
- return; /* this will probably cause a segfault... */
- }
-
- m_context = PK11_CreateDigestContext(m_hashAlgo);
- if (! m_context) {
- qDebug() << "CreateDigestContext failed";
- return;
- }
-
- s = PK11_DigestBegin(m_context);
- if (s != SECSuccess) {
- qDebug() << "DigestBegin failed";
- return;
- }
+ SECStatus s;
+
+ NSS_NoDB_Init(".");
+
+ m_status = 0;
+
+ /* Get a slot to use for the crypto operations */
+ m_slot = PK11_GetInternalKeySlot();
+ if (!m_slot) {
+ qDebug() << "GetInternalKeySlot failed";
+ m_status = 1;
+ return;
+ }
+
+ if (QString("md2") == type) {
+ m_hashAlgo = SEC_OID_MD2;
+ } else if (QString("md5") == type) {
+ m_hashAlgo = SEC_OID_MD5;
+ } else if (QString("sha1") == type) {
+ m_hashAlgo = SEC_OID_SHA1;
+ } else if (QString("sha256") == type) {
+ m_hashAlgo = SEC_OID_SHA256;
+ } else if (QString("sha384") == type) {
+ m_hashAlgo = SEC_OID_SHA384;
+ } else if (QString("sha512") == type) {
+ m_hashAlgo = SEC_OID_SHA512;
+ } else {
+ qDebug() << "Unknown provider type: " << type;
+ return; /* this will probably cause a segfault... */
+ }
+
+ m_context = PK11_CreateDigestContext(m_hashAlgo);
+ if (! m_context) {
+ qDebug() << "CreateDigestContext failed";
+ return;
+ }
+
+ s = PK11_DigestBegin(m_context);
+ if (s != SECSuccess) {
+ qDebug() << "DigestBegin failed";
+ return;
+ }
}
~nssHashContext()
{
- PK11_DestroyContext(m_context, PR_TRUE);
- if (m_slot)
- PK11_FreeSlot(m_slot);
+ PK11_DestroyContext(m_context, PR_TRUE);
+ if (m_slot) {
+ PK11_FreeSlot(m_slot);
+ }
}
Context *clone() const
{
- return new nssHashContext(*this);
+ return new nssHashContext(*this);
}
void clear()
{
- SECStatus s;
+ SECStatus s;
- PK11_DestroyContext(m_context, PR_TRUE);
+ PK11_DestroyContext(m_context, PR_TRUE);
- m_context = PK11_CreateDigestContext(m_hashAlgo);
- if (! m_context) {
- qDebug() << "CreateDigestContext failed";
- return;
- }
+ m_context = PK11_CreateDigestContext(m_hashAlgo);
+ if (! m_context) {
+ qDebug() << "CreateDigestContext failed";
+ return;
+ }
- s = PK11_DigestBegin(m_context);
- if (s != SECSuccess) {
- qDebug() << "DigestBegin failed";
- return;
- }
+ s = PK11_DigestBegin(m_context);
+ if (s != SECSuccess) {
+ qDebug() << "DigestBegin failed";
+ return;
+ }
}
void update(const QCA::MemoryRegion &a)
{
- PK11_DigestOp(m_context, (const unsigned char*)a.data(), a.size());
+ PK11_DigestOp(m_context, (const unsigned char *)a.data(), a.size());
}
QCA::MemoryRegion final()
{
- unsigned int len = 0;
- QCA::SecureArray a( 64 );
- PK11_DigestFinal(m_context, (unsigned char*)a.data(), &len, a.size());
- a.resize(len);
- return a;
+ unsigned int len = 0;
+ QCA::SecureArray a(64);
+ PK11_DigestFinal(m_context, (unsigned char *)a.data(), &len, a.size());
+ a.resize(len);
+ return a;
}
private:
PK11SlotInfo *m_slot;
int m_status;
PK11Context *m_context;
SECOidTag m_hashAlgo;
};
-
//-----------------------------------------------------------
class nssHmacContext : public QCA::MACContext
{
public:
- nssHmacContext( QCA::Provider *p, const QString &type) : QCA::MACContext(p, type)
+ nssHmacContext(QCA::Provider *p, const QString &type) : QCA::MACContext(p, type)
{
- NSS_NoDB_Init(".");
-
- m_status = 0;
-
- /* Get a slot to use for the crypto operations */
- m_slot = PK11_GetInternalKeySlot();
- if (!m_slot)
- {
- qDebug() << "GetInternalKeySlot failed";
- m_status = 1;
- return;
- }
-
- if ( QString("hmac(md5)") == type ) {
- m_macAlgo = CKM_MD5_HMAC;
- }
- else if ( QString("hmac(sha1)") == type ) {
- m_macAlgo = CKM_SHA_1_HMAC;
- }
- else if ( QString("hmac(sha256)") == type ) {
- m_macAlgo = CKM_SHA256_HMAC;
- }
- else if ( QString("hmac(sha384)") == type ) {
- m_macAlgo = CKM_SHA384_HMAC;
- }
- else if ( QString("hmac(sha512)") == type ) {
- m_macAlgo = CKM_SHA512_HMAC;
- }
- else if ( QString("hmac(ripemd160)") == type ) {
- m_macAlgo = CKM_RIPEMD160_HMAC;
- }
- else {
- qDebug() << "Unknown provider type: " << type;
- return; /* this will probably cause a segfault... */
- }
+ NSS_NoDB_Init(".");
+
+ m_status = 0;
+
+ /* Get a slot to use for the crypto operations */
+ m_slot = PK11_GetInternalKeySlot();
+ if (!m_slot) {
+ qDebug() << "GetInternalKeySlot failed";
+ m_status = 1;
+ return;
+ }
+
+ if (QString("hmac(md5)") == type) {
+ m_macAlgo = CKM_MD5_HMAC;
+ } else if (QString("hmac(sha1)") == type) {
+ m_macAlgo = CKM_SHA_1_HMAC;
+ } else if (QString("hmac(sha256)") == type) {
+ m_macAlgo = CKM_SHA256_HMAC;
+ } else if (QString("hmac(sha384)") == type) {
+ m_macAlgo = CKM_SHA384_HMAC;
+ } else if (QString("hmac(sha512)") == type) {
+ m_macAlgo = CKM_SHA512_HMAC;
+ } else if (QString("hmac(ripemd160)") == type) {
+ m_macAlgo = CKM_RIPEMD160_HMAC;
+ } else {
+ qDebug() << "Unknown provider type: " << type;
+ return; /* this will probably cause a segfault... */
+ }
}
~nssHmacContext()
{
- PK11_DestroyContext(m_context, PR_TRUE);
- if (m_slot)
- PK11_FreeSlot(m_slot);
+ PK11_DestroyContext(m_context, PR_TRUE);
+ if (m_slot) {
+ PK11_FreeSlot(m_slot);
+ }
}
Context *clone() const
{
- return new nssHmacContext(*this);
+ return new nssHmacContext(*this);
}
void clear()
{
- PK11_DestroyContext(m_context, PR_TRUE);
-
- SECItem noParams;
- noParams.data = 0;
- noParams.len = 0;
-
- m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
- if (! m_context) {
- qDebug() << "CreateContextBySymKey failed";
- return;
- }
-
- SECStatus s = PK11_DigestBegin(m_context);
- if (s != SECSuccess) {
- qDebug() << "DigestBegin failed";
- return;
- }
+ PK11_DestroyContext(m_context, PR_TRUE);
+
+ SECItem noParams;
+ noParams.data = 0;
+ noParams.len = 0;
+
+ m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
+ if (! m_context) {
+ qDebug() << "CreateContextBySymKey failed";
+ return;
+ }
+
+ SECStatus s = PK11_DigestBegin(m_context);
+ if (s != SECSuccess) {
+ qDebug() << "DigestBegin failed";
+ return;
+ }
}
QCA::KeyLength keyLength() const
{
return anyKeyLength();
}
void setup(const QCA::SymmetricKey &key)
{
/* turn the raw key into a SECItem */
SECItem keyItem;
- keyItem.data = (unsigned char*) key.data();
- keyItem.len = key.size();
-
- m_nssKey = PK11_ImportSymKey(m_slot, m_macAlgo, PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL);
-
- SECItem noParams;
- noParams.data = 0;
- noParams.len = 0;
-
- m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
- if (! m_context) {
- qDebug() << "CreateContextBySymKey failed";
- return;
- }
-
- SECStatus s = PK11_DigestBegin(m_context);
- if (s != SECSuccess) {
- qDebug() << "DigestBegin failed";
- return;
- }
+ keyItem.data = (unsigned char *) key.data();
+ keyItem.len = key.size();
+
+ m_nssKey = PK11_ImportSymKey(m_slot, m_macAlgo, PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL);
+
+ SECItem noParams;
+ noParams.data = 0;
+ noParams.len = 0;
+
+ m_context = PK11_CreateContextBySymKey(m_macAlgo, CKA_SIGN, m_nssKey, &noParams);
+ if (! m_context) {
+ qDebug() << "CreateContextBySymKey failed";
+ return;
+ }
+
+ SECStatus s = PK11_DigestBegin(m_context);
+ if (s != SECSuccess) {
+ qDebug() << "DigestBegin failed";
+ return;
+ }
}
void update(const QCA::MemoryRegion &a)
{
- PK11_DigestOp(m_context, (const unsigned char*)a.data(), a.size());
+ PK11_DigestOp(m_context, (const unsigned char *)a.data(), a.size());
}
- void final( QCA::MemoryRegion *out)
+ void final(QCA::MemoryRegion *out)
{
- // NSS doesn't appear to be able to tell us how big the digest will
- // be for a given algorithm until after we finalise it, so we work
- // around the problem a bit.
- QCA::SecureArray sa( HASH_LENGTH_MAX, 0 ); // assume the biggest hash size we know
- unsigned int len = 0;
- PK11_DigestFinal(m_context, (unsigned char*)sa.data(), &len, sa.size());
- sa.resize(len); // and fix it up later
- *out = sa;
+ // NSS doesn't appear to be able to tell us how big the digest will
+ // be for a given algorithm until after we finalise it, so we work
+ // around the problem a bit.
+ QCA::SecureArray sa(HASH_LENGTH_MAX, 0); // assume the biggest hash size we know
+ unsigned int len = 0;
+ PK11_DigestFinal(m_context, (unsigned char *)sa.data(), &len, sa.size());
+ sa.resize(len); // and fix it up later
+ *out = sa;
}
private:
PK11SlotInfo *m_slot;
int m_status;
PK11Context *m_context;
CK_MECHANISM_TYPE m_macAlgo;
- PK11SymKey* m_nssKey;
+ PK11SymKey *m_nssKey;
};
//-----------------------------------------------------------
class nssCipherContext : public QCA::CipherContext
{
public:
- nssCipherContext( QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type)
+ nssCipherContext(QCA::Provider *p, const QString &type) : QCA::CipherContext(p, type)
{
- NSS_NoDB_Init(".");
-
- if ( QString("aes128-ecb") == type ) {
- m_cipherMechanism = CKM_AES_ECB;
- }
- else if ( QString("aes128-cbc") == type ) {
- m_cipherMechanism = CKM_AES_CBC;
- }
- else if ( QString("des-ecb") == type ) {
- m_cipherMechanism = CKM_DES_ECB;
- }
- else if ( QString("des-cbc") == type ) {
- m_cipherMechanism = CKM_DES_CBC;
- }
- else if ( QString("des-cbc-pkcs7") == type ) {
- m_cipherMechanism = CKM_DES_CBC_PAD;
- }
- else if ( QString("tripledes-ecb") == type ) {
- m_cipherMechanism = CKM_DES3_ECB;
- }
- else {
- qDebug() << "Unknown provider type: " << type;
- return; /* this will probably cause a segfault... */
- }
+ NSS_NoDB_Init(".");
+
+ if (QString("aes128-ecb") == type) {
+ m_cipherMechanism = CKM_AES_ECB;
+ } else if (QString("aes128-cbc") == type) {
+ m_cipherMechanism = CKM_AES_CBC;
+ } else if (QString("des-ecb") == type) {
+ m_cipherMechanism = CKM_DES_ECB;
+ } else if (QString("des-cbc") == type) {
+ m_cipherMechanism = CKM_DES_CBC;
+ } else if (QString("des-cbc-pkcs7") == type) {
+ m_cipherMechanism = CKM_DES_CBC_PAD;
+ } else if (QString("tripledes-ecb") == type) {
+ m_cipherMechanism = CKM_DES3_ECB;
+ } else {
+ qDebug() << "Unknown provider type: " << type;
+ return; /* this will probably cause a segfault... */
+ }
}
~nssCipherContext()
- {
- }
+ {
+ }
void setup(QCA::Direction dir,
const QCA::SymmetricKey &key,
const QCA::InitializationVector &iv,
const QCA::AuthTag &tag)
{
- Q_UNUSED(tag);
- /* Get a slot to use for the crypto operations */
- m_slot = PK11_GetBestSlot( m_cipherMechanism, NULL );
- if (!m_slot)
- {
- qDebug() << "GetBestSlot failed";
- return;
- }
-
- /* turn the raw key into a SECItem */
+ Q_UNUSED(tag);
+ /* Get a slot to use for the crypto operations */
+ m_slot = PK11_GetBestSlot(m_cipherMechanism, NULL);
+ if (!m_slot) {
+ qDebug() << "GetBestSlot failed";
+ return;
+ }
+
+ /* turn the raw key into a SECItem */
SECItem keyItem;
- keyItem.data = (unsigned char*) key.data();
- keyItem.len = key.size();
-
- if (QCA::Encode == dir) {
- m_nssKey = PK11_ImportSymKey(m_slot, m_cipherMechanism,
- PK11_OriginUnwrap, CKA_ENCRYPT,
- &keyItem, NULL);
- } else {
- // decryption
- m_nssKey = PK11_ImportSymKey(m_slot, m_cipherMechanism,
- PK11_OriginUnwrap, CKA_DECRYPT,
- &keyItem, NULL);
- }
-
- SECItem ivItem;
- ivItem.data = (unsigned char*) iv.data();
- ivItem.len = iv.size();
-
- m_params = PK11_ParamFromIV(m_cipherMechanism, &ivItem);
-
- if (QCA::Encode == dir) {
- m_context = PK11_CreateContextBySymKey(m_cipherMechanism,
- CKA_ENCRYPT, m_nssKey,
- m_params);
- } else {
- // decryption
- m_context = PK11_CreateContextBySymKey(m_cipherMechanism,
- CKA_DECRYPT, m_nssKey,
- m_params);
- }
-
- if (! m_context) {
- qDebug() << "CreateContextBySymKey failed";
- return;
- }
+ keyItem.data = (unsigned char *) key.data();
+ keyItem.len = key.size();
+
+ if (QCA::Encode == dir) {
+ m_nssKey = PK11_ImportSymKey(m_slot, m_cipherMechanism,
+ PK11_OriginUnwrap, CKA_ENCRYPT,
+ &keyItem, NULL);
+ } else {
+ // decryption
+ m_nssKey = PK11_ImportSymKey(m_slot, m_cipherMechanism,
+ PK11_OriginUnwrap, CKA_DECRYPT,
+ &keyItem, NULL);
+ }
+
+ SECItem ivItem;
+ ivItem.data = (unsigned char *) iv.data();
+ ivItem.len = iv.size();
+
+ m_params = PK11_ParamFromIV(m_cipherMechanism, &ivItem);
+
+ if (QCA::Encode == dir) {
+ m_context = PK11_CreateContextBySymKey(m_cipherMechanism,
+ CKA_ENCRYPT, m_nssKey,
+ m_params);
+ } else {
+ // decryption
+ m_context = PK11_CreateContextBySymKey(m_cipherMechanism,
+ CKA_DECRYPT, m_nssKey,
+ m_params);
+ }
+
+ if (! m_context) {
+ qDebug() << "CreateContextBySymKey failed";
+ return;
+ }
}
QCA::Provider::Context *clone() const
- {
- return new nssCipherContext(*this);
- }
+ {
+ return new nssCipherContext(*this);
+ }
int blockSize() const
- {
- return PK11_GetBlockSize( m_cipherMechanism, m_params);
- }
+ {
+ return PK11_GetBlockSize(m_cipherMechanism, m_params);
+ }
QCA::AuthTag tag() const
{
- // For future implementation
- return QCA::AuthTag();
+ // For future implementation
+ return QCA::AuthTag();
}
- bool update( const QCA::SecureArray &in, QCA::SecureArray *out )
- {
- out->resize(in.size()+blockSize());
- int resultLength;
+ bool update(const QCA::SecureArray &in, QCA::SecureArray *out)
+ {
+ out->resize(in.size() + blockSize());
+ int resultLength;
- PK11_CipherOp(m_context, (unsigned char*)out->data(),
- &resultLength, out->size(),
- (unsigned char*)in.data(), in.size());
- out->resize(resultLength);
+ PK11_CipherOp(m_context, (unsigned char *)out->data(),
+ &resultLength, out->size(),
+ (unsigned char *)in.data(), in.size());
+ out->resize(resultLength);
- return true;
- }
+ return true;
+ }
- bool final( QCA::SecureArray *out )
- {
- out->resize(blockSize());
- unsigned int resultLength;
+ bool final(QCA::SecureArray *out)
+ {
+ out->resize(blockSize());
+ unsigned int resultLength;
- PK11_DigestFinal(m_context, (unsigned char*)out->data(),
- &resultLength, out->size());
- out->resize(resultLength);
+ PK11_DigestFinal(m_context, (unsigned char *)out->data(),
+ &resultLength, out->size());
+ out->resize(resultLength);
- return true;
- }
+ return true;
+ }
QCA::KeyLength keyLength() const
- {
- int min = 0;
- int max = 0;
- int multiple = 0;
-
- switch (m_cipherMechanism) {
- case CKM_AES_ECB:
- case CKM_AES_CBC:
- min = max = 16;
- multiple = 1;
- break;
-
- case CKM_DES_ECB:
- case CKM_DES_CBC:
- case CKM_DES_CBC_PAD:
- min = max = 8;
- multiple = 1;
- break;
-
- case CKM_DES3_ECB:
- min = 16;
- max = 24;
- multiple = 1;
- break;
- }
-
- return QCA::KeyLength(min, max, multiple);
- }
+ {
+ int min = 0;
+ int max = 0;
+ int multiple = 0;
+
+ switch (m_cipherMechanism) {
+ case CKM_AES_ECB:
+ case CKM_AES_CBC:
+ min = max = 16;
+ multiple = 1;
+ break;
+
+ case CKM_DES_ECB:
+ case CKM_DES_CBC:
+ case CKM_DES_CBC_PAD:
+ min = max = 8;
+ multiple = 1;
+ break;
+
+ case CKM_DES3_ECB:
+ min = 16;
+ max = 24;
+ multiple = 1;
+ break;
+ }
+
+ return QCA::KeyLength(min, max, multiple);
+ }
private:
- PK11SymKey* m_nssKey;
+ PK11SymKey *m_nssKey;
CK_MECHANISM_TYPE m_cipherMechanism;
PK11SlotInfo *m_slot;
PK11Context *m_context;
- SECItem* m_params;
+ SECItem *m_params;
};
-
//==========================================================
class nssProvider : public QCA::Provider
{
public:
void init()
{
}
~nssProvider()
{
}
int qcaVersion() const
{
- return QCA_VERSION;
+ return QCA_VERSION;
}
QString name() const
{
- return "qca-nss";
+ return "qca-nss";
}
QStringList features() const
{
- QStringList list;
-
- list += "md2";
- list += "md5";
- list += "sha1";
- list += "sha256";
- list += "sha384";
- list += "sha512";
-
- list += "hmac(md5)";
- list += "hmac(sha1)";
- list += "hmac(sha256)";
- list += "hmac(sha384)";
- list += "hmac(sha512)";
- // appears to not be implemented in NSS yet
- // list += "hmac(ripemd160)";
-
- list += "aes128-ecb";
- list += "aes128-cbc";
- list += "des-ecb";
- list += "des-cbc";
- list += "des-cbc-pkcs7";
- list += "tripledes-ecb";
-
- return list;
+ QStringList list;
+
+ list += "md2";
+ list += "md5";
+ list += "sha1";
+ list += "sha256";
+ list += "sha384";
+ list += "sha512";
+
+ list += "hmac(md5)";
+ list += "hmac(sha1)";
+ list += "hmac(sha256)";
+ list += "hmac(sha384)";
+ list += "hmac(sha512)";
+ // appears to not be implemented in NSS yet
+ // list += "hmac(ripemd160)";
+
+ list += "aes128-ecb";
+ list += "aes128-cbc";
+ list += "des-ecb";
+ list += "des-cbc";
+ list += "des-cbc-pkcs7";
+ list += "tripledes-ecb";
+
+ return list;
}
Context *createContext(const QString &type)
{
- if ( type == "md2" )
- return new nssHashContext( this, type );
- if ( type == "md5" )
- return new nssHashContext( this, type );
- if ( type == "sha1" )
- return new nssHashContext( this, type );
- if ( type == "sha256" )
- return new nssHashContext( this, type );
- if ( type == "sha384" )
- return new nssHashContext( this, type );
- if ( type == "sha512" )
- return new nssHashContext( this, type );
-
- if ( type == "hmac(md5)" )
- return new nssHmacContext( this, type );
- if ( type == "hmac(sha1)" )
- return new nssHmacContext( this, type );
- if ( type == "hmac(sha256)" )
- return new nssHmacContext( this, type );
- if ( type == "hmac(sha384)" )
- return new nssHmacContext( this, type );
- if ( type == "hmac(sha512)" )
- return new nssHmacContext( this, type );
- if ( type == "hmac(ripemd160)" )
- return new nssHmacContext( this, type );
-
- if ( type == "aes128-ecb" )
- return new nssCipherContext( this, type);
- if ( type == "aes128-cbc" )
- return new nssCipherContext( this, type);
- if ( type == "des-ecb" )
- return new nssCipherContext( this, type);
- if ( type == "des-cbc" )
- return new nssCipherContext( this, type);
- if ( type == "des-cbc-pkcs7" )
- return new nssCipherContext( this, type);
- if ( type == "tripledes-ecb" )
- return new nssCipherContext( this, type);
- else
- return 0;
+ if (type == "md2") {
+ return new nssHashContext(this, type);
+ }
+ if (type == "md5") {
+ return new nssHashContext(this, type);
+ }
+ if (type == "sha1") {
+ return new nssHashContext(this, type);
+ }
+ if (type == "sha256") {
+ return new nssHashContext(this, type);
+ }
+ if (type == "sha384") {
+ return new nssHashContext(this, type);
+ }
+ if (type == "sha512") {
+ return new nssHashContext(this, type);
+ }
+
+ if (type == "hmac(md5)") {
+ return new nssHmacContext(this, type);
+ }
+ if (type == "hmac(sha1)") {
+ return new nssHmacContext(this, type);
+ }
+ if (type == "hmac(sha256)") {
+ return new nssHmacContext(this, type);
+ }
+ if (type == "hmac(sha384)") {
+ return new nssHmacContext(this, type);
+ }
+ if (type == "hmac(sha512)") {
+ return new nssHmacContext(this, type);
+ }
+ if (type == "hmac(ripemd160)") {
+ return new nssHmacContext(this, type);
+ }
+
+ if (type == "aes128-ecb") {
+ return new nssCipherContext(this, type);
+ }
+ if (type == "aes128-cbc") {
+ return new nssCipherContext(this, type);
+ }
+ if (type == "des-ecb") {
+ return new nssCipherContext(this, type);
+ }
+ if (type == "des-cbc") {
+ return new nssCipherContext(this, type);
+ }
+ if (type == "des-cbc-pkcs7") {
+ return new nssCipherContext(this, type);
+ }
+ if (type == "tripledes-ecb") {
+ return new nssCipherContext(this, type);
+ } else {
+ return 0;
+ }
}
};
class nssPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES( QCAPlugin )
+ Q_INTERFACES(QCAPlugin)
public:
- virtual QCA::Provider *createProvider() { return new nssProvider; }
+ virtual QCA::Provider *createProvider()
+ {
+ return new nssProvider;
+ }
};
#include "qca-nss.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_nss, nssPlugin)
#endif
diff --git a/plugins/qca-ossl/ossl110-compat.h b/plugins/qca-ossl/ossl110-compat.h
index b320707e..cfe396db 100644
--- a/plugins/qca-ossl/ossl110-compat.h
+++ b/plugins/qca-ossl/ossl110-compat.h
@@ -1,275 +1,322 @@
/*
* Copyright (C) 2017 Gabriel Souza Franco <gabrielfrancosouza@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#ifndef OSSL110COMPAT_H
#define OSSL110COMPAT_H
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/rsa.h>
#include <openssl/dsa.h>
#if OPENSSL_VERSION_NUMBER < 0x10100000L
#define RSA_F_RSA_METH_DUP 161
static void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps)
{
- if (pr)
+ if (pr) {
*pr = sig->r;
- if (ps)
+ }
+ if (ps) {
*ps = sig->s;
+ }
}
static int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s)
{
- if (!sig) return 0;
+ if (!sig) {
+ return 0;
+ }
sig->r = r;
sig->s = s;
return 1;
}
static void DSA_get0_pqg(const DSA *dsa, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g)
{
- if (p)
+ if (p) {
*p = dsa->p;
- if (q)
+ }
+ if (q) {
*q = dsa->q;
- if (g)
+ }
+ if (g) {
*g = dsa->g;
+ }
}
static int DSA_set0_pqg(DSA *dsa, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{
- if (!dsa) return 0;
+ if (!dsa) {
+ return 0;
+ }
dsa->p = p;
dsa->q = q;
dsa->g = g;
return 1;
}
static void RSA_get0_key(const RSA *rsa, const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
{
- if (n)
+ if (n) {
*n = rsa->n;
- if (e)
+ }
+ if (e) {
*e = rsa->e;
- if (d)
+ }
+ if (d) {
*d = rsa->d;
+ }
}
static int RSA_set0_key(RSA *rsa, BIGNUM *n, BIGNUM *e, BIGNUM *d)
{
- if (!rsa) return 0;
+ if (!rsa) {
+ return 0;
+ }
rsa->n = n;
rsa->e = e;
rsa->d = d;
return 1;
}
static void RSA_get0_factors(const RSA *rsa, const BIGNUM **p, const BIGNUM **q)
{
- if (p)
+ if (p) {
*p = rsa->p;
- if (q)
+ }
+ if (q) {
*q = rsa->q;
+ }
}
static int RSA_set0_factors(RSA *rsa, BIGNUM *p, BIGNUM *q)
{
- if (!rsa) return 0;
+ if (!rsa) {
+ return 0;
+ }
rsa->p = p;
rsa->q = q;
return 1;
}
static void DH_get0_pqg(const DH *dh, const BIGNUM **p, const BIGNUM **q, const BIGNUM **g)
{
- if (p)
+ if (p) {
*p = dh->p;
- if (q)
+ }
+ if (q) {
*q = dh->q;
- if (g)
+ }
+ if (g) {
*g = dh->g;
+ }
}
static int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g)
{
- if (!dh) return 0;
+ if (!dh) {
+ return 0;
+ }
dh->p = p;
dh->q = q;
dh->g = g;
return 1;
}
static void DH_get0_key(const DH *dh, const BIGNUM **pub_key, const BIGNUM **priv_key)
{
- if (pub_key)
+ if (pub_key) {
*pub_key = dh->pub_key;
- if (priv_key)
+ }
+ if (priv_key) {
*priv_key = dh->priv_key;
+ }
}
static int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key)
{
- if (!dh) return 0;
+ if (!dh) {
+ return 0;
+ }
dh->pub_key = pub_key;
dh->priv_key = priv_key;
return 1;
}
static void DSA_get0_key(const DSA *dsa, const BIGNUM **pub_key, const BIGNUM **priv_key)
{
- if (pub_key)
+ if (pub_key) {
*pub_key = dsa->pub_key;
- if (priv_key)
+ }
+ if (priv_key) {
*priv_key = dsa->priv_key;
+ }
}
static int DSA_set0_key(DSA *dsa, BIGNUM *pub_key, BIGNUM *priv_key)
{
- if (!dsa) return 0;
+ if (!dsa) {
+ return 0;
+ }
dsa->pub_key = pub_key;
dsa->priv_key = priv_key;
return 1;
}
static void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig, const X509_ALGOR **palg)
{
- if (psig)
+ if (psig) {
*psig = req->signature;
- if (palg)
+ }
+ if (palg) {
*palg = req->sig_alg;
+ }
}
static void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig, const X509_ALGOR **palg)
{
- if (psig)
+ if (psig) {
*psig = crl->signature;
- if (palg)
+ }
+ if (palg) {
*palg = crl->sig_alg;
+ }
}
static RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth)
{
- if (!meth)
+ if (!meth) {
return NULL;
+ }
RSA_METHOD *_meth = (RSA_METHOD *) OPENSSL_malloc(sizeof(*_meth));
- if (!_meth)
- {
+ if (!_meth) {
RSAerr(RSA_F_RSA_METH_DUP, ERR_R_MALLOC_FAILURE);
return NULL;
}
memcpy(_meth, meth, sizeof(*_meth));
_meth->name = strdup(meth->name);
if (!_meth->name) {
OPENSSL_free(_meth);
RSAerr(RSA_F_RSA_METH_DUP, ERR_R_MALLOC_FAILURE);
return NULL;
}
return _meth;
}
-static int RSA_meth_set_priv_enc(RSA_METHOD *rsa, int (*priv_enc) (int flen, const unsigned char *from,
- unsigned char *to, RSA *rsa, int padding))
+static int RSA_meth_set_priv_enc(RSA_METHOD *rsa, int (*priv_enc)(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding))
{
- if (!rsa) return 0;
+ if (!rsa) {
+ return 0;
+ }
rsa->rsa_priv_enc = priv_enc;
return 1;
}
-static int RSA_meth_set_priv_dec(RSA_METHOD *rsa, int (*priv_dec) (int flen, const unsigned char *from,
- unsigned char *to, RSA *rsa, int padding))
+static int RSA_meth_set_priv_dec(RSA_METHOD *rsa, int (*priv_dec)(int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa, int padding))
{
- if (!rsa) return 0;
+ if (!rsa) {
+ return 0;
+ }
rsa->rsa_priv_dec = priv_dec;
return 1;
}
-static int RSA_meth_set_sign(RSA_METHOD *meth, int (*sign) (int type, const unsigned char *m,
- unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa))
+static int RSA_meth_set_sign(RSA_METHOD *meth, int (*sign)(int type, const unsigned char *m,
+ unsigned int m_length, unsigned char *sigret, unsigned int *siglen, const RSA *rsa))
{
- if (!meth) return 0;
+ if (!meth) {
+ return 0;
+ }
meth->rsa_sign = sign;
return 1;
}
-static int RSA_meth_set_verify(RSA_METHOD *meth, int (*verify) (int dtype, const unsigned char *m,
- unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa))
+static int RSA_meth_set_verify(RSA_METHOD *meth, int (*verify)(int dtype, const unsigned char *m,
+ unsigned int m_length, const unsigned char *sigbuf, unsigned int siglen, const RSA *rsa))
{
- if (!meth) return 0;
+ if (!meth) {
+ return 0;
+ }
meth->rsa_verify = verify;
return 1;
}
-static int RSA_meth_set_finish(RSA_METHOD *meth, int (*finish) (RSA *rsa))
+static int RSA_meth_set_finish(RSA_METHOD *meth, int (*finish)(RSA *rsa))
{
- if (!meth) return 0;
+ if (!meth) {
+ return 0;
+ }
meth->finish = finish;
return 1;
}
static HMAC_CTX *HMAC_CTX_new()
{
HMAC_CTX *ctx = (HMAC_CTX *) OPENSSL_malloc(sizeof(HMAC_CTX));
- if (ctx)
+ if (ctx) {
HMAC_CTX_init(ctx);
+ }
return ctx;
}
static void HMAC_CTX_free(HMAC_CTX *ctx)
{
- if (!ctx)
+ if (!ctx) {
return;
+ }
HMAC_CTX_cleanup(ctx);
EVP_MD_CTX_cleanup(&ctx->i_ctx);
EVP_MD_CTX_cleanup(&ctx->o_ctx);
EVP_MD_CTX_cleanup(&ctx->md_ctx);
OPENSSL_free(ctx);
}
#define ASN1_STRING_get0_data(...) (const unsigned char*)ASN1_STRING_data(__VA_ARGS__)
#define EVP_MD_CTX_new(...) EVP_MD_CTX_create(__VA_ARGS__)
#define EVP_MD_CTX_free(...) EVP_MD_CTX_destroy(__VA_ARGS__)
#define EVP_PKEY_up_ref(pkey) CRYPTO_add(&(pkey)->references, 1, CRYPTO_LOCK_EVP_PKEY)
#define X509_up_ref(cert) CRYPTO_add(&(cert)->references, 1, CRYPTO_LOCK_X509)
#define X509_CRL_up_ref(crl) CRYPTO_add(&(crl)->references, 1, CRYPTO_LOCK_X509_CRL)
#define EVP_PKEY_id(pky) (pky)->type
#define EVP_PKEY_get0_DSA(pky) (pky)->pkey.dsa
#define EVP_PKEY_get0_RSA(pky) (pky)->pkey.rsa
#define EVP_PKEY_get0_DH(pky) (pky)->pkey.dh
#define X509_CRL_get0_lastUpdate X509_CRL_get_lastUpdate
#define X509_CRL_get0_nextUpdate X509_CRL_get_nextUpdate
#define X509_REQ_get_signature_nid(req) OBJ_obj2nid((req)->sig_alg->algorithm)
#define X509_CRL_get_signature_nid(crl) OBJ_obj2nid((crl)->sig_alg->algorithm)
#define X509_REVOKED_get0_serialNumber(rev) (rev)->serialNumber
#define X509_REVOKED_get0_revocationDate(rev) (rev)->revocationDate
#endif // OPENSSL_VERSION_NUMBER < 0x10100000L
#endif // OSSL110COMPAT_H
diff --git a/plugins/qca-ossl/qca-ossl.cpp b/plugins/qca-ossl/qca-ossl.cpp
index 6ddad895..c5f4af68 100644
--- a/plugins/qca-ossl/qca-ossl.cpp
+++ b/plugins/qca-ossl/qca-ossl.cpp
@@ -1,7656 +1,7650 @@
/*
* Copyright (C) 2004-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2013-2016 Ivan Romanov <drizt@land.ru>
* Copyright (C) 2017 Fabian Vogt <fabian@ritter-vogt.de>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <qcaprovider.h>
#include <QDebug>
#include <QScopedPointer>
#include <QTime>
#include <QtPlugin>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/kdf.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <openssl/rand.h>
#include <openssl/pem.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#include <openssl/pkcs12.h>
#include <openssl/ssl.h>
#include "ossl110-compat.h"
#ifndef OSSL_097
// comment this out if you'd rather use openssl 0.9.6
#define OSSL_097
#endif
#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10000000L
// OpenSSL 1.0.0 makes a few changes that aren't very C++ friendly...
// Among other things, CHECKED_PTR_OF returns a void*, but is used in
// contexts requiring STACK pointers.
#undef CHECKED_PTR_OF
#define CHECKED_PTR_OF(type, p) \
- ((_STACK*) (1 ? p : (type*)0))
+ ((_STACK*) (1 ? p : (type*)0))
#endif
#if OPENSSL_VERSION_NUMBER >= 0x10100000L
- #define OSSL_110
+#define OSSL_110
#endif
// OpenSSL 1.1.0 compatibility macros
#ifdef OSSL_110
#define M_ASN1_IA5STRING_new() ASN1_IA5STRING_new()
#define RSA_F_RSA_EAY_PRIVATE_DECRYPT RSA_F_RSA_OSSL_PRIVATE_DECRYPT
#endif
using namespace QCA;
-namespace opensslQCAPlugin {
+namespace opensslQCAPlugin
+{
//----------------------------------------------------------------------------
// Util
//----------------------------------------------------------------------------
static SecureArray bio2buf(BIO *b)
{
- SecureArray buf;
- while(1) {
- SecureArray block(1024);
- int ret = BIO_read(b, block.data(), block.size());
- if(ret <= 0)
- break;
- block.resize(ret);
- buf.append(block);
- if(ret != 1024)
- break;
- }
- BIO_free(b);
- return buf;
+ SecureArray buf;
+ while (1) {
+ SecureArray block(1024);
+ int ret = BIO_read(b, block.data(), block.size());
+ if (ret <= 0) {
+ break;
+ }
+ block.resize(ret);
+ buf.append(block);
+ if (ret != 1024) {
+ break;
+ }
+ }
+ BIO_free(b);
+ return buf;
}
static QByteArray bio2ba(BIO *b)
{
- QByteArray buf;
- while(1) {
- QByteArray block(1024, 0);
- int ret = BIO_read(b, block.data(), block.size());
- if(ret <= 0)
- break;
- block.resize(ret);
- buf.append(block);
- if(ret != 1024)
- break;
- }
- BIO_free(b);
- return buf;
+ QByteArray buf;
+ while (1) {
+ QByteArray block(1024, 0);
+ int ret = BIO_read(b, block.data(), block.size());
+ if (ret <= 0) {
+ break;
+ }
+ block.resize(ret);
+ buf.append(block);
+ if (ret != 1024) {
+ break;
+ }
+ }
+ BIO_free(b);
+ return buf;
}
static BigInteger bn2bi(const BIGNUM *n)
{
- SecureArray buf(BN_num_bytes(n) + 1);
- buf[0] = 0; // positive
- BN_bn2bin(n, (unsigned char *)buf.data() + 1);
- return BigInteger(buf);
+ SecureArray buf(BN_num_bytes(n) + 1);
+ buf[0] = 0; // positive
+ BN_bn2bin(n, (unsigned char *)buf.data() + 1);
+ return BigInteger(buf);
}
static BIGNUM *bi2bn(const BigInteger &n)
{
- SecureArray buf = n.toArray();
- return BN_bin2bn((const unsigned char *)buf.data(), buf.size(), NULL);
+ SecureArray buf = n.toArray();
+ return BN_bin2bn((const unsigned char *)buf.data(), buf.size(), NULL);
}
// take lowest bytes of BIGNUM to fit
// pad with high byte zeroes to fit
static SecureArray bn2fixedbuf(const BIGNUM *n, int size)
{
- SecureArray buf(BN_num_bytes(n));
- BN_bn2bin(n, (unsigned char *)buf.data());
-
- SecureArray out(size);
- memset(out.data(), 0, size);
- int len = qMin(size, buf.size());
- memcpy(out.data() + (size - len), buf.data(), len);
- return out;
+ SecureArray buf(BN_num_bytes(n));
+ BN_bn2bin(n, (unsigned char *)buf.data());
+
+ SecureArray out(size);
+ memset(out.data(), 0, size);
+ int len = qMin(size, buf.size());
+ memcpy(out.data() + (size - len), buf.data(), len);
+ return out;
}
static SecureArray dsasig_der_to_raw(const SecureArray &in)
{
- DSA_SIG *sig = DSA_SIG_new();
- const unsigned char *inp = (const unsigned char *)in.data();
- d2i_DSA_SIG(&sig, &inp, in.size());
+ DSA_SIG *sig = DSA_SIG_new();
+ const unsigned char *inp = (const unsigned char *)in.data();
+ d2i_DSA_SIG(&sig, &inp, in.size());
- const BIGNUM *bnr, *bns;
- DSA_SIG_get0(sig, &bnr, &bns);
+ const BIGNUM *bnr, *bns;
+ DSA_SIG_get0(sig, &bnr, &bns);
- SecureArray part_r = bn2fixedbuf(bnr, 20);
- SecureArray part_s = bn2fixedbuf(bns, 20);
- SecureArray result;
- result.append(part_r);
- result.append(part_s);
+ SecureArray part_r = bn2fixedbuf(bnr, 20);
+ SecureArray part_s = bn2fixedbuf(bns, 20);
+ SecureArray result;
+ result.append(part_r);
+ result.append(part_s);
- DSA_SIG_free(sig);
- return result;
+ DSA_SIG_free(sig);
+ return result;
}
static SecureArray dsasig_raw_to_der(const SecureArray &in)
{
- if(in.size() != 40)
- return SecureArray();
-
- DSA_SIG *sig = DSA_SIG_new();
- SecureArray part_r(20); BIGNUM *bnr;
- SecureArray part_s(20); BIGNUM *bns;
- memcpy(part_r.data(), in.data(), 20);
- memcpy(part_s.data(), in.data() + 20, 20);
- bnr = BN_bin2bn((const unsigned char *)part_r.data(), part_r.size(), NULL);
- bns = BN_bin2bn((const unsigned char *)part_s.data(), part_s.size(), NULL);
-
- if(DSA_SIG_set0(sig, bnr, bns) == 0)
- return SecureArray();
- // Not documented what happens in the failure case, free bnr and bns?
-
- int len = i2d_DSA_SIG(sig, NULL);
- SecureArray result(len);
- unsigned char *p = (unsigned char *)result.data();
- i2d_DSA_SIG(sig, &p);
-
- DSA_SIG_free(sig);
- return result;
+ if (in.size() != 40) {
+ return SecureArray();
+ }
+
+ DSA_SIG *sig = DSA_SIG_new();
+ SecureArray part_r(20); BIGNUM *bnr;
+ SecureArray part_s(20); BIGNUM *bns;
+ memcpy(part_r.data(), in.data(), 20);
+ memcpy(part_s.data(), in.data() + 20, 20);
+ bnr = BN_bin2bn((const unsigned char *)part_r.data(), part_r.size(), NULL);
+ bns = BN_bin2bn((const unsigned char *)part_s.data(), part_s.size(), NULL);
+
+ if (DSA_SIG_set0(sig, bnr, bns) == 0) {
+ return SecureArray();
+ }
+ // Not documented what happens in the failure case, free bnr and bns?
+
+ int len = i2d_DSA_SIG(sig, NULL);
+ SecureArray result(len);
+ unsigned char *p = (unsigned char *)result.data();
+ i2d_DSA_SIG(sig, &p);
+
+ DSA_SIG_free(sig);
+ return result;
}
static int passphrase_cb(char *buf, int size, int rwflag, void *u)
{
- Q_UNUSED(buf);
- Q_UNUSED(size);
- Q_UNUSED(rwflag);
- Q_UNUSED(u);
- return 0;
+ Q_UNUSED(buf);
+ Q_UNUSED(size);
+ Q_UNUSED(rwflag);
+ Q_UNUSED(u);
+ return 0;
}
/*static bool is_basic_constraint(const ConstraintType &t)
{
- bool basic = false;
- switch(t.known())
- {
- case DigitalSignature:
- case NonRepudiation:
- case KeyEncipherment:
- case DataEncipherment:
- case KeyAgreement:
- case KeyCertificateSign:
- case CRLSign:
- case EncipherOnly:
- case DecipherOnly:
- basic = true;
- break;
-
- case ServerAuth:
- case ClientAuth:
- case CodeSigning:
- case EmailProtection:
- case IPSecEndSystem:
- case IPSecTunnel:
- case IPSecUser:
- case TimeStamping:
- case OCSPSigning:
- break;
- }
- return basic;
+ bool basic = false;
+ switch(t.known())
+ {
+ case DigitalSignature:
+ case NonRepudiation:
+ case KeyEncipherment:
+ case DataEncipherment:
+ case KeyAgreement:
+ case KeyCertificateSign:
+ case CRLSign:
+ case EncipherOnly:
+ case DecipherOnly:
+ basic = true;
+ break;
+
+ case ServerAuth:
+ case ClientAuth:
+ case CodeSigning:
+ case EmailProtection:
+ case IPSecEndSystem:
+ case IPSecTunnel:
+ case IPSecUser:
+ case TimeStamping:
+ case OCSPSigning:
+ break;
+ }
+ return basic;
}
static Constraints basic_only(const Constraints &list)
{
- Constraints out;
- for(int n = 0; n < list.count(); ++n)
- {
- if(is_basic_constraint(list[n]))
- out += list[n];
- }
- return out;
+ Constraints out;
+ for(int n = 0; n < list.count(); ++n)
+ {
+ if(is_basic_constraint(list[n]))
+ out += list[n];
+ }
+ return out;
}
static Constraints ext_only(const Constraints &list)
{
- Constraints out;
- for(int n = 0; n < list.count(); ++n)
- {
- if(!is_basic_constraint(list[n]))
- out += list[n];
- }
- return out;
+ Constraints out;
+ for(int n = 0; n < list.count(); ++n)
+ {
+ if(!is_basic_constraint(list[n]))
+ out += list[n];
+ }
+ return out;
}*/
// logic from Botan
/*static Constraints find_constraints(const PKeyContext &key, const Constraints &orig)
{
- Constraints constraints;
+ Constraints constraints;
- if(key.key()->type() == PKey::RSA)
- constraints += KeyEncipherment;
+ if(key.key()->type() == PKey::RSA)
+ constraints += KeyEncipherment;
- if(key.key()->type() == PKey::DH)
- constraints += KeyAgreement;
+ if(key.key()->type() == PKey::DH)
+ constraints += KeyAgreement;
- if(key.key()->type() == PKey::RSA || key.key()->type() == PKey::DSA)
- {
- constraints += DigitalSignature;
- constraints += NonRepudiation;
- }
+ if(key.key()->type() == PKey::RSA || key.key()->type() == PKey::DSA)
+ {
+ constraints += DigitalSignature;
+ constraints += NonRepudiation;
+ }
- Constraints limits = basic_only(orig);
- Constraints the_rest = ext_only(orig);
+ Constraints limits = basic_only(orig);
+ Constraints the_rest = ext_only(orig);
- if(!limits.isEmpty())
- {
- Constraints reduced;
- for(int n = 0; n < constraints.count(); ++n)
- {
- if(limits.contains(constraints[n]))
- reduced += constraints[n];
- }
- constraints = reduced;
- }
+ if(!limits.isEmpty())
+ {
+ Constraints reduced;
+ for(int n = 0; n < constraints.count(); ++n)
+ {
+ if(limits.contains(constraints[n]))
+ reduced += constraints[n];
+ }
+ constraints = reduced;
+ }
- constraints += the_rest;
+ constraints += the_rest;
- return constraints;
+ return constraints;
}*/
static void try_add_name_item(X509_NAME **name, int nid, const QString &val)
{
- if(val.isEmpty())
- return;
- QByteArray buf = val.toLatin1();
- if(!(*name))
- *name = X509_NAME_new();
- X509_NAME_add_entry_by_NID(*name, nid, MBSTRING_ASC, (unsigned char *)buf.data(), buf.size(), -1, 0);
+ if (val.isEmpty()) {
+ return;
+ }
+ QByteArray buf = val.toLatin1();
+ if (!(*name)) {
+ *name = X509_NAME_new();
+ }
+ X509_NAME_add_entry_by_NID(*name, nid, MBSTRING_ASC, (unsigned char *)buf.data(), buf.size(), -1, 0);
}
static X509_NAME *new_cert_name(const CertificateInfo &info)
{
- X509_NAME *name = 0;
- // FIXME support multiple items of each type
- try_add_name_item(&name, NID_commonName, info.value(CommonName));
- try_add_name_item(&name, NID_countryName, info.value(Country));
- try_add_name_item(&name, NID_localityName, info.value(Locality));
- try_add_name_item(&name, NID_stateOrProvinceName, info.value(State));
- try_add_name_item(&name, NID_organizationName, info.value(Organization));
- try_add_name_item(&name, NID_organizationalUnitName, info.value(OrganizationalUnit));
- return name;
+ X509_NAME *name = 0;
+ // FIXME support multiple items of each type
+ try_add_name_item(&name, NID_commonName, info.value(CommonName));
+ try_add_name_item(&name, NID_countryName, info.value(Country));
+ try_add_name_item(&name, NID_localityName, info.value(Locality));
+ try_add_name_item(&name, NID_stateOrProvinceName, info.value(State));
+ try_add_name_item(&name, NID_organizationName, info.value(Organization));
+ try_add_name_item(&name, NID_organizationalUnitName, info.value(OrganizationalUnit));
+ return name;
}
static void try_get_name_item(X509_NAME *name, int nid, const CertificateInfoType &t, CertificateInfo *info)
{
- int loc;
- loc = -1;
- while ((loc = X509_NAME_get_index_by_NID(name, nid, loc)) != -1) {
- X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, loc);
- ASN1_STRING *data = X509_NAME_ENTRY_get_data(ne);
- QByteArray cs((const char *)data->data, data->length);
- info->insert(t, QString::fromLatin1(cs));
- }
+ int loc;
+ loc = -1;
+ while ((loc = X509_NAME_get_index_by_NID(name, nid, loc)) != -1) {
+ X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, loc);
+ ASN1_STRING *data = X509_NAME_ENTRY_get_data(ne);
+ QByteArray cs((const char *)data->data, data->length);
+ info->insert(t, QString::fromLatin1(cs));
+ }
}
static void try_get_name_item_by_oid(X509_NAME *name, const QString &oidText, const CertificateInfoType &t, CertificateInfo *info)
{
- ASN1_OBJECT *oid = OBJ_txt2obj( oidText.toLatin1().data(), 1); // 1 = only accept dotted input
- if(!oid)
- return;
-
- int loc;
- loc = -1;
- while ((loc = X509_NAME_get_index_by_OBJ(name, oid, loc)) != -1) {
- X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, loc);
- ASN1_STRING *data = X509_NAME_ENTRY_get_data(ne);
- QByteArray cs((const char *)data->data, data->length);
- info->insert(t, QString::fromLatin1(cs));
- qDebug() << "oid: " << oidText << ", result: " << cs;
- }
- ASN1_OBJECT_free(oid);
+ ASN1_OBJECT *oid = OBJ_txt2obj(oidText.toLatin1().data(), 1); // 1 = only accept dotted input
+ if (!oid) {
+ return;
+ }
+
+ int loc;
+ loc = -1;
+ while ((loc = X509_NAME_get_index_by_OBJ(name, oid, loc)) != -1) {
+ X509_NAME_ENTRY *ne = X509_NAME_get_entry(name, loc);
+ ASN1_STRING *data = X509_NAME_ENTRY_get_data(ne);
+ QByteArray cs((const char *)data->data, data->length);
+ info->insert(t, QString::fromLatin1(cs));
+ qDebug() << "oid: " << oidText << ", result: " << cs;
+ }
+ ASN1_OBJECT_free(oid);
}
static CertificateInfo get_cert_name(X509_NAME *name)
{
- CertificateInfo info;
- try_get_name_item(name, NID_commonName, CommonName, &info);
- try_get_name_item(name, NID_countryName, Country, &info);
- try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.3"), IncorporationCountry, &info);
- try_get_name_item(name, NID_localityName, Locality, &info);
- try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.1"), IncorporationLocality, &info);
- try_get_name_item(name, NID_stateOrProvinceName, State, &info);
- try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.2"), IncorporationState, &info);
- try_get_name_item(name, NID_organizationName, Organization, &info);
- try_get_name_item(name, NID_organizationalUnitName, OrganizationalUnit, &info);
-
- // legacy email
- {
- CertificateInfo p9_info;
- try_get_name_item(name, NID_pkcs9_emailAddress, EmailLegacy, &p9_info);
- QList<QString> emails = info.values(Email);
- QMapIterator<CertificateInfoType,QString> it(p9_info);
- while(it.hasNext())
- {
- it.next();
- if(!emails.contains(it.value()))
- info.insert(Email, it.value());
- }
- }
-
- return info;
+ CertificateInfo info;
+ try_get_name_item(name, NID_commonName, CommonName, &info);
+ try_get_name_item(name, NID_countryName, Country, &info);
+ try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.3"), IncorporationCountry, &info);
+ try_get_name_item(name, NID_localityName, Locality, &info);
+ try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.1"), IncorporationLocality, &info);
+ try_get_name_item(name, NID_stateOrProvinceName, State, &info);
+ try_get_name_item_by_oid(name, QString("1.3.6.1.4.1.311.60.2.1.2"), IncorporationState, &info);
+ try_get_name_item(name, NID_organizationName, Organization, &info);
+ try_get_name_item(name, NID_organizationalUnitName, OrganizationalUnit, &info);
+
+ // legacy email
+ {
+ CertificateInfo p9_info;
+ try_get_name_item(name, NID_pkcs9_emailAddress, EmailLegacy, &p9_info);
+ QList<QString> emails = info.values(Email);
+ QMapIterator<CertificateInfoType, QString> it(p9_info);
+ while (it.hasNext()) {
+ it.next();
+ if (!emails.contains(it.value())) {
+ info.insert(Email, it.value());
+ }
+ }
+ }
+
+ return info;
}
static X509_EXTENSION *new_subject_key_id(X509 *cert)
{
- X509V3_CTX ctx;
- X509V3_set_ctx_nodb(&ctx);
- X509V3_set_ctx(&ctx, NULL, cert, NULL, NULL, 0);
- X509_EXTENSION *ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_subject_key_identifier, (char *)"hash");
- return ex;
+ X509V3_CTX ctx;
+ X509V3_set_ctx_nodb(&ctx);
+ X509V3_set_ctx(&ctx, NULL, cert, NULL, NULL, 0);
+ X509_EXTENSION *ex = X509V3_EXT_conf_nid(NULL, &ctx, NID_subject_key_identifier, (char *)"hash");
+ return ex;
}
static X509_EXTENSION *new_basic_constraints(bool ca, int pathlen)
{
- BASIC_CONSTRAINTS *bs = BASIC_CONSTRAINTS_new();
- bs->ca = (ca ? 1: 0);
- bs->pathlen = ASN1_INTEGER_new();
- ASN1_INTEGER_set(bs->pathlen, pathlen);
-
- X509_EXTENSION *ex = X509V3_EXT_i2d(NID_basic_constraints, 1, bs); // 1 = critical
- BASIC_CONSTRAINTS_free(bs);
- return ex;
+ BASIC_CONSTRAINTS *bs = BASIC_CONSTRAINTS_new();
+ bs->ca = (ca ? 1 : 0);
+ bs->pathlen = ASN1_INTEGER_new();
+ ASN1_INTEGER_set(bs->pathlen, pathlen);
+
+ X509_EXTENSION *ex = X509V3_EXT_i2d(NID_basic_constraints, 1, bs); // 1 = critical
+ BASIC_CONSTRAINTS_free(bs);
+ return ex;
}
static void get_basic_constraints(X509_EXTENSION *ex, bool *ca, int *pathlen)
{
- BASIC_CONSTRAINTS *bs = (BASIC_CONSTRAINTS *)X509V3_EXT_d2i(ex);
- *ca = (bs->ca ? true: false);
- if(bs->pathlen)
- *pathlen = ASN1_INTEGER_get(bs->pathlen);
- else
- *pathlen = 0;
- BASIC_CONSTRAINTS_free(bs);
+ BASIC_CONSTRAINTS *bs = (BASIC_CONSTRAINTS *)X509V3_EXT_d2i(ex);
+ *ca = (bs->ca ? true : false);
+ if (bs->pathlen) {
+ *pathlen = ASN1_INTEGER_get(bs->pathlen);
+ } else {
+ *pathlen = 0;
+ }
+ BASIC_CONSTRAINTS_free(bs);
}
-enum ConstraintBit
-{
- Bit_DigitalSignature = 0,
- Bit_NonRepudiation = 1,
- Bit_KeyEncipherment = 2,
- Bit_DataEncipherment = 3,
- Bit_KeyAgreement = 4,
- Bit_KeyCertificateSign = 5,
- Bit_CRLSign = 6,
- Bit_EncipherOnly = 7,
- Bit_DecipherOnly = 8
+enum ConstraintBit {
+ Bit_DigitalSignature = 0,
+ Bit_NonRepudiation = 1,
+ Bit_KeyEncipherment = 2,
+ Bit_DataEncipherment = 3,
+ Bit_KeyAgreement = 4,
+ Bit_KeyCertificateSign = 5,
+ Bit_CRLSign = 6,
+ Bit_EncipherOnly = 7,
+ Bit_DecipherOnly = 8
};
static QByteArray ipaddress_string_to_bytes(const QString &)
{
- return QByteArray(4, 0);
+ return QByteArray(4, 0);
}
static GENERAL_NAME *new_general_name(const CertificateInfoType &t, const QString &val)
{
- GENERAL_NAME *name = 0;
- switch(t.known())
- {
- case Email:
- {
- QByteArray buf = val.toLatin1();
-
- ASN1_IA5STRING *str = M_ASN1_IA5STRING_new();
- ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
-
- name = GENERAL_NAME_new();
- name->type = GEN_EMAIL;
- name->d.rfc822Name = str;
- break;
- }
- case URI:
- {
- QByteArray buf = val.toLatin1();
-
- ASN1_IA5STRING *str = M_ASN1_IA5STRING_new();
- ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
-
- name = GENERAL_NAME_new();
- name->type = GEN_URI;
- name->d.uniformResourceIdentifier = str;
- break;
- }
- case DNS:
- {
- QByteArray buf = val.toLatin1();
-
- ASN1_IA5STRING *str = M_ASN1_IA5STRING_new();
- ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
-
- name = GENERAL_NAME_new();
- name->type = GEN_DNS;
- name->d.dNSName = str;
- break;
- }
- case IPAddress:
- {
- QByteArray buf = ipaddress_string_to_bytes(val);
-
- ASN1_OCTET_STRING *str = ASN1_OCTET_STRING_new();
- ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
-
- name = GENERAL_NAME_new();
- name->type = GEN_IPADD;
- name->d.iPAddress = str;
- break;
- }
- case XMPP:
- {
- QByteArray buf = val.toUtf8();
-
- ASN1_UTF8STRING *str = ASN1_UTF8STRING_new();
- ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
-
- ASN1_TYPE *at = ASN1_TYPE_new();
- at->type = V_ASN1_UTF8STRING;
- at->value.utf8string = str;
-
- OTHERNAME *other = OTHERNAME_new();
- other->type_id = OBJ_txt2obj("1.3.6.1.5.5.7.8.5", 1); // 1 = only accept dotted input
- other->value = at;
-
- name = GENERAL_NAME_new();
- name->type = GEN_OTHERNAME;
- name->d.otherName = other;
- break;
- }
- default:
- break;
- }
- return name;
+ GENERAL_NAME *name = 0;
+ switch (t.known()) {
+ case Email: {
+ QByteArray buf = val.toLatin1();
+
+ ASN1_IA5STRING *str = M_ASN1_IA5STRING_new();
+ ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
+
+ name = GENERAL_NAME_new();
+ name->type = GEN_EMAIL;
+ name->d.rfc822Name = str;
+ break;
+ }
+ case URI: {
+ QByteArray buf = val.toLatin1();
+
+ ASN1_IA5STRING *str = M_ASN1_IA5STRING_new();
+ ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
+
+ name = GENERAL_NAME_new();
+ name->type = GEN_URI;
+ name->d.uniformResourceIdentifier = str;
+ break;
+ }
+ case DNS: {
+ QByteArray buf = val.toLatin1();
+
+ ASN1_IA5STRING *str = M_ASN1_IA5STRING_new();
+ ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
+
+ name = GENERAL_NAME_new();
+ name->type = GEN_DNS;
+ name->d.dNSName = str;
+ break;
+ }
+ case IPAddress: {
+ QByteArray buf = ipaddress_string_to_bytes(val);
+
+ ASN1_OCTET_STRING *str = ASN1_OCTET_STRING_new();
+ ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
+
+ name = GENERAL_NAME_new();
+ name->type = GEN_IPADD;
+ name->d.iPAddress = str;
+ break;
+ }
+ case XMPP: {
+ QByteArray buf = val.toUtf8();
+
+ ASN1_UTF8STRING *str = ASN1_UTF8STRING_new();
+ ASN1_STRING_set((ASN1_STRING *)str, (unsigned char *)buf.data(), buf.size());
+
+ ASN1_TYPE *at = ASN1_TYPE_new();
+ at->type = V_ASN1_UTF8STRING;
+ at->value.utf8string = str;
+
+ OTHERNAME *other = OTHERNAME_new();
+ other->type_id = OBJ_txt2obj("1.3.6.1.5.5.7.8.5", 1); // 1 = only accept dotted input
+ other->value = at;
+
+ name = GENERAL_NAME_new();
+ name->type = GEN_OTHERNAME;
+ name->d.otherName = other;
+ break;
+ }
+ default:
+ break;
+ }
+ return name;
}
static void try_add_general_name(GENERAL_NAMES **gn, const CertificateInfoType &t, const QString &val)
{
- if(val.isEmpty())
- return;
- GENERAL_NAME *name = new_general_name(t, val);
- if(name)
- {
- if(!(*gn))
- *gn = sk_GENERAL_NAME_new_null();
- sk_GENERAL_NAME_push(*gn, name);
- }
+ if (val.isEmpty()) {
+ return;
+ }
+ GENERAL_NAME *name = new_general_name(t, val);
+ if (name) {
+ if (!(*gn)) {
+ *gn = sk_GENERAL_NAME_new_null();
+ }
+ sk_GENERAL_NAME_push(*gn, name);
+ }
}
static X509_EXTENSION *new_cert_subject_alt_name(const CertificateInfo &info)
{
- GENERAL_NAMES *gn = 0;
- // FIXME support multiple items of each type
- try_add_general_name(&gn, Email, info.value(Email));
- try_add_general_name(&gn, URI, info.value(URI));
- try_add_general_name(&gn, DNS, info.value(DNS));
- try_add_general_name(&gn, IPAddress, info.value(IPAddress));
- try_add_general_name(&gn, XMPP, info.value(XMPP));
- if(!gn)
- return 0;
-
- X509_EXTENSION *ex = X509V3_EXT_i2d(NID_subject_alt_name, 0, gn);
- sk_GENERAL_NAME_pop_free(gn, GENERAL_NAME_free);
- return ex;
+ GENERAL_NAMES *gn = 0;
+ // FIXME support multiple items of each type
+ try_add_general_name(&gn, Email, info.value(Email));
+ try_add_general_name(&gn, URI, info.value(URI));
+ try_add_general_name(&gn, DNS, info.value(DNS));
+ try_add_general_name(&gn, IPAddress, info.value(IPAddress));
+ try_add_general_name(&gn, XMPP, info.value(XMPP));
+ if (!gn) {
+ return 0;
+ }
+
+ X509_EXTENSION *ex = X509V3_EXT_i2d(NID_subject_alt_name, 0, gn);
+ sk_GENERAL_NAME_pop_free(gn, GENERAL_NAME_free);
+ return ex;
}
static GENERAL_NAME *find_next_general_name(GENERAL_NAMES *names, int type, int *pos)
{
- int temp = *pos;
- GENERAL_NAME *gn = 0;
- *pos = -1;
- for(int n = temp; n < sk_GENERAL_NAME_num(names); ++n)
- {
- GENERAL_NAME *i = sk_GENERAL_NAME_value(names, n);
- if(i->type == type)
- {
- gn = i;
- *pos = n;
- break;
- }
- }
- return gn;
+ int temp = *pos;
+ GENERAL_NAME *gn = 0;
+ *pos = -1;
+ for (int n = temp; n < sk_GENERAL_NAME_num(names); ++n) {
+ GENERAL_NAME *i = sk_GENERAL_NAME_value(names, n);
+ if (i->type == type) {
+ gn = i;
+ *pos = n;
+ break;
+ }
+ }
+ return gn;
}
static QByteArray qca_ASN1_STRING_toByteArray(ASN1_STRING *x)
{
- return QByteArray(reinterpret_cast<const char *>(ASN1_STRING_get0_data(x)), ASN1_STRING_length(x));
+ return QByteArray(reinterpret_cast<const char *>(ASN1_STRING_get0_data(x)), ASN1_STRING_length(x));
}
static void try_get_general_name(GENERAL_NAMES *names, const CertificateInfoType &t, CertificateInfo *info)
{
- switch(t.known())
- {
- case Email:
- {
- int pos = 0;
- while (pos != -1)
- {
- GENERAL_NAME *gn = find_next_general_name(names, GEN_EMAIL, &pos);
- if (pos != -1)
- {
- QByteArray cs = qca_ASN1_STRING_toByteArray(gn->d.rfc822Name);
- info->insert(t, QString::fromLatin1(cs));
- ++pos;
- }
- }
- break;
- }
- case URI:
- {
- int pos = 0;
- while (pos != -1)
- {
- GENERAL_NAME *gn = find_next_general_name(names, GEN_URI, &pos);
- if (pos != -1)
- {
- QByteArray cs= qca_ASN1_STRING_toByteArray(gn->d.uniformResourceIdentifier);
- info->insert(t, QString::fromLatin1(cs));
- ++pos;
- }
- }
- break;
- }
- case DNS:
- {
- int pos = 0;
- while (pos != -1)
- {
- GENERAL_NAME *gn = find_next_general_name(names, GEN_DNS, &pos);
- if (pos != -1)
- {
- QByteArray cs = qca_ASN1_STRING_toByteArray(gn->d.dNSName);
- info->insert(t, QString::fromLatin1(cs));
- ++pos;
- }
- }
- break;
- }
- case IPAddress:
- {
- int pos = 0;
- while (pos != -1)
- {
- GENERAL_NAME *gn = find_next_general_name(names, GEN_IPADD, &pos);
- if (pos != -1)
- {
- ASN1_OCTET_STRING *str = gn->d.iPAddress;
- QByteArray buf = qca_ASN1_STRING_toByteArray(str);
-
- QString out;
- // IPv4 (TODO: handle IPv6)
- if(buf.size() == 4)
- {
- out = "0.0.0.0";
- }
- else
- break;
- info->insert(t, out);
- ++pos;
- }
- }
- break;
- }
- case XMPP:
- {
- int pos = 0;
- while( pos != -1)
- {
- GENERAL_NAME *gn = find_next_general_name(names, GEN_OTHERNAME, &pos);
- if (pos != -1)
- {
- OTHERNAME *other = gn->d.otherName;
- if(!other)
- break;
-
- ASN1_OBJECT *obj = OBJ_txt2obj("1.3.6.1.5.5.7.8.5", 1); // 1 = only accept dotted input
- if(OBJ_cmp(other->type_id, obj) != 0)
- break;
- ASN1_OBJECT_free(obj);
-
- ASN1_TYPE *at = other->value;
- if(at->type != V_ASN1_UTF8STRING)
- break;
-
- ASN1_UTF8STRING *str = at->value.utf8string;
- QByteArray buf = qca_ASN1_STRING_toByteArray(str);
- info->insert(t, QString::fromUtf8(buf));
- ++pos;
- }
- }
- break;
- }
- default:
- break;
- }
+ switch (t.known()) {
+ case Email: {
+ int pos = 0;
+ while (pos != -1) {
+ GENERAL_NAME *gn = find_next_general_name(names, GEN_EMAIL, &pos);
+ if (pos != -1) {
+ QByteArray cs = qca_ASN1_STRING_toByteArray(gn->d.rfc822Name);
+ info->insert(t, QString::fromLatin1(cs));
+ ++pos;
+ }
+ }
+ break;
+ }
+ case URI: {
+ int pos = 0;
+ while (pos != -1) {
+ GENERAL_NAME *gn = find_next_general_name(names, GEN_URI, &pos);
+ if (pos != -1) {
+ QByteArray cs = qca_ASN1_STRING_toByteArray(gn->d.uniformResourceIdentifier);
+ info->insert(t, QString::fromLatin1(cs));
+ ++pos;
+ }
+ }
+ break;
+ }
+ case DNS: {
+ int pos = 0;
+ while (pos != -1) {
+ GENERAL_NAME *gn = find_next_general_name(names, GEN_DNS, &pos);
+ if (pos != -1) {
+ QByteArray cs = qca_ASN1_STRING_toByteArray(gn->d.dNSName);
+ info->insert(t, QString::fromLatin1(cs));
+ ++pos;
+ }
+ }
+ break;
+ }
+ case IPAddress: {
+ int pos = 0;
+ while (pos != -1) {
+ GENERAL_NAME *gn = find_next_general_name(names, GEN_IPADD, &pos);
+ if (pos != -1) {
+ ASN1_OCTET_STRING *str = gn->d.iPAddress;
+ QByteArray buf = qca_ASN1_STRING_toByteArray(str);
+
+ QString out;
+ // IPv4 (TODO: handle IPv6)
+ if (buf.size() == 4) {
+ out = "0.0.0.0";
+ } else {
+ break;
+ }
+ info->insert(t, out);
+ ++pos;
+ }
+ }
+ break;
+ }
+ case XMPP: {
+ int pos = 0;
+ while (pos != -1) {
+ GENERAL_NAME *gn = find_next_general_name(names, GEN_OTHERNAME, &pos);
+ if (pos != -1) {
+ OTHERNAME *other = gn->d.otherName;
+ if (!other) {
+ break;
+ }
+
+ ASN1_OBJECT *obj = OBJ_txt2obj("1.3.6.1.5.5.7.8.5", 1); // 1 = only accept dotted input
+ if (OBJ_cmp(other->type_id, obj) != 0) {
+ break;
+ }
+ ASN1_OBJECT_free(obj);
+
+ ASN1_TYPE *at = other->value;
+ if (at->type != V_ASN1_UTF8STRING) {
+ break;
+ }
+
+ ASN1_UTF8STRING *str = at->value.utf8string;
+ QByteArray buf = qca_ASN1_STRING_toByteArray(str);
+ info->insert(t, QString::fromUtf8(buf));
+ ++pos;
+ }
+ }
+ break;
+ }
+ default:
+ break;
+ }
}
static CertificateInfo get_cert_alt_name(X509_EXTENSION *ex)
{
- CertificateInfo info;
- GENERAL_NAMES *gn = (GENERAL_NAMES *)X509V3_EXT_d2i(ex);
- try_get_general_name(gn, Email, &info);
- try_get_general_name(gn, URI, &info);
- try_get_general_name(gn, DNS, &info);
- try_get_general_name(gn, IPAddress, &info);
- try_get_general_name(gn, XMPP, &info);
- GENERAL_NAMES_free(gn);
- return info;
+ CertificateInfo info;
+ GENERAL_NAMES *gn = (GENERAL_NAMES *)X509V3_EXT_d2i(ex);
+ try_get_general_name(gn, Email, &info);
+ try_get_general_name(gn, URI, &info);
+ try_get_general_name(gn, DNS, &info);
+ try_get_general_name(gn, IPAddress, &info);
+ try_get_general_name(gn, XMPP, &info);
+ GENERAL_NAMES_free(gn);
+ return info;
}
static X509_EXTENSION *new_cert_key_usage(const Constraints &constraints)
{
- ASN1_BIT_STRING *keyusage = 0;
- for(int n = 0; n < constraints.count(); ++n)
- {
- int bit = -1;
- switch(constraints[n].known())
- {
- case DigitalSignature:
- bit = Bit_DigitalSignature;
- break;
- case NonRepudiation:
- bit = Bit_NonRepudiation;
- break;
- case KeyEncipherment:
- bit = Bit_KeyEncipherment;
- break;
- case DataEncipherment:
- bit = Bit_DataEncipherment;
- break;
- case KeyAgreement:
- bit = Bit_KeyAgreement;
- break;
- case KeyCertificateSign:
- bit = Bit_KeyCertificateSign;
- break;
- case CRLSign:
- bit = Bit_CRLSign;
- break;
- case EncipherOnly:
- bit = Bit_EncipherOnly;
- break;
- case DecipherOnly:
- bit = Bit_DecipherOnly;
- break;
- default:
- break;
- }
- if(bit != -1)
- {
- if(!keyusage)
- keyusage = ASN1_BIT_STRING_new();
- ASN1_BIT_STRING_set_bit(keyusage, bit, 1);
- }
- }
- if(!keyusage)
- return 0;
-
- X509_EXTENSION *ex = X509V3_EXT_i2d(NID_key_usage, 1, keyusage); // 1 = critical
- ASN1_BIT_STRING_free(keyusage);
- return ex;
+ ASN1_BIT_STRING *keyusage = 0;
+ for (int n = 0; n < constraints.count(); ++n) {
+ int bit = -1;
+ switch (constraints[n].known()) {
+ case DigitalSignature:
+ bit = Bit_DigitalSignature;
+ break;
+ case NonRepudiation:
+ bit = Bit_NonRepudiation;
+ break;
+ case KeyEncipherment:
+ bit = Bit_KeyEncipherment;
+ break;
+ case DataEncipherment:
+ bit = Bit_DataEncipherment;
+ break;
+ case KeyAgreement:
+ bit = Bit_KeyAgreement;
+ break;
+ case KeyCertificateSign:
+ bit = Bit_KeyCertificateSign;
+ break;
+ case CRLSign:
+ bit = Bit_CRLSign;
+ break;
+ case EncipherOnly:
+ bit = Bit_EncipherOnly;
+ break;
+ case DecipherOnly:
+ bit = Bit_DecipherOnly;
+ break;
+ default:
+ break;
+ }
+ if (bit != -1) {
+ if (!keyusage) {
+ keyusage = ASN1_BIT_STRING_new();
+ }
+ ASN1_BIT_STRING_set_bit(keyusage, bit, 1);
+ }
+ }
+ if (!keyusage) {
+ return 0;
+ }
+
+ X509_EXTENSION *ex = X509V3_EXT_i2d(NID_key_usage, 1, keyusage); // 1 = critical
+ ASN1_BIT_STRING_free(keyusage);
+ return ex;
}
static Constraints get_cert_key_usage(X509_EXTENSION *ex)
{
- Constraints constraints;
- int bit_table[9] =
- {
- DigitalSignature,
- NonRepudiation,
- KeyEncipherment,
- DataEncipherment,
- KeyAgreement,
- KeyCertificateSign,
- CRLSign,
- EncipherOnly,
- DecipherOnly
- };
-
- ASN1_BIT_STRING *keyusage = (ASN1_BIT_STRING *)X509V3_EXT_d2i(ex);
- for(int n = 0; n < 9; ++n)
- {
- if(ASN1_BIT_STRING_get_bit(keyusage, n))
- constraints += ConstraintType((ConstraintTypeKnown)bit_table[n]);
- }
- ASN1_BIT_STRING_free(keyusage);
- return constraints;
+ Constraints constraints;
+ int bit_table[9] = {
+ DigitalSignature,
+ NonRepudiation,
+ KeyEncipherment,
+ DataEncipherment,
+ KeyAgreement,
+ KeyCertificateSign,
+ CRLSign,
+ EncipherOnly,
+ DecipherOnly
+ };
+
+ ASN1_BIT_STRING *keyusage = (ASN1_BIT_STRING *)X509V3_EXT_d2i(ex);
+ for (int n = 0; n < 9; ++n) {
+ if (ASN1_BIT_STRING_get_bit(keyusage, n)) {
+ constraints += ConstraintType((ConstraintTypeKnown)bit_table[n]);
+ }
+ }
+ ASN1_BIT_STRING_free(keyusage);
+ return constraints;
}
static X509_EXTENSION *new_cert_ext_key_usage(const Constraints &constraints)
{
- EXTENDED_KEY_USAGE *extkeyusage = 0;
- for(int n = 0; n < constraints.count(); ++n)
- {
- int nid = -1;
- // TODO: don't use known/nid, and instead just use OIDs
- switch(constraints[n].known())
- {
- case ServerAuth:
- nid = NID_server_auth;
- break;
- case ClientAuth:
- nid = NID_client_auth;
- break;
- case CodeSigning:
- nid = NID_code_sign;
- break;
- case EmailProtection:
- nid = NID_email_protect;
- break;
- case IPSecEndSystem:
- nid = NID_ipsecEndSystem;
- break;
- case IPSecTunnel:
- nid = NID_ipsecTunnel;
- break;
- case IPSecUser:
- nid = NID_ipsecUser;
- break;
- case TimeStamping:
- nid = NID_time_stamp;
- break;
- case OCSPSigning:
- nid = NID_OCSP_sign;
- break;
- default:
- break;
- }
- if(nid != -1)
- {
- if(!extkeyusage)
- extkeyusage = sk_ASN1_OBJECT_new_null();
- ASN1_OBJECT *obj = OBJ_nid2obj(nid);
- sk_ASN1_OBJECT_push(extkeyusage, obj);
- }
- }
- if(!extkeyusage)
- return 0;
-
- X509_EXTENSION *ex = X509V3_EXT_i2d(NID_ext_key_usage, 0, extkeyusage); // 0 = not critical
- sk_ASN1_OBJECT_pop_free(extkeyusage, ASN1_OBJECT_free);
- return ex;
+ EXTENDED_KEY_USAGE *extkeyusage = 0;
+ for (int n = 0; n < constraints.count(); ++n) {
+ int nid = -1;
+ // TODO: don't use known/nid, and instead just use OIDs
+ switch (constraints[n].known()) {
+ case ServerAuth:
+ nid = NID_server_auth;
+ break;
+ case ClientAuth:
+ nid = NID_client_auth;
+ break;
+ case CodeSigning:
+ nid = NID_code_sign;
+ break;
+ case EmailProtection:
+ nid = NID_email_protect;
+ break;
+ case IPSecEndSystem:
+ nid = NID_ipsecEndSystem;
+ break;
+ case IPSecTunnel:
+ nid = NID_ipsecTunnel;
+ break;
+ case IPSecUser:
+ nid = NID_ipsecUser;
+ break;
+ case TimeStamping:
+ nid = NID_time_stamp;
+ break;
+ case OCSPSigning:
+ nid = NID_OCSP_sign;
+ break;
+ default:
+ break;
+ }
+ if (nid != -1) {
+ if (!extkeyusage) {
+ extkeyusage = sk_ASN1_OBJECT_new_null();
+ }
+ ASN1_OBJECT *obj = OBJ_nid2obj(nid);
+ sk_ASN1_OBJECT_push(extkeyusage, obj);
+ }
+ }
+ if (!extkeyusage) {
+ return 0;
+ }
+
+ X509_EXTENSION *ex = X509V3_EXT_i2d(NID_ext_key_usage, 0, extkeyusage); // 0 = not critical
+ sk_ASN1_OBJECT_pop_free(extkeyusage, ASN1_OBJECT_free);
+ return ex;
}
static Constraints get_cert_ext_key_usage(X509_EXTENSION *ex)
{
- Constraints constraints;
-
- EXTENDED_KEY_USAGE *extkeyusage = (EXTENDED_KEY_USAGE *)X509V3_EXT_d2i(ex);
- for(int n = 0; n < sk_ASN1_OBJECT_num(extkeyusage); ++n)
- {
- ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(extkeyusage, n);
- int nid = OBJ_obj2nid(obj);
- if(nid == NID_undef)
- continue;
-
- // TODO: don't use known/nid, and instead just use OIDs
- int t = -1;
- switch(nid)
- {
- case NID_server_auth:
- t = ServerAuth;
- break;
- case NID_client_auth:
- t = ClientAuth;
- break;
- case NID_code_sign:
- t = CodeSigning;
- break;
- case NID_email_protect:
- t = EmailProtection;
- break;
- case NID_ipsecEndSystem:
- t = IPSecEndSystem;
- break;
- case NID_ipsecTunnel:
- t = IPSecTunnel;
- break;
- case NID_ipsecUser:
- t = IPSecUser;
- break;
- case NID_time_stamp:
- t = TimeStamping;
- break;
- case NID_OCSP_sign:
- t = OCSPSigning;
- break;
- };
-
- if(t == -1)
- continue;
-
- constraints.append(ConstraintType((ConstraintTypeKnown)t));
- }
- sk_ASN1_OBJECT_pop_free(extkeyusage, ASN1_OBJECT_free);
- return constraints;
+ Constraints constraints;
+
+ EXTENDED_KEY_USAGE *extkeyusage = (EXTENDED_KEY_USAGE *)X509V3_EXT_d2i(ex);
+ for (int n = 0; n < sk_ASN1_OBJECT_num(extkeyusage); ++n) {
+ ASN1_OBJECT *obj = sk_ASN1_OBJECT_value(extkeyusage, n);
+ int nid = OBJ_obj2nid(obj);
+ if (nid == NID_undef) {
+ continue;
+ }
+
+ // TODO: don't use known/nid, and instead just use OIDs
+ int t = -1;
+ switch (nid) {
+ case NID_server_auth:
+ t = ServerAuth;
+ break;
+ case NID_client_auth:
+ t = ClientAuth;
+ break;
+ case NID_code_sign:
+ t = CodeSigning;
+ break;
+ case NID_email_protect:
+ t = EmailProtection;
+ break;
+ case NID_ipsecEndSystem:
+ t = IPSecEndSystem;
+ break;
+ case NID_ipsecTunnel:
+ t = IPSecTunnel;
+ break;
+ case NID_ipsecUser:
+ t = IPSecUser;
+ break;
+ case NID_time_stamp:
+ t = TimeStamping;
+ break;
+ case NID_OCSP_sign:
+ t = OCSPSigning;
+ break;
+ };
+
+ if (t == -1) {
+ continue;
+ }
+
+ constraints.append(ConstraintType((ConstraintTypeKnown)t));
+ }
+ sk_ASN1_OBJECT_pop_free(extkeyusage, ASN1_OBJECT_free);
+ return constraints;
}
static X509_EXTENSION *new_cert_policies(const QStringList &policies)
{
- STACK_OF(POLICYINFO) *pols = 0;
- for(int n = 0; n < policies.count(); ++n)
- {
- QByteArray cs = policies[n].toLatin1();
- ASN1_OBJECT *obj = OBJ_txt2obj(cs.data(), 1); // 1 = only accept dotted input
- if(!obj)
- continue;
- if(!pols)
- pols = sk_POLICYINFO_new_null();
- POLICYINFO *pol = POLICYINFO_new();
- pol->policyid = obj;
- sk_POLICYINFO_push(pols, pol);
- }
- if(!pols)
- return 0;
-
- X509_EXTENSION *ex = X509V3_EXT_i2d(NID_certificate_policies, 0, pols); // 0 = not critical
- sk_POLICYINFO_pop_free(pols, POLICYINFO_free);
- return ex;
+ STACK_OF(POLICYINFO) *pols = 0;
+ for (int n = 0; n < policies.count(); ++n) {
+ QByteArray cs = policies[n].toLatin1();
+ ASN1_OBJECT *obj = OBJ_txt2obj(cs.data(), 1); // 1 = only accept dotted input
+ if (!obj) {
+ continue;
+ }
+ if (!pols) {
+ pols = sk_POLICYINFO_new_null();
+ }
+ POLICYINFO *pol = POLICYINFO_new();
+ pol->policyid = obj;
+ sk_POLICYINFO_push(pols, pol);
+ }
+ if (!pols) {
+ return 0;
+ }
+
+ X509_EXTENSION *ex = X509V3_EXT_i2d(NID_certificate_policies, 0, pols); // 0 = not critical
+ sk_POLICYINFO_pop_free(pols, POLICYINFO_free);
+ return ex;
}
static QStringList get_cert_policies(X509_EXTENSION *ex)
{
- QStringList out;
- STACK_OF(POLICYINFO) *pols = (STACK_OF(POLICYINFO) *)X509V3_EXT_d2i(ex);
- for(int n = 0; n < sk_POLICYINFO_num(pols); ++n)
- {
- POLICYINFO *pol = sk_POLICYINFO_value(pols, n);
- QByteArray buf(128, 0);
- OBJ_obj2txt((char *)buf.data(), buf.size(), pol->policyid, 1); // 1 = only accept dotted input
- out += QString::fromLatin1(buf);
- }
- sk_POLICYINFO_pop_free(pols, POLICYINFO_free);
- return out;
+ QStringList out;
+ STACK_OF(POLICYINFO) *pols = (STACK_OF(POLICYINFO) *)X509V3_EXT_d2i(ex);
+ for (int n = 0; n < sk_POLICYINFO_num(pols); ++n) {
+ POLICYINFO *pol = sk_POLICYINFO_value(pols, n);
+ QByteArray buf(128, 0);
+ OBJ_obj2txt((char *)buf.data(), buf.size(), pol->policyid, 1); // 1 = only accept dotted input
+ out += QString::fromLatin1(buf);
+ }
+ sk_POLICYINFO_pop_free(pols, POLICYINFO_free);
+ return out;
}
static QByteArray get_cert_subject_key_id(X509_EXTENSION *ex)
{
- ASN1_OCTET_STRING *skid = (ASN1_OCTET_STRING *)X509V3_EXT_d2i(ex);
- QByteArray out = qca_ASN1_STRING_toByteArray(skid);
- ASN1_OCTET_STRING_free(skid);
- return out;
+ ASN1_OCTET_STRING *skid = (ASN1_OCTET_STRING *)X509V3_EXT_d2i(ex);
+ QByteArray out = qca_ASN1_STRING_toByteArray(skid);
+ ASN1_OCTET_STRING_free(skid);
+ return out;
}
// If you get any more crashes in this code, please provide a copy
// of the cert to bradh AT frogmouth.net
static QByteArray get_cert_issuer_key_id(X509_EXTENSION *ex)
{
- AUTHORITY_KEYID *akid = (AUTHORITY_KEYID *)X509V3_EXT_d2i(ex);
- QByteArray out;
- if (akid->keyid)
- out = qca_ASN1_STRING_toByteArray(akid->keyid);
- AUTHORITY_KEYID_free(akid);
- return out;
+ AUTHORITY_KEYID *akid = (AUTHORITY_KEYID *)X509V3_EXT_d2i(ex);
+ QByteArray out;
+ if (akid->keyid) {
+ out = qca_ASN1_STRING_toByteArray(akid->keyid);
+ }
+ AUTHORITY_KEYID_free(akid);
+ return out;
}
static Validity convert_verify_error(int err)
{
- // TODO: ErrorExpiredCA
- Validity rc;
- switch(err)
- {
- case X509_V_ERR_CERT_REJECTED:
- rc = ErrorRejected;
- break;
- case X509_V_ERR_CERT_UNTRUSTED:
- rc = ErrorUntrusted;
- break;
- case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
- case X509_V_ERR_CERT_SIGNATURE_FAILURE:
- case X509_V_ERR_CRL_SIGNATURE_FAILURE:
- case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
- case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
- rc = ErrorSignatureFailed;
- break;
- case X509_V_ERR_INVALID_CA:
- case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
- case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
- case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
- rc = ErrorInvalidCA;
- break;
- case X509_V_ERR_INVALID_PURPOSE: // note: not used by store verify
- rc = ErrorInvalidPurpose;
- break;
- case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
- case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
- rc = ErrorSelfSigned;
- break;
- case X509_V_ERR_CERT_REVOKED:
- rc = ErrorRevoked;
- break;
- case X509_V_ERR_PATH_LENGTH_EXCEEDED:
- rc = ErrorPathLengthExceeded;
- break;
- case X509_V_ERR_CERT_NOT_YET_VALID:
- case X509_V_ERR_CERT_HAS_EXPIRED:
- case X509_V_ERR_CRL_NOT_YET_VALID:
- case X509_V_ERR_CRL_HAS_EXPIRED:
- case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
- case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
- case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
- case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
- rc = ErrorExpired;
- break;
- case X509_V_ERR_APPLICATION_VERIFICATION:
- case X509_V_ERR_OUT_OF_MEM:
- case X509_V_ERR_UNABLE_TO_GET_CRL:
- case X509_V_ERR_CERT_CHAIN_TOO_LONG:
- default:
- rc = ErrorValidityUnknown;
- break;
- }
- return rc;
+ // TODO: ErrorExpiredCA
+ Validity rc;
+ switch (err) {
+ case X509_V_ERR_CERT_REJECTED:
+ rc = ErrorRejected;
+ break;
+ case X509_V_ERR_CERT_UNTRUSTED:
+ rc = ErrorUntrusted;
+ break;
+ case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
+ case X509_V_ERR_CERT_SIGNATURE_FAILURE:
+ case X509_V_ERR_CRL_SIGNATURE_FAILURE:
+ case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
+ case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
+ rc = ErrorSignatureFailed;
+ break;
+ case X509_V_ERR_INVALID_CA:
+ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
+ case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
+ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
+ rc = ErrorInvalidCA;
+ break;
+ case X509_V_ERR_INVALID_PURPOSE: // note: not used by store verify
+ rc = ErrorInvalidPurpose;
+ break;
+ case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
+ case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
+ rc = ErrorSelfSigned;
+ break;
+ case X509_V_ERR_CERT_REVOKED:
+ rc = ErrorRevoked;
+ break;
+ case X509_V_ERR_PATH_LENGTH_EXCEEDED:
+ rc = ErrorPathLengthExceeded;
+ break;
+ case X509_V_ERR_CERT_NOT_YET_VALID:
+ case X509_V_ERR_CERT_HAS_EXPIRED:
+ case X509_V_ERR_CRL_NOT_YET_VALID:
+ case X509_V_ERR_CRL_HAS_EXPIRED:
+ case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
+ case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
+ case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
+ case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
+ rc = ErrorExpired;
+ break;
+ case X509_V_ERR_APPLICATION_VERIFICATION:
+ case X509_V_ERR_OUT_OF_MEM:
+ case X509_V_ERR_UNABLE_TO_GET_CRL:
+ case X509_V_ERR_CERT_CHAIN_TOO_LONG:
+ default:
+ rc = ErrorValidityUnknown;
+ break;
+ }
+ return rc;
}
EVP_PKEY *qca_d2i_PKCS8PrivateKey(const SecureArray &in, EVP_PKEY **x, pem_password_cb *cb, void *u)
{
- PKCS8_PRIV_KEY_INFO *p8inf;
-
- // first try unencrypted form
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(bi, NULL);
- BIO_free(bi);
- if(!p8inf)
- {
- X509_SIG *p8;
-
- // now try encrypted form
- bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- p8 = d2i_PKCS8_bio(bi, NULL);
- BIO_free(bi);
- if(!p8)
- return NULL;
-
- // get passphrase
- char psbuf[PEM_BUFSIZE];
- int klen;
- if(cb)
- klen = cb(psbuf, PEM_BUFSIZE, 0, u);
- else
- klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
- if(klen <= 0)
- {
- PEMerr(PEM_F_D2I_PKCS8PRIVATEKEY_BIO, PEM_R_BAD_PASSWORD_READ);
- X509_SIG_free(p8);
- return NULL;
- }
-
- // decrypt it
- p8inf = PKCS8_decrypt(p8, psbuf, klen);
- X509_SIG_free(p8);
- if(!p8inf)
- return NULL;
- }
-
- EVP_PKEY *ret = EVP_PKCS82PKEY(p8inf);
- PKCS8_PRIV_KEY_INFO_free(p8inf);
- if(!ret)
- return NULL;
- if(x)
- {
- if(*x)
- EVP_PKEY_free(*x);
- *x = ret;
- }
- return ret;
+ PKCS8_PRIV_KEY_INFO *p8inf;
+
+ // first try unencrypted form
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ p8inf = d2i_PKCS8_PRIV_KEY_INFO_bio(bi, NULL);
+ BIO_free(bi);
+ if (!p8inf) {
+ X509_SIG *p8;
+
+ // now try encrypted form
+ bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ p8 = d2i_PKCS8_bio(bi, NULL);
+ BIO_free(bi);
+ if (!p8) {
+ return NULL;
+ }
+
+ // get passphrase
+ char psbuf[PEM_BUFSIZE];
+ int klen;
+ if (cb) {
+ klen = cb(psbuf, PEM_BUFSIZE, 0, u);
+ } else {
+ klen = PEM_def_callback(psbuf, PEM_BUFSIZE, 0, u);
+ }
+ if (klen <= 0) {
+ PEMerr(PEM_F_D2I_PKCS8PRIVATEKEY_BIO, PEM_R_BAD_PASSWORD_READ);
+ X509_SIG_free(p8);
+ return NULL;
+ }
+
+ // decrypt it
+ p8inf = PKCS8_decrypt(p8, psbuf, klen);
+ X509_SIG_free(p8);
+ if (!p8inf) {
+ return NULL;
+ }
+ }
+
+ EVP_PKEY *ret = EVP_PKCS82PKEY(p8inf);
+ PKCS8_PRIV_KEY_INFO_free(p8inf);
+ if (!ret) {
+ return NULL;
+ }
+ if (x) {
+ if (*x) {
+ EVP_PKEY_free(*x);
+ }
+ *x = ret;
+ }
+ return ret;
}
class opensslHashContext : public HashContext
{
public:
- opensslHashContext(const EVP_MD *algorithm, Provider *p, const QString &type) : HashContext(p, type)
- {
- m_algorithm = algorithm;
- m_context = EVP_MD_CTX_new();
- EVP_DigestInit( m_context, m_algorithm );
- }
-
- opensslHashContext(const opensslHashContext &other)
- : HashContext(other)
- {
- m_algorithm = other.m_algorithm;
- m_context = EVP_MD_CTX_new();
- EVP_MD_CTX_copy_ex(m_context, other.m_context);
- }
-
- ~opensslHashContext()
- {
- EVP_MD_CTX_free(m_context);
- }
-
- void clear()
- {
- EVP_MD_CTX_free(m_context);
- m_context = EVP_MD_CTX_new();
- EVP_DigestInit( m_context, m_algorithm );
- }
-
- void update(const MemoryRegion &a)
- {
- EVP_DigestUpdate( m_context, (unsigned char*)a.data(), a.size() );
- }
-
- MemoryRegion final()
- {
- SecureArray a( EVP_MD_size( m_algorithm ) );
- EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 );
- return a;
- }
-
- Provider::Context *clone() const
- {
- return new opensslHashContext(*this);
- }
+ opensslHashContext(const EVP_MD *algorithm, Provider *p, const QString &type) : HashContext(p, type)
+ {
+ m_algorithm = algorithm;
+ m_context = EVP_MD_CTX_new();
+ EVP_DigestInit(m_context, m_algorithm);
+ }
+
+ opensslHashContext(const opensslHashContext &other)
+ : HashContext(other)
+ {
+ m_algorithm = other.m_algorithm;
+ m_context = EVP_MD_CTX_new();
+ EVP_MD_CTX_copy_ex(m_context, other.m_context);
+ }
+
+ ~opensslHashContext()
+ {
+ EVP_MD_CTX_free(m_context);
+ }
+
+ void clear()
+ {
+ EVP_MD_CTX_free(m_context);
+ m_context = EVP_MD_CTX_new();
+ EVP_DigestInit(m_context, m_algorithm);
+ }
+
+ void update(const MemoryRegion &a)
+ {
+ EVP_DigestUpdate(m_context, (unsigned char *)a.data(), a.size());
+ }
+
+ MemoryRegion final()
+ {
+ SecureArray a(EVP_MD_size(m_algorithm));
+ EVP_DigestFinal(m_context, (unsigned char *)a.data(), 0);
+ return a;
+ }
+
+ Provider::Context *clone() const
+ {
+ return new opensslHashContext(*this);
+ }
protected:
- const EVP_MD *m_algorithm;
- EVP_MD_CTX *m_context;
+ const EVP_MD *m_algorithm;
+ EVP_MD_CTX *m_context;
};
-
class opensslPbkdf1Context : public KDFContext
{
public:
- opensslPbkdf1Context(const EVP_MD *algorithm, Provider *p, const QString &type) : KDFContext(p, type)
- {
- m_algorithm = algorithm;
- m_context = EVP_MD_CTX_new();
- EVP_DigestInit( m_context, m_algorithm );
- }
-
- opensslPbkdf1Context(const opensslPbkdf1Context &other)
- : KDFContext(other)
- {
- m_algorithm = other.m_algorithm;
- m_context = EVP_MD_CTX_new();
- EVP_MD_CTX_copy(m_context, other.m_context);
- }
-
- ~opensslPbkdf1Context()
- {
- EVP_MD_CTX_free(m_context);
- }
-
- Provider::Context *clone() const
- {
- return new opensslPbkdf1Context( *this );
- }
-
- SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
- unsigned int keyLength, unsigned int iterationCount)
- {
- /* from RFC2898:
- Steps:
-
- 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
- "derived key too long" and stop.
- */
- if ( keyLength > (unsigned int)EVP_MD_size( m_algorithm ) ) {
- std::cout << "derived key too long" << std::endl;
- return SymmetricKey();
- }
-
- /*
- 2. Apply the underlying hash function Hash for c iterations to the
- concatenation of the password P and the salt S, then extract
- the first dkLen octets to produce a derived key DK:
-
- T_1 = Hash (P || S) ,
- T_2 = Hash (T_1) ,
- ...
- T_c = Hash (T_{c-1}) ,
- DK = Tc<0..dkLen-1>
- */
- // calculate T_1
- EVP_DigestUpdate( m_context, (unsigned char*)secret.data(), secret.size() );
- EVP_DigestUpdate( m_context, (unsigned char*)salt.data(), salt.size() );
- SecureArray a( EVP_MD_size( m_algorithm ) );
- EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 );
-
- // calculate T_2 up to T_c
- for ( unsigned int i = 2; i <= iterationCount; ++i ) {
- EVP_DigestInit( m_context, m_algorithm );
- EVP_DigestUpdate( m_context, (unsigned char*)a.data(), a.size() );
- EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 );
- }
-
- // shrink a to become DK, of the required length
- a.resize(keyLength);
-
- /*
- 3. Output the derived key DK.
- */
- return a;
- }
-
- SymmetricKey makeKey(const SecureArray &secret,
- const InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount)
- {
- Q_ASSERT(iterationCount != NULL);
- QTime timer;
-
- /* from RFC2898:
- Steps:
-
- 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
- "derived key too long" and stop.
- */
- if ( keyLength > (unsigned int)EVP_MD_size( m_algorithm ) ) {
- std::cout << "derived key too long" << std::endl;
- return SymmetricKey();
- }
-
- /*
- 2. Apply the underlying hash function Hash for M milliseconds
- to the concatenation of the password P and the salt S, incrementing c,
- then extract the first dkLen octets to produce a derived key DK:
-
- time from M to 0
- T_1 = Hash (P || S) ,
- T_2 = Hash (T_1) ,
- ...
- T_c = Hash (T_{c-1}) ,
- when time = 0: stop,
- DK = Tc<0..dkLen-1>
- */
- // calculate T_1
- EVP_DigestUpdate( m_context, (unsigned char*)secret.data(), secret.size() );
- EVP_DigestUpdate( m_context, (unsigned char*)salt.data(), salt.size() );
- SecureArray a( EVP_MD_size( m_algorithm ) );
- EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 );
-
- // calculate T_2 up to T_c
- *iterationCount = 2 - 1; // <- Have to remove 1, unless it computes one
- timer.start(); // ^ time more than the base function
- // ^ with the same iterationCount
- while (timer.elapsed() < msecInterval) {
- EVP_DigestInit( m_context, m_algorithm );
- EVP_DigestUpdate( m_context, (unsigned char*)a.data(), a.size() );
- EVP_DigestFinal( m_context, (unsigned char*)a.data(), 0 );
- ++(*iterationCount);
- }
-
- // shrink a to become DK, of the required length
- a.resize(keyLength);
-
- /*
- 3. Output the derived key DK.
- */
- return a;
- }
+ opensslPbkdf1Context(const EVP_MD *algorithm, Provider *p, const QString &type) : KDFContext(p, type)
+ {
+ m_algorithm = algorithm;
+ m_context = EVP_MD_CTX_new();
+ EVP_DigestInit(m_context, m_algorithm);
+ }
+
+ opensslPbkdf1Context(const opensslPbkdf1Context &other)
+ : KDFContext(other)
+ {
+ m_algorithm = other.m_algorithm;
+ m_context = EVP_MD_CTX_new();
+ EVP_MD_CTX_copy(m_context, other.m_context);
+ }
+
+ ~opensslPbkdf1Context()
+ {
+ EVP_MD_CTX_free(m_context);
+ }
+
+ Provider::Context *clone() const
+ {
+ return new opensslPbkdf1Context(*this);
+ }
+
+ SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
+ unsigned int keyLength, unsigned int iterationCount)
+ {
+ /* from RFC2898:
+ Steps:
+
+ 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
+ "derived key too long" and stop.
+ */
+ if (keyLength > (unsigned int)EVP_MD_size(m_algorithm)) {
+ std::cout << "derived key too long" << std::endl;
+ return SymmetricKey();
+ }
+
+ /*
+ 2. Apply the underlying hash function Hash for c iterations to the
+ concatenation of the password P and the salt S, then extract
+ the first dkLen octets to produce a derived key DK:
+
+ T_1 = Hash (P || S) ,
+ T_2 = Hash (T_1) ,
+ ...
+ T_c = Hash (T_{c-1}) ,
+ DK = Tc<0..dkLen-1>
+ */
+ // calculate T_1
+ EVP_DigestUpdate(m_context, (unsigned char *)secret.data(), secret.size());
+ EVP_DigestUpdate(m_context, (unsigned char *)salt.data(), salt.size());
+ SecureArray a(EVP_MD_size(m_algorithm));
+ EVP_DigestFinal(m_context, (unsigned char *)a.data(), 0);
+
+ // calculate T_2 up to T_c
+ for (unsigned int i = 2; i <= iterationCount; ++i) {
+ EVP_DigestInit(m_context, m_algorithm);
+ EVP_DigestUpdate(m_context, (unsigned char *)a.data(), a.size());
+ EVP_DigestFinal(m_context, (unsigned char *)a.data(), 0);
+ }
+
+ // shrink a to become DK, of the required length
+ a.resize(keyLength);
+
+ /*
+ 3. Output the derived key DK.
+ */
+ return a;
+ }
+
+ SymmetricKey makeKey(const SecureArray &secret,
+ const InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount)
+ {
+ Q_ASSERT(iterationCount != NULL);
+ QTime timer;
+
+ /* from RFC2898:
+ Steps:
+
+ 1. If dkLen > 16 for MD2 and MD5, or dkLen > 20 for SHA-1, output
+ "derived key too long" and stop.
+ */
+ if (keyLength > (unsigned int)EVP_MD_size(m_algorithm)) {
+ std::cout << "derived key too long" << std::endl;
+ return SymmetricKey();
+ }
+
+ /*
+ 2. Apply the underlying hash function Hash for M milliseconds
+ to the concatenation of the password P and the salt S, incrementing c,
+ then extract the first dkLen octets to produce a derived key DK:
+
+ time from M to 0
+ T_1 = Hash (P || S) ,
+ T_2 = Hash (T_1) ,
+ ...
+ T_c = Hash (T_{c-1}) ,
+ when time = 0: stop,
+ DK = Tc<0..dkLen-1>
+ */
+ // calculate T_1
+ EVP_DigestUpdate(m_context, (unsigned char *)secret.data(), secret.size());
+ EVP_DigestUpdate(m_context, (unsigned char *)salt.data(), salt.size());
+ SecureArray a(EVP_MD_size(m_algorithm));
+ EVP_DigestFinal(m_context, (unsigned char *)a.data(), 0);
+
+ // calculate T_2 up to T_c
+ *iterationCount = 2 - 1; // <- Have to remove 1, unless it computes one
+ timer.start(); // ^ time more than the base function
+ // ^ with the same iterationCount
+ while (timer.elapsed() < msecInterval) {
+ EVP_DigestInit(m_context, m_algorithm);
+ EVP_DigestUpdate(m_context, (unsigned char *)a.data(), a.size());
+ EVP_DigestFinal(m_context, (unsigned char *)a.data(), 0);
+ ++(*iterationCount);
+ }
+
+ // shrink a to become DK, of the required length
+ a.resize(keyLength);
+
+ /*
+ 3. Output the derived key DK.
+ */
+ return a;
+ }
protected:
- const EVP_MD *m_algorithm;
- EVP_MD_CTX *m_context;
+ const EVP_MD *m_algorithm;
+ EVP_MD_CTX *m_context;
};
class opensslPbkdf2Context : public KDFContext
{
public:
- opensslPbkdf2Context(Provider *p, const QString &type) : KDFContext(p, type)
- {
- }
-
- Provider::Context *clone() const
- {
- return new opensslPbkdf2Context( *this );
- }
-
- SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
- unsigned int keyLength, unsigned int iterationCount)
- {
- SecureArray out(keyLength);
- PKCS5_PBKDF2_HMAC_SHA1( (char*)secret.data(), secret.size(),
- (unsigned char*)salt.data(), salt.size(),
- iterationCount, keyLength, (unsigned char*)out.data() );
- return out;
- }
-
- SymmetricKey makeKey(const SecureArray &secret,
- const InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount)
- {
- Q_ASSERT(iterationCount != NULL);
- QTime timer;
- SecureArray out(keyLength);
-
- *iterationCount = 0;
- timer.start();
-
- // PBKDF2 needs an iterationCount itself, unless PBKDF1.
- // So we need to calculate first the number of iterations for
- // That time interval, then feed the iterationCounts to PBKDF2
- while (timer.elapsed() < msecInterval) {
- PKCS5_PBKDF2_HMAC_SHA1((char*)secret.data(),
- secret.size(),
- (unsigned char*)salt.data(),
- salt.size(),
- 1,
- keyLength,
- (unsigned char*)out.data());
- ++(*iterationCount);
- }
-
- // Now we can directely call makeKey base function,
- // as we now have the iterationCount
- out = makeKey(secret, salt, keyLength, *iterationCount);
-
- return out;
- }
+ opensslPbkdf2Context(Provider *p, const QString &type) : KDFContext(p, type)
+ {
+ }
+
+ Provider::Context *clone() const
+ {
+ return new opensslPbkdf2Context(*this);
+ }
+
+ SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
+ unsigned int keyLength, unsigned int iterationCount)
+ {
+ SecureArray out(keyLength);
+ PKCS5_PBKDF2_HMAC_SHA1((char *)secret.data(), secret.size(),
+ (unsigned char *)salt.data(), salt.size(),
+ iterationCount, keyLength, (unsigned char *)out.data());
+ return out;
+ }
+
+ SymmetricKey makeKey(const SecureArray &secret,
+ const InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount)
+ {
+ Q_ASSERT(iterationCount != NULL);
+ QTime timer;
+ SecureArray out(keyLength);
+
+ *iterationCount = 0;
+ timer.start();
+
+ // PBKDF2 needs an iterationCount itself, unless PBKDF1.
+ // So we need to calculate first the number of iterations for
+ // That time interval, then feed the iterationCounts to PBKDF2
+ while (timer.elapsed() < msecInterval) {
+ PKCS5_PBKDF2_HMAC_SHA1((char *)secret.data(),
+ secret.size(),
+ (unsigned char *)salt.data(),
+ salt.size(),
+ 1,
+ keyLength,
+ (unsigned char *)out.data());
+ ++(*iterationCount);
+ }
+
+ // Now we can directely call makeKey base function,
+ // as we now have the iterationCount
+ out = makeKey(secret, salt, keyLength, *iterationCount);
+
+ return out;
+ }
protected:
};
class opensslHkdfContext : public HKDFContext
{
public:
- opensslHkdfContext(Provider *p, const QString &type) : HKDFContext(p, type)
- {
- }
-
- Provider::Context *clone() const
- {
- return new opensslHkdfContext( *this );
- }
-
- SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
- const InitializationVector &info, unsigned int keyLength)
- {
- SecureArray out(keyLength);
- EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
- EVP_PKEY_derive_init(pctx);
- EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256());
- EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt.data(), int(salt.size()));
- EVP_PKEY_CTX_set1_hkdf_key(pctx, secret.data(), int(secret.size()));
- EVP_PKEY_CTX_add1_hkdf_info(pctx, info.data(), int(info.size()));
- size_t outlen = out.size();
- EVP_PKEY_derive(pctx, reinterpret_cast<unsigned char*>(out.data()), &outlen);
- EVP_PKEY_CTX_free(pctx);
- return out;
- }
+ opensslHkdfContext(Provider *p, const QString &type) : HKDFContext(p, type)
+ {
+ }
+
+ Provider::Context *clone() const
+ {
+ return new opensslHkdfContext(*this);
+ }
+
+ SymmetricKey makeKey(const SecureArray &secret, const InitializationVector &salt,
+ const InitializationVector &info, unsigned int keyLength)
+ {
+ SecureArray out(keyLength);
+ EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
+ EVP_PKEY_derive_init(pctx);
+ EVP_PKEY_CTX_set_hkdf_md(pctx, EVP_sha256());
+ EVP_PKEY_CTX_set1_hkdf_salt(pctx, salt.data(), int(salt.size()));
+ EVP_PKEY_CTX_set1_hkdf_key(pctx, secret.data(), int(secret.size()));
+ EVP_PKEY_CTX_add1_hkdf_info(pctx, info.data(), int(info.size()));
+ size_t outlen = out.size();
+ EVP_PKEY_derive(pctx, reinterpret_cast<unsigned char *>(out.data()), &outlen);
+ EVP_PKEY_CTX_free(pctx);
+ return out;
+ }
};
class opensslHMACContext : public MACContext
{
public:
- opensslHMACContext(const EVP_MD *algorithm, Provider *p, const QString &type) : MACContext(p, type)
- {
- m_algorithm = algorithm;
- m_context = HMAC_CTX_new();
+ opensslHMACContext(const EVP_MD *algorithm, Provider *p, const QString &type) : MACContext(p, type)
+ {
+ m_algorithm = algorithm;
+ m_context = HMAC_CTX_new();
#ifndef OSSL_110
- HMAC_CTX_init( m_context );
+ HMAC_CTX_init(m_context);
#endif
- }
-
- opensslHMACContext(const opensslHMACContext &other)
- : MACContext(other)
- {
- m_algorithm = other.m_algorithm;
- m_context = HMAC_CTX_new();
- HMAC_CTX_copy(m_context, other.m_context);
- }
-
- ~opensslHMACContext()
- {
- HMAC_CTX_free(m_context);
- }
-
- void setup(const SymmetricKey &key)
- {
- HMAC_Init_ex( m_context, key.data(), key.size(), m_algorithm, 0 );
- }
-
- KeyLength keyLength() const
- {
- return anyKeyLength();
- }
-
- void update(const MemoryRegion &a)
- {
- HMAC_Update( m_context, (unsigned char *)a.data(), a.size() );
- }
-
- void final(MemoryRegion *out)
- {
- SecureArray sa( EVP_MD_size( m_algorithm ), 0 );
- HMAC_Final(m_context, (unsigned char *)sa.data(), 0 );
+ }
+
+ opensslHMACContext(const opensslHMACContext &other)
+ : MACContext(other)
+ {
+ m_algorithm = other.m_algorithm;
+ m_context = HMAC_CTX_new();
+ HMAC_CTX_copy(m_context, other.m_context);
+ }
+
+ ~opensslHMACContext()
+ {
+ HMAC_CTX_free(m_context);
+ }
+
+ void setup(const SymmetricKey &key)
+ {
+ HMAC_Init_ex(m_context, key.data(), key.size(), m_algorithm, 0);
+ }
+
+ KeyLength keyLength() const
+ {
+ return anyKeyLength();
+ }
+
+ void update(const MemoryRegion &a)
+ {
+ HMAC_Update(m_context, (unsigned char *)a.data(), a.size());
+ }
+
+ void final(MemoryRegion *out)
+ {
+ SecureArray sa(EVP_MD_size(m_algorithm), 0);
+ HMAC_Final(m_context, (unsigned char *)sa.data(), 0);
#ifdef OSSL_110
- HMAC_CTX_reset(m_context);
+ HMAC_CTX_reset(m_context);
#else
- HMAC_CTX_cleanup(m_context);
+ HMAC_CTX_cleanup(m_context);
#endif
- *out = sa;
- }
+ *out = sa;
+ }
- Provider::Context *clone() const
- {
- return new opensslHMACContext(*this);
- }
+ Provider::Context *clone() const
+ {
+ return new opensslHMACContext(*this);
+ }
protected:
- HMAC_CTX *m_context;
- const EVP_MD *m_algorithm;
+ HMAC_CTX *m_context;
+ const EVP_MD *m_algorithm;
};
//----------------------------------------------------------------------------
// EVPKey
//----------------------------------------------------------------------------
// note: this class squelches processing errors, since QCA doesn't care about them
class EVPKey
{
public:
- enum State { Idle, SignActive, SignError, VerifyActive, VerifyError };
- EVP_PKEY *pkey;
- EVP_MD_CTX *mdctx;
- State state;
- bool raw_type;
- SecureArray raw;
-
- EVPKey()
- {
- pkey = 0;
- raw_type = false;
- state = Idle;
- mdctx = EVP_MD_CTX_new();
- }
-
- EVPKey(const EVPKey &from)
- {
- pkey = from.pkey;
- EVP_PKEY_up_ref(pkey);
- raw_type = false;
- state = Idle;
- mdctx = EVP_MD_CTX_new();
- EVP_MD_CTX_copy(mdctx, from.mdctx);
- }
-
- ~EVPKey()
- {
- reset();
- EVP_MD_CTX_free(mdctx);
- }
-
- void reset()
- {
- if(pkey)
- EVP_PKEY_free(pkey);
- pkey = 0;
- raw.clear ();
- raw_type = false;
- }
-
- void startSign(const EVP_MD *type)
- {
- state = SignActive;
- if(!type)
- {
- raw_type = true;
- raw.clear ();
- }
- else
- {
- raw_type = false;
- EVP_MD_CTX_init(mdctx);
- if(!EVP_SignInit_ex(mdctx, type, NULL))
- state = SignError;
- }
- }
-
- void startVerify(const EVP_MD *type)
- {
- state = VerifyActive;
- if(!type)
- {
- raw_type = true;
- raw.clear ();
- }
- else
- {
- raw_type = false;
- EVP_MD_CTX_init(mdctx);
- if(!EVP_VerifyInit_ex(mdctx, type, NULL))
- state = VerifyError;
- }
- }
-
- void update(const MemoryRegion &in)
- {
- if(state == SignActive)
- {
- if (raw_type)
- raw += in;
- else
- if(!EVP_SignUpdate(mdctx, in.data(), (unsigned int)in.size()))
- state = SignError;
- }
- else if(state == VerifyActive)
- {
- if (raw_type)
- raw += in;
- else
- if(!EVP_VerifyUpdate(mdctx, in.data(), (unsigned int)in.size()))
- state = VerifyError;
- }
- }
-
- SecureArray endSign()
- {
- if(state == SignActive)
- {
- SecureArray out(EVP_PKEY_size(pkey));
- unsigned int len = out.size();
- if (raw_type)
- {
- int type = EVP_PKEY_id(pkey);
-
- if (type == EVP_PKEY_RSA)
- {
- RSA *rsa = EVP_PKEY_get0_RSA(pkey);
- if(RSA_private_encrypt (raw.size(), (unsigned char *)raw.data(),
- (unsigned char *)out.data(), rsa,
- RSA_PKCS1_PADDING) == -1) {
-
- state = SignError;
- return SecureArray ();
- }
- }
- else if (type == EVP_PKEY_DSA)
- {
- state = SignError;
- return SecureArray ();
- }
- else
- {
- state = SignError;
- return SecureArray ();
- }
- }
- else {
- if(!EVP_SignFinal(mdctx, (unsigned char *)out.data(), &len, pkey))
- {
- state = SignError;
- return SecureArray();
- }
- }
- out.resize(len);
- state = Idle;
- return out;
- }
- else
- return SecureArray();
- }
-
- bool endVerify(const SecureArray &sig)
- {
- if(state == VerifyActive)
- {
- if (raw_type)
- {
- SecureArray out(EVP_PKEY_size(pkey));
- int len = 0;
-
- int type = EVP_PKEY_id(pkey);
-
- if (type == EVP_PKEY_RSA) {
- RSA *rsa = EVP_PKEY_get0_RSA(pkey);
- if((len = RSA_public_decrypt (sig.size(), (unsigned char *)sig.data(),
- (unsigned char *)out.data (), rsa,
- RSA_PKCS1_PADDING)) == -1) {
-
- state = VerifyError;
- return false;
- }
- }
- else if (type == EVP_PKEY_DSA)
- {
- state = VerifyError;
- return false;
- }
- else
- {
- state = VerifyError;
- return false;
- }
-
- out.resize (len);
-
- if (out != raw) {
- state = VerifyError;
- return false;
- }
- }
- else
- {
- if(EVP_VerifyFinal(mdctx, (unsigned char *)sig.data(), (unsigned int)sig.size(), pkey) != 1)
- {
- state = VerifyError;
- return false;
- }
- }
- state = Idle;
- return true;
- }
- else
- return false;
- }
+ enum State { Idle, SignActive, SignError, VerifyActive, VerifyError };
+ EVP_PKEY *pkey;
+ EVP_MD_CTX *mdctx;
+ State state;
+ bool raw_type;
+ SecureArray raw;
+
+ EVPKey()
+ {
+ pkey = 0;
+ raw_type = false;
+ state = Idle;
+ mdctx = EVP_MD_CTX_new();
+ }
+
+ EVPKey(const EVPKey &from)
+ {
+ pkey = from.pkey;
+ EVP_PKEY_up_ref(pkey);
+ raw_type = false;
+ state = Idle;
+ mdctx = EVP_MD_CTX_new();
+ EVP_MD_CTX_copy(mdctx, from.mdctx);
+ }
+
+ ~EVPKey()
+ {
+ reset();
+ EVP_MD_CTX_free(mdctx);
+ }
+
+ void reset()
+ {
+ if (pkey) {
+ EVP_PKEY_free(pkey);
+ }
+ pkey = 0;
+ raw.clear();
+ raw_type = false;
+ }
+
+ void startSign(const EVP_MD *type)
+ {
+ state = SignActive;
+ if (!type) {
+ raw_type = true;
+ raw.clear();
+ } else {
+ raw_type = false;
+ EVP_MD_CTX_init(mdctx);
+ if (!EVP_SignInit_ex(mdctx, type, NULL)) {
+ state = SignError;
+ }
+ }
+ }
+
+ void startVerify(const EVP_MD *type)
+ {
+ state = VerifyActive;
+ if (!type) {
+ raw_type = true;
+ raw.clear();
+ } else {
+ raw_type = false;
+ EVP_MD_CTX_init(mdctx);
+ if (!EVP_VerifyInit_ex(mdctx, type, NULL)) {
+ state = VerifyError;
+ }
+ }
+ }
+
+ void update(const MemoryRegion &in)
+ {
+ if (state == SignActive) {
+ if (raw_type) {
+ raw += in;
+ } else if (!EVP_SignUpdate(mdctx, in.data(), (unsigned int)in.size())) {
+ state = SignError;
+ }
+ } else if (state == VerifyActive) {
+ if (raw_type) {
+ raw += in;
+ } else if (!EVP_VerifyUpdate(mdctx, in.data(), (unsigned int)in.size())) {
+ state = VerifyError;
+ }
+ }
+ }
+
+ SecureArray endSign()
+ {
+ if (state == SignActive) {
+ SecureArray out(EVP_PKEY_size(pkey));
+ unsigned int len = out.size();
+ if (raw_type) {
+ int type = EVP_PKEY_id(pkey);
+
+ if (type == EVP_PKEY_RSA) {
+ RSA *rsa = EVP_PKEY_get0_RSA(pkey);
+ if (RSA_private_encrypt(raw.size(), (unsigned char *)raw.data(),
+ (unsigned char *)out.data(), rsa,
+ RSA_PKCS1_PADDING) == -1) {
+
+ state = SignError;
+ return SecureArray();
+ }
+ } else if (type == EVP_PKEY_DSA) {
+ state = SignError;
+ return SecureArray();
+ } else {
+ state = SignError;
+ return SecureArray();
+ }
+ } else {
+ if (!EVP_SignFinal(mdctx, (unsigned char *)out.data(), &len, pkey)) {
+ state = SignError;
+ return SecureArray();
+ }
+ }
+ out.resize(len);
+ state = Idle;
+ return out;
+ } else {
+ return SecureArray();
+ }
+ }
+
+ bool endVerify(const SecureArray &sig)
+ {
+ if (state == VerifyActive) {
+ if (raw_type) {
+ SecureArray out(EVP_PKEY_size(pkey));
+ int len = 0;
+
+ int type = EVP_PKEY_id(pkey);
+
+ if (type == EVP_PKEY_RSA) {
+ RSA *rsa = EVP_PKEY_get0_RSA(pkey);
+ if ((len = RSA_public_decrypt(sig.size(), (unsigned char *)sig.data(),
+ (unsigned char *)out.data(), rsa,
+ RSA_PKCS1_PADDING)) == -1) {
+
+ state = VerifyError;
+ return false;
+ }
+ } else if (type == EVP_PKEY_DSA) {
+ state = VerifyError;
+ return false;
+ } else {
+ state = VerifyError;
+ return false;
+ }
+
+ out.resize(len);
+
+ if (out != raw) {
+ state = VerifyError;
+ return false;
+ }
+ } else {
+ if (EVP_VerifyFinal(mdctx, (unsigned char *)sig.data(), (unsigned int)sig.size(), pkey) != 1) {
+ state = VerifyError;
+ return false;
+ }
+ }
+ state = Idle;
+ return true;
+ } else {
+ return false;
+ }
+ }
};
//----------------------------------------------------------------------------
// MyDLGroup
//----------------------------------------------------------------------------
// IETF primes from Botan
-const char* IETF_1024_PRIME =
- "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1"
- "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD"
- "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245"
- "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED"
- "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381"
- "FFFFFFFF FFFFFFFF";
-
-const char* IETF_2048_PRIME =
- "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1"
- "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD"
- "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245"
- "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED"
- "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D"
- "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F"
- "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D"
- "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B"
- "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9"
- "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510"
- "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF";
-
-const char* IETF_4096_PRIME =
- "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1"
- "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD"
- "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245"
- "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED"
- "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D"
- "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F"
- "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D"
- "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B"
- "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9"
- "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510"
- "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64"
- "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7"
- "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B"
- "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C"
- "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31"
- "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7"
- "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA"
- "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6"
- "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED"
- "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9"
- "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34063199"
- "FFFFFFFF FFFFFFFF";
+const char *IETF_1024_PRIME =
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1"
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD"
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245"
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED"
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381"
+ "FFFFFFFF FFFFFFFF";
+
+const char *IETF_2048_PRIME =
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1"
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD"
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245"
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED"
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D"
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F"
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D"
+ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B"
+ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9"
+ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510"
+ "15728E5A 8AACAA68 FFFFFFFF FFFFFFFF";
+
+const char *IETF_4096_PRIME =
+ "FFFFFFFF FFFFFFFF C90FDAA2 2168C234 C4C6628B 80DC1CD1"
+ "29024E08 8A67CC74 020BBEA6 3B139B22 514A0879 8E3404DD"
+ "EF9519B3 CD3A431B 302B0A6D F25F1437 4FE1356D 6D51C245"
+ "E485B576 625E7EC6 F44C42E9 A637ED6B 0BFF5CB6 F406B7ED"
+ "EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE45B3D"
+ "C2007CB8 A163BF05 98DA4836 1C55D39A 69163FA8 FD24CF5F"
+ "83655D23 DCA3AD96 1C62F356 208552BB 9ED52907 7096966D"
+ "670C354E 4ABC9804 F1746C08 CA18217C 32905E46 2E36CE3B"
+ "E39E772C 180E8603 9B2783A2 EC07A28F B5C55DF0 6F4C52C9"
+ "DE2BCBF6 95581718 3995497C EA956AE5 15D22618 98FA0510"
+ "15728E5A 8AAAC42D AD33170D 04507A33 A85521AB DF1CBA64"
+ "ECFB8504 58DBEF0A 8AEA7157 5D060C7D B3970F85 A6E1E4C7"
+ "ABF5AE8C DB0933D7 1E8C94E0 4A25619D CEE3D226 1AD2EE6B"
+ "F12FFA06 D98A0864 D8760273 3EC86A64 521F2B18 177B200C"
+ "BBE11757 7A615D6C 770988C0 BAD946E2 08E24FA0 74E5AB31"
+ "43DB5BFC E0FD108E 4B82D120 A9210801 1A723C12 A787E6D7"
+ "88719A10 BDBA5B26 99C32718 6AF4E23C 1A946834 B6150BDA"
+ "2583E9CA 2AD44CE8 DBBBC2DB 04DE8EF9 2E8EFC14 1FBECAA6"
+ "287C5947 4E6BC05D 99B2964F A090C3A2 233BA186 515BE7ED"
+ "1F612970 CEE2D7AF B81BDD76 2170481C D0069127 D5B05AA9"
+ "93B4EA98 8D8FDDC1 86FFB7DC 90A6C08F 4DF435C9 34063199"
+ "FFFFFFFF FFFFFFFF";
// JCE seeds from Botan
-const char* JCE_512_SEED = "B869C82B 35D70E1B 1FF91B28 E37A62EC DC34409B";
+const char *JCE_512_SEED = "B869C82B 35D70E1B 1FF91B28 E37A62EC DC34409B";
const int JCE_512_COUNTER = 123;
-const char* JCE_768_SEED = "77D0F8C4 DAD15EB8 C4F2F8D6 726CEFD9 6D5BB399";
+const char *JCE_768_SEED = "77D0F8C4 DAD15EB8 C4F2F8D6 726CEFD9 6D5BB399";
const int JCE_768_COUNTER = 263;
-const char* JCE_1024_SEED = "8D515589 4229D5E6 89EE01E6 018A237E 2CAE64CD";
+const char *JCE_1024_SEED = "8D515589 4229D5E6 89EE01E6 018A237E 2CAE64CD";
const int JCE_1024_COUNTER = 92;
static QByteArray dehex(const QString &hex)
{
- QString str;
- for(int n = 0; n < hex.length(); ++n)
- {
- if(hex[n] != ' ')
- str += hex[n];
- }
- return hexToArray(str);
+ QString str;
+ for (int n = 0; n < hex.length(); ++n) {
+ if (hex[n] != ' ') {
+ str += hex[n];
+ }
+ }
+ return hexToArray(str);
}
static BigInteger decode(const QString &prime)
{
- QByteArray a(1, 0); // 1 byte of zero padding
- a.append(dehex(prime));
- return BigInteger(SecureArray(a));
+ QByteArray a(1, 0); // 1 byte of zero padding
+ a.append(dehex(prime));
+ return BigInteger(SecureArray(a));
}
#ifndef OPENSSL_FIPS
static QByteArray decode_seed(const QString &hex_seed)
{
- return dehex(hex_seed);
+ return dehex(hex_seed);
}
#endif
class DLParams
{
public:
- BigInteger p, q, g;
+ BigInteger p, q, g;
};
#ifndef OPENSSL_FIPS
-namespace {
-struct DsaDeleter
+namespace
{
- static inline void cleanup(void *pointer)
- {
- if (pointer)
- DSA_free((DSA *)pointer);
- }
+struct DsaDeleter {
+ static inline void cleanup(void *pointer)
+ {
+ if (pointer) {
+ DSA_free((DSA *)pointer);
+ }
+ }
};
} // end of anonymous namespace
static bool make_dlgroup(const QByteArray &seed, int bits, int counter, DLParams *params)
{
- int ret_counter;
- QScopedPointer<DSA, DsaDeleter> dsa(DSA_new());
- if(!dsa)
- return false;
+ int ret_counter;
+ QScopedPointer<DSA, DsaDeleter> dsa(DSA_new());
+ if (!dsa) {
+ return false;
+ }
- if (DSA_generate_parameters_ex(dsa.data(), bits, (const unsigned char *)seed.data(), seed.size(),
- &ret_counter, NULL, NULL) != 1)
- return false;
+ if (DSA_generate_parameters_ex(dsa.data(), bits, (const unsigned char *)seed.data(), seed.size(),
+ &ret_counter, NULL, NULL) != 1) {
+ return false;
+ }
- if(ret_counter != counter)
- return false;
+ if (ret_counter != counter) {
+ return false;
+ }
- const BIGNUM *bnp, *bnq, *bng;
- DSA_get0_pqg(dsa.data(), &bnp, &bnq, &bng);
- params->p = bn2bi(bnp);
- params->q = bn2bi(bnq);
- params->g = bn2bi(bng);
+ const BIGNUM *bnp, *bnq, *bng;
+ DSA_get0_pqg(dsa.data(), &bnp, &bnq, &bng);
+ params->p = bn2bi(bnp);
+ params->q = bn2bi(bnq);
+ params->g = bn2bi(bng);
- return true;
+ return true;
}
#endif
static bool get_dlgroup(const BigInteger &p, const BigInteger &g, DLParams *params)
{
- params->p = p;
- params->q = BigInteger(0);
- params->g = g;
- return true;
+ params->p = p;
+ params->q = BigInteger(0);
+ params->g = g;
+ return true;
}
class DLGroupMaker : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- DLGroupSet set;
- bool ok;
- DLParams params;
-
- DLGroupMaker(DLGroupSet _set)
- {
- set = _set;
- }
-
- ~DLGroupMaker()
- {
- wait();
- }
-
- virtual void run()
- {
- switch (set)
- {
+ DLGroupSet set;
+ bool ok;
+ DLParams params;
+
+ DLGroupMaker(DLGroupSet _set)
+ {
+ set = _set;
+ }
+
+ ~DLGroupMaker()
+ {
+ wait();
+ }
+
+ virtual void run()
+ {
+ switch (set) {
#ifndef OPENSSL_FIPS
- case DSA_512:
- ok = make_dlgroup(decode_seed(JCE_512_SEED), 512, JCE_512_COUNTER, &params);
- break;
+ case DSA_512:
+ ok = make_dlgroup(decode_seed(JCE_512_SEED), 512, JCE_512_COUNTER, &params);
+ break;
- case DSA_768:
- ok = make_dlgroup(decode_seed(JCE_768_SEED), 768, JCE_768_COUNTER, &params);
- break;
+ case DSA_768:
+ ok = make_dlgroup(decode_seed(JCE_768_SEED), 768, JCE_768_COUNTER, &params);
+ break;
- case DSA_1024:
- ok = make_dlgroup(decode_seed(JCE_1024_SEED), 1024, JCE_1024_COUNTER, &params);
- break;
+ case DSA_1024:
+ ok = make_dlgroup(decode_seed(JCE_1024_SEED), 1024, JCE_1024_COUNTER, &params);
+ break;
#endif
- case IETF_1024:
- ok = get_dlgroup(decode(IETF_1024_PRIME), 2, &params);
- break;
+ case IETF_1024:
+ ok = get_dlgroup(decode(IETF_1024_PRIME), 2, &params);
+ break;
- case IETF_2048:
- ok = get_dlgroup(decode(IETF_2048_PRIME), 2, &params);
- break;
+ case IETF_2048:
+ ok = get_dlgroup(decode(IETF_2048_PRIME), 2, &params);
+ break;
- case IETF_4096:
- ok = get_dlgroup(decode(IETF_4096_PRIME), 2, &params);
- break;
+ case IETF_4096:
+ ok = get_dlgroup(decode(IETF_4096_PRIME), 2, &params);
+ break;
- default:
- ok = false;
- break;
- }
- }
+ default:
+ ok = false;
+ break;
+ }
+ }
};
class MyDLGroup : public DLGroupContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- DLGroupMaker *gm;
- bool wasBlocking;
- DLParams params;
- bool empty;
-
- MyDLGroup(Provider *p) : DLGroupContext(p)
- {
- gm = 0;
- empty = true;
- }
-
- MyDLGroup(const MyDLGroup &from) : DLGroupContext(from.provider())
- {
- gm = 0;
- empty = true;
- }
-
- ~MyDLGroup()
- {
- delete gm;
- }
-
- virtual Provider::Context *clone() const
- {
- return new MyDLGroup(*this);
- }
-
- virtual QList<DLGroupSet> supportedGroupSets() const
- {
- QList<DLGroupSet> list;
-
- // DSA_* was removed in FIPS specification
- // https://bugzilla.redhat.com/show_bug.cgi?id=1144655
+ DLGroupMaker *gm;
+ bool wasBlocking;
+ DLParams params;
+ bool empty;
+
+ MyDLGroup(Provider *p) : DLGroupContext(p)
+ {
+ gm = 0;
+ empty = true;
+ }
+
+ MyDLGroup(const MyDLGroup &from) : DLGroupContext(from.provider())
+ {
+ gm = 0;
+ empty = true;
+ }
+
+ ~MyDLGroup()
+ {
+ delete gm;
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new MyDLGroup(*this);
+ }
+
+ virtual QList<DLGroupSet> supportedGroupSets() const
+ {
+ QList<DLGroupSet> list;
+
+ // DSA_* was removed in FIPS specification
+ // https://bugzilla.redhat.com/show_bug.cgi?id=1144655
#ifndef OPENSSL_FIPS
- list += DSA_512;
- list += DSA_768;
- list += DSA_1024;
+ list += DSA_512;
+ list += DSA_768;
+ list += DSA_1024;
#endif
- list += IETF_1024;
- list += IETF_2048;
- list += IETF_4096;
- return list;
- }
-
- virtual bool isNull() const
- {
- return empty;
- }
-
- virtual void fetchGroup(DLGroupSet set, bool block)
- {
- params = DLParams();
- empty = true;
-
- gm = new DLGroupMaker(set);
- wasBlocking = block;
- if(block)
- {
- gm->run();
- gm_finished();
- }
- else
- {
- connect(gm, SIGNAL(finished()), SLOT(gm_finished()));
- gm->start();
- }
- }
-
- virtual void getResult(BigInteger *p, BigInteger *q, BigInteger *g) const
- {
- *p = params.p;
- *q = params.q;
- *g = params.g;
- }
+ list += IETF_1024;
+ list += IETF_2048;
+ list += IETF_4096;
+ return list;
+ }
+
+ virtual bool isNull() const
+ {
+ return empty;
+ }
+
+ virtual void fetchGroup(DLGroupSet set, bool block)
+ {
+ params = DLParams();
+ empty = true;
+
+ gm = new DLGroupMaker(set);
+ wasBlocking = block;
+ if (block) {
+ gm->run();
+ gm_finished();
+ } else {
+ connect(gm, SIGNAL(finished()), SLOT(gm_finished()));
+ gm->start();
+ }
+ }
+
+ virtual void getResult(BigInteger *p, BigInteger *q, BigInteger *g) const
+ {
+ *p = params.p;
+ *q = params.q;
+ *g = params.g;
+ }
private slots:
- void gm_finished()
- {
- bool ok = gm->ok;
- if(ok)
- {
- params = gm->params;
- empty = false;
- }
-
- if(wasBlocking)
- delete gm;
- else
- gm->deleteLater();
- gm = 0;
-
- if(!wasBlocking)
- emit finished();
- }
+ void gm_finished()
+ {
+ bool ok = gm->ok;
+ if (ok) {
+ params = gm->params;
+ empty = false;
+ }
+
+ if (wasBlocking) {
+ delete gm;
+ } else {
+ gm->deleteLater();
+ }
+ gm = 0;
+
+ if (!wasBlocking) {
+ emit finished();
+ }
+ }
};
//----------------------------------------------------------------------------
// RSAKey
//----------------------------------------------------------------------------
-namespace {
-struct RsaDeleter
+namespace
{
- static inline void cleanup(void *pointer)
- {
- if (pointer)
- RSA_free((RSA *)pointer);
- }
+struct RsaDeleter {
+ static inline void cleanup(void *pointer)
+ {
+ if (pointer) {
+ RSA_free((RSA *)pointer);
+ }
+ }
};
-struct BnDeleter
-{
- static inline void cleanup(void *pointer)
- {
- if (pointer)
- BN_free((BIGNUM *)pointer);
- }
+struct BnDeleter {
+ static inline void cleanup(void *pointer)
+ {
+ if (pointer) {
+ BN_free((BIGNUM *)pointer);
+ }
+ }
};
} // end of anonymous namespace
class RSAKeyMaker : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- RSA *result;
- int bits, exp;
-
- RSAKeyMaker(int _bits, int _exp, QObject *parent = 0) : QThread(parent), result(0), bits(_bits), exp(_exp)
- {
- }
-
- ~RSAKeyMaker()
- {
- wait();
- if(result)
- RSA_free(result);
- }
-
- virtual void run()
- {
- QScopedPointer<RSA, RsaDeleter> rsa(RSA_new());
- if(!rsa)
- return;
-
- QScopedPointer<BIGNUM, BnDeleter> e(BN_new());
- if(!e)
- return;
-
- BN_clear(e.data());
- if (BN_set_word(e.data(), exp) != 1)
- return;
-
- if (RSA_generate_key_ex(rsa.data(), bits, e.data(), NULL) == 0)
- return;
-
- result = rsa.take();
- }
-
- RSA *takeResult()
- {
- RSA *rsa = result;
- result = 0;
- return rsa;
- }
-};
+ RSA *result;
+ int bits, exp;
-class RSAKey : public RSAContext
-{
- Q_OBJECT
-public:
- EVPKey evp;
- RSAKeyMaker *keymaker;
- bool wasBlocking;
- bool sec;
-
- RSAKey(Provider *p) : RSAContext(p)
- {
- keymaker = 0;
- sec = false;
- }
-
- RSAKey(const RSAKey &from) : RSAContext(from.provider()), evp(from.evp)
- {
- keymaker = 0;
- sec = from.sec;
- }
-
- ~RSAKey()
- {
- delete keymaker;
- }
-
- virtual Provider::Context *clone() const
- {
- return new RSAKey(*this);
- }
-
- virtual bool isNull() const
- {
- return (evp.pkey ? false: true);
- }
-
- virtual PKey::Type type() const
- {
- return PKey::RSA;
- }
-
- virtual bool isPrivate() const
- {
- return sec;
- }
-
- virtual bool canExport() const
- {
- return true;
- }
-
- virtual void convertToPublic()
- {
- if(!sec)
- return;
-
- // extract the public key into DER format
- RSA *rsa_pkey = EVP_PKEY_get0_RSA(evp.pkey);
- int len = i2d_RSAPublicKey(rsa_pkey, NULL);
- SecureArray result(len);
- unsigned char *p = (unsigned char *)result.data();
- i2d_RSAPublicKey(rsa_pkey, &p);
- p = (unsigned char *)result.data();
-
- // put the DER public key back into openssl
- evp.reset();
- RSA *rsa;
-#ifdef OSSL_097
- rsa = d2i_RSAPublicKey(NULL, (const unsigned char **)&p, result.size());
-#else
- rsa = d2i_RSAPublicKey(NULL, (unsigned char **)&p, result.size());
-#endif
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_RSA(evp.pkey, rsa);
- sec = false;
- }
-
- virtual int bits() const
- {
- return EVP_PKEY_bits(evp.pkey);
- }
-
- virtual int maximumEncryptSize(EncryptionAlgorithm alg) const
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- int size = 0;
- switch(alg)
- {
- case EME_PKCS1v15: size = RSA_size(rsa) - 11 - 1; break;
- case EME_PKCS1_OAEP: size = RSA_size(rsa) - 41 - 1; break;
- case EME_PKCS1v15_SSL: size = RSA_size(rsa) - 11 - 1; break;
- case EME_NO_PADDING: size = RSA_size(rsa) - 1; break;
- }
-
- return size;
- }
-
- virtual SecureArray encrypt(const SecureArray &in, EncryptionAlgorithm alg)
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- SecureArray buf = in;
- int max = maximumEncryptSize(alg);
-
- if(buf.size() > max)
- buf.resize(max);
- SecureArray result(RSA_size(rsa));
-
- int pad;
- switch(alg)
- {
- case EME_PKCS1v15: pad = RSA_PKCS1_PADDING; break;
- case EME_PKCS1_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break;
- case EME_PKCS1v15_SSL: pad = RSA_SSLV23_PADDING; break;
- case EME_NO_PADDING: pad = RSA_NO_PADDING; break;
- default: return SecureArray(); break;
- }
-
- int ret;
- if (isPrivate())
- ret = RSA_private_encrypt(buf.size(), (unsigned char *)buf.data(), (unsigned char *)result.data(), rsa, pad);
- else
- ret = RSA_public_encrypt(buf.size(), (unsigned char *)buf.data(), (unsigned char *)result.data(), rsa, pad);
-
- if(ret < 0)
- return SecureArray();
- result.resize(ret);
-
- return result;
- }
-
- virtual bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg)
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- SecureArray result(RSA_size(rsa));
- int pad;
-
- switch(alg)
- {
- case EME_PKCS1v15: pad = RSA_PKCS1_PADDING; break;
- case EME_PKCS1_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break;
- case EME_PKCS1v15_SSL: pad = RSA_SSLV23_PADDING; break;
- case EME_NO_PADDING: pad = RSA_NO_PADDING; break;
- default: return false; break;
- }
-
- int ret;
- if (isPrivate())
- ret = RSA_private_decrypt(in.size(), (unsigned char *)in.data(), (unsigned char *)result.data(), rsa, pad);
- else
- ret = RSA_public_decrypt(in.size(), (unsigned char *)in.data(), (unsigned char *)result.data(), rsa, pad);
-
- if(ret < 0)
- return false;
- result.resize(ret);
-
- *out = result;
- return true;
- }
-
- virtual void startSign(SignatureAlgorithm alg, SignatureFormat)
- {
- const EVP_MD *md = 0;
- if(alg == EMSA3_SHA1)
- md = EVP_sha1();
- else if(alg == EMSA3_MD5)
- md = EVP_md5();
-#ifdef HAVE_OPENSSL_MD2
- else if(alg == EMSA3_MD2)
- md = EVP_md2();
-#endif
- else if(alg == EMSA3_RIPEMD160)
- md = EVP_ripemd160();
- else if(alg == EMSA3_SHA224)
- md = EVP_sha224();
- else if(alg == EMSA3_SHA256)
- md = EVP_sha256();
- else if(alg == EMSA3_SHA384)
- md = EVP_sha384();
- else if(alg == EMSA3_SHA512)
- md = EVP_sha512();
- else if(alg == EMSA3_Raw)
- {
- // md = 0
- }
- evp.startSign(md);
- }
-
- virtual void startVerify(SignatureAlgorithm alg, SignatureFormat)
- {
- const EVP_MD *md = 0;
- if(alg == EMSA3_SHA1)
- md = EVP_sha1();
- else if(alg == EMSA3_MD5)
- md = EVP_md5();
-#ifdef HAVE_OPENSSL_MD2
- else if(alg == EMSA3_MD2)
- md = EVP_md2();
-#endif
- else if(alg == EMSA3_RIPEMD160)
- md = EVP_ripemd160();
- else if(alg == EMSA3_SHA224)
- md = EVP_sha224();
- else if(alg == EMSA3_SHA256)
- md = EVP_sha256();
- else if(alg == EMSA3_SHA384)
- md = EVP_sha384();
- else if(alg == EMSA3_SHA512)
- md = EVP_sha512();
- else if(alg == EMSA3_Raw)
- {
- // md = 0
- }
- evp.startVerify(md);
- }
-
- virtual void update(const MemoryRegion &in)
- {
- evp.update(in);
- }
-
- virtual QByteArray endSign()
- {
- return evp.endSign().toByteArray();
- }
-
- virtual bool endVerify(const QByteArray &sig)
- {
- return evp.endVerify(sig);
- }
-
- virtual void createPrivate(int bits, int exp, bool block)
- {
- evp.reset();
-
- keymaker = new RSAKeyMaker(bits, exp, !block ? this : 0);
- wasBlocking = block;
- if(block)
- {
- keymaker->run();
- km_finished();
- }
- else
- {
- connect(keymaker, SIGNAL(finished()), SLOT(km_finished()));
- keymaker->start();
- }
- }
-
- virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d)
- {
- evp.reset();
-
- RSA *rsa = RSA_new();
- if(RSA_set0_key(rsa, bi2bn(n), bi2bn(e), bi2bn(d)) == 0
- || RSA_set0_factors(rsa, bi2bn(p), bi2bn(q)) == 0)
- {
- // Free BIGNUMS?
- RSA_free(rsa);
- return;
- }
-
- // When private key has no Public Exponent (e) or Private Exponent (d)
- // need to disable blinding. Otherwise decryption will be broken.
- // http://www.mail-archive.com/openssl-users@openssl.org/msg63530.html
- if(e == BigInteger(0) || d == BigInteger(0))
- RSA_blinding_off(rsa);
-
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_RSA(evp.pkey, rsa);
- sec = true;
- }
-
- virtual void createPublic(const BigInteger &n, const BigInteger &e)
- {
- evp.reset();
-
- RSA *rsa = RSA_new();
- if(RSA_set0_key(rsa, bi2bn(n), bi2bn(e), NULL) == 0)
- {
- RSA_free(rsa);
- return;
- }
-
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_RSA(evp.pkey, rsa);
- sec = false;
- }
-
- virtual BigInteger n() const
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- const BIGNUM *bnn;
- RSA_get0_key(rsa, &bnn, NULL, NULL);
- return bn2bi(bnn);
- }
-
- virtual BigInteger e() const
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- const BIGNUM *bne;
- RSA_get0_key(rsa, NULL, &bne, NULL);
- return bn2bi(bne);
- }
-
- virtual BigInteger p() const
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- const BIGNUM *bnp;
- RSA_get0_factors(rsa, &bnp, NULL);
- return bn2bi(bnp);
- }
-
- virtual BigInteger q() const
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- const BIGNUM *bnq;
- RSA_get0_factors(rsa, NULL, &bnq);
- return bn2bi(bnq);
- }
-
- virtual BigInteger d() const
- {
- RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
- const BIGNUM *bnd;
- RSA_get0_key(rsa, NULL, NULL, &bnd);
- return bn2bi(bnd);
- }
+ RSAKeyMaker(int _bits, int _exp, QObject *parent = 0) : QThread(parent), result(0), bits(_bits), exp(_exp)
+ {
+ }
-private slots:
- void km_finished()
- {
- RSA *rsa = keymaker->takeResult();
- if(wasBlocking)
- delete keymaker;
- else
- keymaker->deleteLater();
- keymaker = 0;
-
- if(rsa)
- {
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_RSA(evp.pkey, rsa);
- sec = true;
- }
-
- if(!wasBlocking)
- emit finished();
- }
+ ~RSAKeyMaker()
+ {
+ wait();
+ if (result) {
+ RSA_free(result);
+ }
+ }
+
+ virtual void run()
+ {
+ QScopedPointer<RSA, RsaDeleter> rsa(RSA_new());
+ if (!rsa) {
+ return;
+ }
+
+ QScopedPointer<BIGNUM, BnDeleter> e(BN_new());
+ if (!e) {
+ return;
+ }
+
+ BN_clear(e.data());
+ if (BN_set_word(e.data(), exp) != 1) {
+ return;
+ }
+
+ if (RSA_generate_key_ex(rsa.data(), bits, e.data(), NULL) == 0) {
+ return;
+ }
+
+ result = rsa.take();
+ }
+
+ RSA *takeResult()
+ {
+ RSA *rsa = result;
+ result = 0;
+ return rsa;
+ }
};
-//----------------------------------------------------------------------------
-// DSAKey
-//----------------------------------------------------------------------------
-class DSAKeyMaker : public QThread
+class RSAKey : public RSAContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- DLGroup domain;
- DSA *result;
-
- DSAKeyMaker(const DLGroup &_domain, QObject *parent = 0) : QThread(parent), domain(_domain), result(0)
- {
- }
-
- ~DSAKeyMaker()
- {
- wait();
- if(result)
- DSA_free(result);
- }
-
- virtual void run()
- {
- DSA *dsa = DSA_new();
- BIGNUM *pne = bi2bn(domain.p()),
- *qne = bi2bn(domain.q()),
- *gne = bi2bn(domain.g());
-
- if(!DSA_set0_pqg(dsa, pne, qne, gne)
- || !DSA_generate_key(dsa))
- {
- DSA_free(dsa);
- return;
- }
- result = dsa;
- }
-
- DSA *takeResult()
- {
- DSA *dsa = result;
- result = 0;
- return dsa;
- }
-};
+ EVPKey evp;
+ RSAKeyMaker *keymaker;
+ bool wasBlocking;
+ bool sec;
-// note: DSA doesn't use SignatureAlgorithm, since EMSA1 is always assumed
-class DSAKey : public DSAContext
-{
- Q_OBJECT
-public:
- EVPKey evp;
- DSAKeyMaker *keymaker;
- bool wasBlocking;
- bool transformsig;
- bool sec;
-
- DSAKey(Provider *p) : DSAContext(p)
- {
- keymaker = 0;
- sec = false;
- }
-
- DSAKey(const DSAKey &from) : DSAContext(from.provider()), evp(from.evp)
- {
- keymaker = 0;
- sec = from.sec;
- }
-
- ~DSAKey()
- {
- delete keymaker;
- }
-
- virtual Provider::Context *clone() const
- {
- return new DSAKey(*this);
- }
-
- virtual bool isNull() const
- {
- return (evp.pkey ? false: true);
- }
-
- virtual PKey::Type type() const
- {
- return PKey::DSA;
- }
-
- virtual bool isPrivate() const
- {
- return sec;
- }
-
- virtual bool canExport() const
- {
- return true;
- }
-
- virtual void convertToPublic()
- {
- if(!sec)
- return;
-
- // extract the public key into DER format
- DSA *dsa_pkey = EVP_PKEY_get0_DSA(evp.pkey);
- int len = i2d_DSAPublicKey(dsa_pkey, NULL);
- SecureArray result(len);
- unsigned char *p = (unsigned char *)result.data();
- i2d_DSAPublicKey(dsa_pkey, &p);
- p = (unsigned char *)result.data();
-
- // put the DER public key back into openssl
- evp.reset();
- DSA *dsa;
+ RSAKey(Provider *p) : RSAContext(p)
+ {
+ keymaker = 0;
+ sec = false;
+ }
+
+ RSAKey(const RSAKey &from) : RSAContext(from.provider()), evp(from.evp)
+ {
+ keymaker = 0;
+ sec = from.sec;
+ }
+
+ ~RSAKey()
+ {
+ delete keymaker;
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new RSAKey(*this);
+ }
+
+ virtual bool isNull() const
+ {
+ return (evp.pkey ? false : true);
+ }
+
+ virtual PKey::Type type() const
+ {
+ return PKey::RSA;
+ }
+
+ virtual bool isPrivate() const
+ {
+ return sec;
+ }
+
+ virtual bool canExport() const
+ {
+ return true;
+ }
+
+ virtual void convertToPublic()
+ {
+ if (!sec) {
+ return;
+ }
+
+ // extract the public key into DER format
+ RSA *rsa_pkey = EVP_PKEY_get0_RSA(evp.pkey);
+ int len = i2d_RSAPublicKey(rsa_pkey, NULL);
+ SecureArray result(len);
+ unsigned char *p = (unsigned char *)result.data();
+ i2d_RSAPublicKey(rsa_pkey, &p);
+ p = (unsigned char *)result.data();
+
+ // put the DER public key back into openssl
+ evp.reset();
+ RSA *rsa;
#ifdef OSSL_097
- dsa = d2i_DSAPublicKey(NULL, (const unsigned char **)&p, result.size());
+ rsa = d2i_RSAPublicKey(NULL, (const unsigned char **)&p, result.size());
#else
- dsa = d2i_DSAPublicKey(NULL, (unsigned char **)&p, result.size());
+ rsa = d2i_RSAPublicKey(NULL, (unsigned char **)&p, result.size());
+#endif
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_RSA(evp.pkey, rsa);
+ sec = false;
+ }
+
+ virtual int bits() const
+ {
+ return EVP_PKEY_bits(evp.pkey);
+ }
+
+ virtual int maximumEncryptSize(EncryptionAlgorithm alg) const
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ int size = 0;
+ switch (alg) {
+ case EME_PKCS1v15: size = RSA_size(rsa) - 11 - 1; break;
+ case EME_PKCS1_OAEP: size = RSA_size(rsa) - 41 - 1; break;
+ case EME_PKCS1v15_SSL: size = RSA_size(rsa) - 11 - 1; break;
+ case EME_NO_PADDING: size = RSA_size(rsa) - 1; break;
+ }
+
+ return size;
+ }
+
+ virtual SecureArray encrypt(const SecureArray &in, EncryptionAlgorithm alg)
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ SecureArray buf = in;
+ int max = maximumEncryptSize(alg);
+
+ if (buf.size() > max) {
+ buf.resize(max);
+ }
+ SecureArray result(RSA_size(rsa));
+
+ int pad;
+ switch (alg) {
+ case EME_PKCS1v15: pad = RSA_PKCS1_PADDING; break;
+ case EME_PKCS1_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break;
+ case EME_PKCS1v15_SSL: pad = RSA_SSLV23_PADDING; break;
+ case EME_NO_PADDING: pad = RSA_NO_PADDING; break;
+ default: return SecureArray(); break;
+ }
+
+ int ret;
+ if (isPrivate()) {
+ ret = RSA_private_encrypt(buf.size(), (unsigned char *)buf.data(), (unsigned char *)result.data(), rsa, pad);
+ } else {
+ ret = RSA_public_encrypt(buf.size(), (unsigned char *)buf.data(), (unsigned char *)result.data(), rsa, pad);
+ }
+
+ if (ret < 0) {
+ return SecureArray();
+ }
+ result.resize(ret);
+
+ return result;
+ }
+
+ virtual bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg)
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ SecureArray result(RSA_size(rsa));
+ int pad;
+
+ switch (alg) {
+ case EME_PKCS1v15: pad = RSA_PKCS1_PADDING; break;
+ case EME_PKCS1_OAEP: pad = RSA_PKCS1_OAEP_PADDING; break;
+ case EME_PKCS1v15_SSL: pad = RSA_SSLV23_PADDING; break;
+ case EME_NO_PADDING: pad = RSA_NO_PADDING; break;
+ default: return false; break;
+ }
+
+ int ret;
+ if (isPrivate()) {
+ ret = RSA_private_decrypt(in.size(), (unsigned char *)in.data(), (unsigned char *)result.data(), rsa, pad);
+ } else {
+ ret = RSA_public_decrypt(in.size(), (unsigned char *)in.data(), (unsigned char *)result.data(), rsa, pad);
+ }
+
+ if (ret < 0) {
+ return false;
+ }
+ result.resize(ret);
+
+ *out = result;
+ return true;
+ }
+
+ virtual void startSign(SignatureAlgorithm alg, SignatureFormat)
+ {
+ const EVP_MD *md = 0;
+ if (alg == EMSA3_SHA1) {
+ md = EVP_sha1();
+ } else if (alg == EMSA3_MD5) {
+ md = EVP_md5();
+ }
+#ifdef HAVE_OPENSSL_MD2
+ else if (alg == EMSA3_MD2) {
+ md = EVP_md2();
+ }
+#endif
+ else if (alg == EMSA3_RIPEMD160) {
+ md = EVP_ripemd160();
+ } else if (alg == EMSA3_SHA224) {
+ md = EVP_sha224();
+ } else if (alg == EMSA3_SHA256) {
+ md = EVP_sha256();
+ } else if (alg == EMSA3_SHA384) {
+ md = EVP_sha384();
+ } else if (alg == EMSA3_SHA512) {
+ md = EVP_sha512();
+ } else if (alg == EMSA3_Raw) {
+ // md = 0
+ }
+ evp.startSign(md);
+ }
+
+ virtual void startVerify(SignatureAlgorithm alg, SignatureFormat)
+ {
+ const EVP_MD *md = 0;
+ if (alg == EMSA3_SHA1) {
+ md = EVP_sha1();
+ } else if (alg == EMSA3_MD5) {
+ md = EVP_md5();
+ }
+#ifdef HAVE_OPENSSL_MD2
+ else if (alg == EMSA3_MD2) {
+ md = EVP_md2();
+ }
#endif
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DSA(evp.pkey, dsa);
- sec = false;
- }
-
- virtual int bits() const
- {
- return EVP_PKEY_bits(evp.pkey);
- }
-
- virtual void startSign(SignatureAlgorithm, SignatureFormat format)
- {
- // openssl native format is DER, so transform otherwise
- if(format != DERSequence)
- transformsig = true;
- else
- transformsig = false;
-
- evp.startSign(EVP_sha1());
- }
-
- virtual void startVerify(SignatureAlgorithm, SignatureFormat format)
- {
- // openssl native format is DER, so transform otherwise
- if(format != DERSequence)
- transformsig = true;
- else
- transformsig = false;
-
- evp.startVerify(EVP_sha1());
- }
-
- virtual void update(const MemoryRegion &in)
- {
- evp.update(in);
- }
-
- virtual QByteArray endSign()
- {
- SecureArray out = evp.endSign();
- if(transformsig)
- return dsasig_der_to_raw(out).toByteArray();
- else
- return out.toByteArray();
- }
-
- virtual bool endVerify(const QByteArray &sig)
- {
- SecureArray in;
- if(transformsig)
- in = dsasig_raw_to_der(sig);
- else
- in = sig;
- return evp.endVerify(in);
- }
-
- virtual void createPrivate(const DLGroup &domain, bool block)
- {
- evp.reset();
-
- keymaker = new DSAKeyMaker(domain, !block ? this : 0);
- wasBlocking = block;
- if(block)
- {
- keymaker->run();
- km_finished();
- }
- else
- {
- connect(keymaker, SIGNAL(finished()), SLOT(km_finished()));
- keymaker->start();
- }
- }
-
- virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x)
- {
- evp.reset();
-
- DSA *dsa = DSA_new();
- BIGNUM *bnp = bi2bn(domain.p());
- BIGNUM *bnq = bi2bn(domain.q());
- BIGNUM *bng = bi2bn(domain.g());
- BIGNUM *bnpub_key = bi2bn(y);
- BIGNUM *bnpriv_key = bi2bn(x);
-
- if(!DSA_set0_pqg(dsa, bnp, bnq, bng)
- || !DSA_set0_key(dsa, bnpub_key, bnpriv_key))
- {
- DSA_free(dsa);
- return;
- }
-
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DSA(evp.pkey, dsa);
- sec = true;
- }
-
- virtual void createPublic(const DLGroup &domain, const BigInteger &y)
- {
- evp.reset();
-
- DSA *dsa = DSA_new();
- BIGNUM *bnp = bi2bn(domain.p());
- BIGNUM *bnq = bi2bn(domain.q());
- BIGNUM *bng = bi2bn(domain.g());
- BIGNUM *bnpub_key = bi2bn(y);
-
- if(!DSA_set0_pqg(dsa, bnp, bnq, bng)
- || !DSA_set0_key(dsa, bnpub_key, NULL))
- {
- DSA_free(dsa);
- return;
- }
-
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DSA(evp.pkey, dsa);
- sec = false;
- }
-
- virtual DLGroup domain() const
- {
- DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey);
- const BIGNUM *bnp, *bnq, *bng;
- DSA_get0_pqg(dsa, &bnp, &bnq, &bng);
- return DLGroup(bn2bi(bnp), bn2bi(bnq), bn2bi(bng));
- }
-
- virtual BigInteger y() const
- {
- DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey);
- const BIGNUM *bnpub_key;
- DSA_get0_key(dsa, &bnpub_key, NULL);
- return bn2bi(bnpub_key);
- }
-
- virtual BigInteger x() const
- {
- DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey);
- const BIGNUM *bnpriv_key;
- DSA_get0_key(dsa, NULL, &bnpriv_key);
- return bn2bi(bnpriv_key);
- }
+ else if (alg == EMSA3_RIPEMD160) {
+ md = EVP_ripemd160();
+ } else if (alg == EMSA3_SHA224) {
+ md = EVP_sha224();
+ } else if (alg == EMSA3_SHA256) {
+ md = EVP_sha256();
+ } else if (alg == EMSA3_SHA384) {
+ md = EVP_sha384();
+ } else if (alg == EMSA3_SHA512) {
+ md = EVP_sha512();
+ } else if (alg == EMSA3_Raw) {
+ // md = 0
+ }
+ evp.startVerify(md);
+ }
+
+ virtual void update(const MemoryRegion &in)
+ {
+ evp.update(in);
+ }
+
+ virtual QByteArray endSign()
+ {
+ return evp.endSign().toByteArray();
+ }
+
+ virtual bool endVerify(const QByteArray &sig)
+ {
+ return evp.endVerify(sig);
+ }
+
+ virtual void createPrivate(int bits, int exp, bool block)
+ {
+ evp.reset();
+
+ keymaker = new RSAKeyMaker(bits, exp, !block ? this : 0);
+ wasBlocking = block;
+ if (block) {
+ keymaker->run();
+ km_finished();
+ } else {
+ connect(keymaker, SIGNAL(finished()), SLOT(km_finished()));
+ keymaker->start();
+ }
+ }
+
+ virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d)
+ {
+ evp.reset();
+
+ RSA *rsa = RSA_new();
+ if (RSA_set0_key(rsa, bi2bn(n), bi2bn(e), bi2bn(d)) == 0
+ || RSA_set0_factors(rsa, bi2bn(p), bi2bn(q)) == 0) {
+ // Free BIGNUMS?
+ RSA_free(rsa);
+ return;
+ }
+
+ // When private key has no Public Exponent (e) or Private Exponent (d)
+ // need to disable blinding. Otherwise decryption will be broken.
+ // http://www.mail-archive.com/openssl-users@openssl.org/msg63530.html
+ if (e == BigInteger(0) || d == BigInteger(0)) {
+ RSA_blinding_off(rsa);
+ }
+
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_RSA(evp.pkey, rsa);
+ sec = true;
+ }
+
+ virtual void createPublic(const BigInteger &n, const BigInteger &e)
+ {
+ evp.reset();
+
+ RSA *rsa = RSA_new();
+ if (RSA_set0_key(rsa, bi2bn(n), bi2bn(e), NULL) == 0) {
+ RSA_free(rsa);
+ return;
+ }
+
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_RSA(evp.pkey, rsa);
+ sec = false;
+ }
+
+ virtual BigInteger n() const
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ const BIGNUM *bnn;
+ RSA_get0_key(rsa, &bnn, NULL, NULL);
+ return bn2bi(bnn);
+ }
+
+ virtual BigInteger e() const
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ const BIGNUM *bne;
+ RSA_get0_key(rsa, NULL, &bne, NULL);
+ return bn2bi(bne);
+ }
+
+ virtual BigInteger p() const
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ const BIGNUM *bnp;
+ RSA_get0_factors(rsa, &bnp, NULL);
+ return bn2bi(bnp);
+ }
+
+ virtual BigInteger q() const
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ const BIGNUM *bnq;
+ RSA_get0_factors(rsa, NULL, &bnq);
+ return bn2bi(bnq);
+ }
+
+ virtual BigInteger d() const
+ {
+ RSA *rsa = EVP_PKEY_get0_RSA(evp.pkey);
+ const BIGNUM *bnd;
+ RSA_get0_key(rsa, NULL, NULL, &bnd);
+ return bn2bi(bnd);
+ }
private slots:
- void km_finished()
- {
- DSA *dsa = keymaker->takeResult();
- if(wasBlocking)
- delete keymaker;
- else
- keymaker->deleteLater();
- keymaker = 0;
-
- if(dsa)
- {
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DSA(evp.pkey, dsa);
- sec = true;
- }
-
- if(!wasBlocking)
- emit finished();
- }
+ void km_finished()
+ {
+ RSA *rsa = keymaker->takeResult();
+ if (wasBlocking) {
+ delete keymaker;
+ } else {
+ keymaker->deleteLater();
+ }
+ keymaker = 0;
+
+ if (rsa) {
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_RSA(evp.pkey, rsa);
+ sec = true;
+ }
+
+ if (!wasBlocking) {
+ emit finished();
+ }
+ }
};
//----------------------------------------------------------------------------
-// DHKey
+// DSAKey
//----------------------------------------------------------------------------
-class DHKeyMaker : public QThread
+class DSAKeyMaker : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- DLGroup domain;
- DH *result;
-
- DHKeyMaker(const DLGroup &_domain, QObject *parent = 0) : QThread(parent), domain(_domain), result(0)
- {
- }
-
- ~DHKeyMaker()
- {
- wait();
- if(result)
- DH_free(result);
- }
-
- virtual void run()
- {
- DH *dh = DH_new();
- BIGNUM *bnp = bi2bn(domain.p());
- BIGNUM *bng = bi2bn(domain.g());
- if(!DH_set0_pqg(dh, bnp, NULL, bng)
- || !DH_generate_key(dh))
- {
- DH_free(dh);
- return;
- }
- result = dh;
- }
-
- DH *takeResult()
- {
- DH *dh = result;
- result = 0;
- return dh;
- }
+ DLGroup domain;
+ DSA *result;
+
+ DSAKeyMaker(const DLGroup &_domain, QObject *parent = 0) : QThread(parent), domain(_domain), result(0)
+ {
+ }
+
+ ~DSAKeyMaker()
+ {
+ wait();
+ if (result) {
+ DSA_free(result);
+ }
+ }
+
+ virtual void run()
+ {
+ DSA *dsa = DSA_new();
+ BIGNUM *pne = bi2bn(domain.p()),
+ *qne = bi2bn(domain.q()),
+ *gne = bi2bn(domain.g());
+
+ if (!DSA_set0_pqg(dsa, pne, qne, gne)
+ || !DSA_generate_key(dsa)) {
+ DSA_free(dsa);
+ return;
+ }
+ result = dsa;
+ }
+
+ DSA *takeResult()
+ {
+ DSA *dsa = result;
+ result = 0;
+ return dsa;
+ }
};
-class DHKey : public DHContext
+// note: DSA doesn't use SignatureAlgorithm, since EMSA1 is always assumed
+class DSAKey : public DSAContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- EVPKey evp;
- DHKeyMaker *keymaker;
- bool wasBlocking;
- bool sec;
-
- DHKey(Provider *p) : DHContext(p)
- {
- keymaker = 0;
- sec = false;
- }
-
- DHKey(const DHKey &from) : DHContext(from.provider()), evp(from.evp)
- {
- keymaker = 0;
- sec = from.sec;
- }
-
- ~DHKey()
- {
- delete keymaker;
- }
-
- virtual Provider::Context *clone() const
- {
- return new DHKey(*this);
- }
-
- virtual bool isNull() const
- {
- return (evp.pkey ? false: true);
- }
-
- virtual PKey::Type type() const
- {
- return PKey::DH;
- }
-
- virtual bool isPrivate() const
- {
- return sec;
- }
-
- virtual bool canExport() const
- {
- return true;
- }
-
- virtual void convertToPublic()
- {
- if(!sec)
- return;
-
- DH *orig = EVP_PKEY_get0_DH(evp.pkey);
- DH *dh = DH_new();
- const BIGNUM *bnp, *bng, *bnpub_key;
- DH_get0_pqg(orig, &bnp, NULL, &bng);
- DH_get0_key(orig, &bnpub_key, NULL);
-
- DH_set0_key(dh, BN_dup(bnpub_key), NULL);
- DH_set0_pqg(dh, BN_dup(bnp), NULL, BN_dup(bng));
-
- evp.reset();
-
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DH(evp.pkey, dh);
- sec = false;
- }
-
- virtual int bits() const
- {
- return EVP_PKEY_bits(evp.pkey);
- }
-
- virtual SymmetricKey deriveKey(const PKeyBase &theirs)
- {
- DH *dh = EVP_PKEY_get0_DH(evp.pkey);
- DH *them = EVP_PKEY_get0_DH(static_cast<const DHKey *>(&theirs)->evp.pkey);
- const BIGNUM *bnpub_key;
- DH_get0_key(them, &bnpub_key, NULL);
-
- SecureArray result(DH_size(dh));
- int ret = DH_compute_key((unsigned char *)result.data(), bnpub_key, dh);
- if(ret <= 0)
- return SymmetricKey();
- result.resize(ret);
- return SymmetricKey(result);
- }
-
- virtual void createPrivate(const DLGroup &domain, bool block)
- {
- evp.reset();
-
- keymaker = new DHKeyMaker(domain, !block ? this : 0);
- wasBlocking = block;
- if(block)
- {
- keymaker->run();
- km_finished();
- }
- else
- {
- connect(keymaker, SIGNAL(finished()), SLOT(km_finished()));
- keymaker->start();
- }
- }
-
- virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x)
- {
- evp.reset();
-
- DH *dh = DH_new();
- BIGNUM *bnp = bi2bn(domain.p());
- BIGNUM *bng = bi2bn(domain.g());
- BIGNUM *bnpub_key = bi2bn(y);
- BIGNUM *bnpriv_key = bi2bn(x);
-
- if(!DH_set0_key(dh, bnpub_key, bnpriv_key)
- || !DH_set0_pqg(dh, bnp, NULL, bng))
- {
- DH_free(dh);
- return;
- }
-
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DH(evp.pkey, dh);
- sec = true;
- }
-
- virtual void createPublic(const DLGroup &domain, const BigInteger &y)
- {
- evp.reset();
-
- DH *dh = DH_new();
- BIGNUM *bnp = bi2bn(domain.p());
- BIGNUM *bng = bi2bn(domain.g());
- BIGNUM *bnpub_key = bi2bn(y);
-
- if(!DH_set0_key(dh, bnpub_key, NULL)
- || !DH_set0_pqg(dh, bnp, NULL, bng))
- {
- DH_free(dh);
- return;
- }
-
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DH(evp.pkey, dh);
- sec = false;
- }
-
- virtual DLGroup domain() const
- {
- DH *dh = EVP_PKEY_get0_DH(evp.pkey);
- const BIGNUM *bnp, *bng;
- DH_get0_pqg(dh, &bnp, NULL, &bng);
- return DLGroup(bn2bi(bnp), bn2bi(bng));
- }
-
- virtual BigInteger y() const
- {
- DH *dh = EVP_PKEY_get0_DH(evp.pkey);
- const BIGNUM *bnpub_key;
- DH_get0_key(dh, &bnpub_key, NULL);
- return bn2bi(bnpub_key);
- }
-
- virtual BigInteger x() const
- {
- DH *dh = EVP_PKEY_get0_DH(evp.pkey);
- const BIGNUM *bnpriv_key;
- DH_get0_key(dh, NULL, &bnpriv_key);
- return bn2bi(bnpriv_key);
- }
+ EVPKey evp;
+ DSAKeyMaker *keymaker;
+ bool wasBlocking;
+ bool transformsig;
+ bool sec;
-private slots:
- void km_finished()
- {
- DH *dh = keymaker->takeResult();
- if(wasBlocking)
- delete keymaker;
- else
- keymaker->deleteLater();
- keymaker = 0;
-
- if(dh)
- {
- evp.pkey = EVP_PKEY_new();
- EVP_PKEY_assign_DH(evp.pkey, dh);
- sec = true;
- }
-
- if(!wasBlocking)
- emit finished();
- }
-};
+ DSAKey(Provider *p) : DSAContext(p)
+ {
+ keymaker = 0;
+ sec = false;
+ }
-//----------------------------------------------------------------------------
-// QCA-based RSA_METHOD
-//----------------------------------------------------------------------------
+ DSAKey(const DSAKey &from) : DSAContext(from.provider()), evp(from.evp)
+ {
+ keymaker = 0;
+ sec = from.sec;
+ }
-// only supports EMSA3_Raw for now
-class QCA_RSA_METHOD
-{
-public:
- RSAPrivateKey key;
+ ~DSAKey()
+ {
+ delete keymaker;
+ }
- QCA_RSA_METHOD(RSAPrivateKey _key, RSA *rsa)
- {
- key = _key;
- RSA_set_method(rsa, rsa_method());
-#ifndef OSSL_110
- rsa->flags |= RSA_FLAG_SIGN_VER;
-#endif
- RSA_set_app_data(rsa, this);
- BIGNUM *bnn = bi2bn(_key.n());
- BIGNUM *bne = bi2bn(_key.e());
-
- RSA_set0_key(rsa, bnn, bne, NULL);
- }
-
- RSA_METHOD *rsa_method()
- {
- static RSA_METHOD *ops = 0;
-
- if(!ops)
- {
- ops = RSA_meth_dup(RSA_get_default_method());
- RSA_meth_set_priv_enc(ops, NULL); //pkcs11_rsa_encrypt
- RSA_meth_set_priv_dec(ops, rsa_priv_dec); //pkcs11_rsa_encrypt
-#ifdef OSSL_110
- RSA_meth_set_sign(ops, NULL);
-#else
- RSA_meth_set_sign(ops, rsa_sign);
-#endif
- RSA_meth_set_verify(ops, NULL); //pkcs11_rsa_verify
- RSA_meth_set_finish(ops, rsa_finish);
- }
- return ops;
- }
-
- static int rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
- {
- QCA::EncryptionAlgorithm algo;
-
- if (padding == RSA_PKCS1_PADDING)
- {
- algo = QCA::EME_PKCS1v15;
- }
- else if (padding == RSA_PKCS1_OAEP_PADDING)
- {
- algo = QCA::EME_PKCS1_OAEP;
- }
- else
- {
- RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
- return -1;
- }
-
- QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa);
-
- QCA::SecureArray input;
- input.resize(flen);
- memcpy(input.data(), from, input.size());
-
- QCA::SecureArray output;
-
- if (self->key.decrypt(input, &output, algo)) {
- memcpy(to, output.data(), output.size());
- return output.size();
- }
-
- // XXX: An error should be set in this case too.
- return -1;
- }
+ virtual Provider::Context *clone() const
+ {
+ return new DSAKey(*this);
+ }
-#ifndef OSSL_110
- static int rsa_sign(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
- {
- QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa);
-
- // TODO: this is disgusting
-
- unsigned char *p, *tmps = NULL;
- const unsigned char *s = NULL;
- int i,j;
- j = 0;
-
- if(type == NID_md5_sha1)
- {
- }
- else
- {
- // make X509 packet
- X509_SIG sig;
- ASN1_TYPE parameter;
-
- X509_ALGOR algor;
- ASN1_OCTET_STRING digest;
- int rsa_size = RSA_size(rsa);
- //int rsa_size = 128;
- //CK_ULONG sigsize = rsa_size;
-
- sig.algor= &algor;
- sig.algor->algorithm=OBJ_nid2obj(type);
- if (sig.algor->algorithm == NULL)
- {
- //RSAerr(RSA_F_RSA_SIGN,RSA_R_UNKNOWN_ALGORITHM_TYPE);
- return 0;
- }
- if (sig.algor->algorithm->length == 0)
- {
- //RSAerr(RSA_F_RSA_SIGN,RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD);
- return 0;
- }
- parameter.type=V_ASN1_NULL;
- parameter.value.ptr=NULL;
- sig.algor->parameter= &parameter;
-
- sig.digest= &digest;
- sig.digest->data=(unsigned char *)m; /* TMP UGLY CAST */
- sig.digest->length=m_len;
-
- i=i2d_X509_SIG(&sig,NULL);
-
- j=rsa_size;
- if (i > (j-RSA_PKCS1_PADDING_SIZE))
- {
- //RSAerr(RSA_F_RSA_SIGN,RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY);
- return 0;
- }
-
- tmps=(unsigned char *)OPENSSL_malloc((unsigned int)j+1);
- if (tmps == NULL)
- {
- //RSAerr(RSA_F_RSA_SIGN,ERR_R_MALLOC_FAILURE);
- return 0;
- }
- p=tmps;
- i2d_X509_SIG(&sig,&p);
- s=tmps;
- m = s;
- m_len = i;
- }
-
- SecureArray input;
- input.resize(m_len);
- memcpy(input.data(), m, input.size());
- SecureArray result = self->key.signMessage(input, EMSA3_Raw);
-
- if(tmps)
- {
- OPENSSL_cleanse(tmps,(unsigned int)j+1);
- OPENSSL_free(tmps);
- }
-
- // TODO: even though we return error here, PKCS7_sign will
- // not return error. what gives?
- if(result.isEmpty())
- return 0;
-
- memcpy(sigret, result.data(), result.size());
- *siglen = result.size();
-
- return 1;
- }
-#endif
+ virtual bool isNull() const
+ {
+ return (evp.pkey ? false : true);
+ }
- static int rsa_finish(RSA *rsa)
- {
- QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa);
- delete self;
- return 1;
- }
-};
+ virtual PKey::Type type() const
+ {
+ return PKey::DSA;
+ }
-static RSA *createFromExisting(const RSAPrivateKey &key)
-{
- RSA *r = RSA_new();
- new QCA_RSA_METHOD(key, r); // will delete itself on RSA_free
- return r;
-}
+ virtual bool isPrivate() const
+ {
+ return sec;
+ }
-//----------------------------------------------------------------------------
-// MyPKeyContext
-//----------------------------------------------------------------------------
-class MyPKeyContext : public PKeyContext
-{
-public:
- PKeyBase *k;
-
- MyPKeyContext(Provider *p) : PKeyContext(p)
- {
- k = 0;
- }
-
- ~MyPKeyContext()
- {
- delete k;
- }
-
- virtual Provider::Context *clone() const
- {
- MyPKeyContext *c = new MyPKeyContext(*this);
- c->k = (PKeyBase *)k->clone();
- return c;
- }
-
- virtual QList<PKey::Type> supportedTypes() const
- {
- QList<PKey::Type> list;
- list += PKey::RSA;
- list += PKey::DSA;
- list += PKey::DH;
- return list;
- }
-
- virtual QList<PKey::Type> supportedIOTypes() const
- {
- QList<PKey::Type> list;
- list += PKey::RSA;
- list += PKey::DSA;
- return list;
- }
-
- virtual QList<PBEAlgorithm> supportedPBEAlgorithms() const
- {
- QList<PBEAlgorithm> list;
- list += PBES2_DES_SHA1;
- list += PBES2_TripleDES_SHA1;
- return list;
- }
-
- virtual PKeyBase *key()
- {
- return k;
- }
-
- virtual const PKeyBase *key() const
- {
- return k;
- }
-
- virtual void setKey(PKeyBase *key)
- {
- k = key;
- }
-
- virtual bool importKey(const PKeyBase *key)
- {
- Q_UNUSED(key);
- return false;
- }
-
- EVP_PKEY *get_pkey() const
- {
- PKey::Type t = k->type();
- if(t == PKey::RSA)
- return static_cast<RSAKey *>(k)->evp.pkey;
- else if(t == PKey::DSA)
- return static_cast<DSAKey *>(k)->evp.pkey;
- else
- return static_cast<DHKey *>(k)->evp.pkey;
- }
-
- PKeyBase *pkeyToBase(EVP_PKEY *pkey, bool sec) const
- {
- PKeyBase *nk = 0;
- int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
- if(pkey_type == EVP_PKEY_RSA)
- {
- RSAKey *c = new RSAKey(provider());
- c->evp.pkey = pkey;
- c->sec = sec;
- nk = c;
- }
- else if(pkey_type == EVP_PKEY_DSA)
- {
- DSAKey *c = new DSAKey(provider());
- c->evp.pkey = pkey;
- c->sec = sec;
- nk = c;
- }
- else if(pkey_type == EVP_PKEY_DH)
- {
- DHKey *c = new DHKey(provider());
- c->evp.pkey = pkey;
- c->sec = sec;
- nk = c;
- }
- else
- {
- EVP_PKEY_free(pkey);
- }
- return nk;
- }
-
- virtual QByteArray publicToDER() const
- {
- EVP_PKEY *pkey = get_pkey();
-
- int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
-
- // OpenSSL does not have DH import/export support
- if(pkey_type == EVP_PKEY_DH)
- return QByteArray();
-
- BIO *bo = BIO_new(BIO_s_mem());
- i2d_PUBKEY_bio(bo, pkey);
- QByteArray buf = bio2ba(bo);
- return buf;
- }
-
- virtual QString publicToPEM() const
- {
- EVP_PKEY *pkey = get_pkey();
-
- int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
-
- // OpenSSL does not have DH import/export support
- if(pkey_type == EVP_PKEY_DH)
- return QString();
-
- BIO *bo = BIO_new(BIO_s_mem());
- PEM_write_bio_PUBKEY(bo, pkey);
- QByteArray buf = bio2ba(bo);
- return QString::fromLatin1(buf);
- }
-
- virtual ConvertResult publicFromDER(const QByteArray &in)
- {
- delete k;
- k = 0;
-
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- EVP_PKEY *pkey = d2i_PUBKEY_bio(bi, NULL);
- BIO_free(bi);
-
- if(!pkey)
- return ErrorDecode;
-
- k = pkeyToBase(pkey, false);
- if(k)
- return ConvertGood;
- else
- return ErrorDecode;
- }
-
- virtual ConvertResult publicFromPEM(const QString &s)
- {
- delete k;
- k = 0;
-
- QByteArray in = s.toLatin1();
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- EVP_PKEY *pkey = PEM_read_bio_PUBKEY(bi, NULL, passphrase_cb, NULL);
- BIO_free(bi);
-
- if(!pkey)
- return ErrorDecode;
-
- k = pkeyToBase(pkey, false);
- if(k)
- return ConvertGood;
- else
- return ErrorDecode;
- }
-
- virtual SecureArray privateToDER(const SecureArray &passphrase, PBEAlgorithm pbe) const
- {
- //if(pbe == PBEDefault)
- // pbe = PBES2_TripleDES_SHA1;
-
- const EVP_CIPHER *cipher = 0;
- if(pbe == PBES2_TripleDES_SHA1)
- cipher = EVP_des_ede3_cbc();
- else if(pbe == PBES2_DES_SHA1)
- cipher = EVP_des_cbc();
-
- if(!cipher)
- return SecureArray();
-
- EVP_PKEY *pkey = get_pkey();
- int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
-
- // OpenSSL does not have DH import/export support
- if(pkey_type == EVP_PKEY_DH)
- return SecureArray();
-
- BIO *bo = BIO_new(BIO_s_mem());
- if(!passphrase.isEmpty())
- i2d_PKCS8PrivateKey_bio(bo, pkey, cipher, NULL, 0, NULL, (void *)passphrase.data());
- else
- i2d_PKCS8PrivateKey_bio(bo, pkey, NULL, NULL, 0, NULL, NULL);
- SecureArray buf = bio2buf(bo);
- return buf;
- }
-
- virtual QString privateToPEM(const SecureArray &passphrase, PBEAlgorithm pbe) const
- {
- //if(pbe == PBEDefault)
- // pbe = PBES2_TripleDES_SHA1;
-
- const EVP_CIPHER *cipher = 0;
- if(pbe == PBES2_TripleDES_SHA1)
- cipher = EVP_des_ede3_cbc();
- else if(pbe == PBES2_DES_SHA1)
- cipher = EVP_des_cbc();
-
- if(!cipher)
- return QString();
-
- EVP_PKEY *pkey = get_pkey();
- int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
-
- // OpenSSL does not have DH import/export support
- if(pkey_type == EVP_PKEY_DH)
- return QString();
-
- BIO *bo = BIO_new(BIO_s_mem());
- if(!passphrase.isEmpty())
- PEM_write_bio_PKCS8PrivateKey(bo, pkey, cipher, NULL, 0, NULL, (void *)passphrase.data());
- else
- PEM_write_bio_PKCS8PrivateKey(bo, pkey, NULL, NULL, 0, NULL, NULL);
- SecureArray buf = bio2buf(bo);
- return QString::fromLatin1(buf.toByteArray());
- }
-
- virtual ConvertResult privateFromDER(const SecureArray &in, const SecureArray &passphrase)
- {
- delete k;
- k = 0;
-
- EVP_PKEY *pkey;
- if(!passphrase.isEmpty())
- pkey = qca_d2i_PKCS8PrivateKey(in, NULL, NULL, (void *)passphrase.data());
- else
- pkey = qca_d2i_PKCS8PrivateKey(in, NULL, passphrase_cb, NULL);
-
- if(!pkey)
- return ErrorDecode;
-
- k = pkeyToBase(pkey, true);
- if(k)
- return ConvertGood;
- else
- return ErrorDecode;
- }
-
- virtual ConvertResult privateFromPEM(const QString &s, const SecureArray &passphrase)
- {
- delete k;
- k = 0;
-
- QByteArray in = s.toLatin1();
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- EVP_PKEY *pkey;
- if(!passphrase.isEmpty())
- pkey = PEM_read_bio_PrivateKey(bi, NULL, NULL, (void *)passphrase.data());
- else
- pkey = PEM_read_bio_PrivateKey(bi, NULL, passphrase_cb, NULL);
- BIO_free(bi);
-
- if(!pkey)
- return ErrorDecode;
-
- k = pkeyToBase(pkey, true);
- if(k)
- return ConvertGood;
- else
- return ErrorDecode;
- }
-};
+ virtual bool canExport() const
+ {
+ return true;
+ }
-//----------------------------------------------------------------------------
-// MyCertContext
-//----------------------------------------------------------------------------
-class X509Item
-{
-public:
- X509 *cert;
- X509_REQ *req;
- X509_CRL *crl;
-
- enum Type { TypeCert, TypeReq, TypeCRL };
-
- X509Item()
- {
- cert = 0;
- req = 0;
- crl = 0;
- }
-
- X509Item(const X509Item &from)
- {
- cert = 0;
- req = 0;
- crl = 0;
- *this = from;
- }
-
- ~X509Item()
- {
- reset();
- }
-
- X509Item & operator=(const X509Item &from)
- {
- if(this != &from)
- {
- reset();
- cert = from.cert;
- req = from.req;
- crl = from.crl;
-
- if(cert)
- X509_up_ref(cert);
- if(req)
- {
-#ifdef OSSL_110
- // Not exposed, so copy
- req = X509_REQ_dup(req);
+ virtual void convertToPublic()
+ {
+ if (!sec) {
+ return;
+ }
+
+ // extract the public key into DER format
+ DSA *dsa_pkey = EVP_PKEY_get0_DSA(evp.pkey);
+ int len = i2d_DSAPublicKey(dsa_pkey, NULL);
+ SecureArray result(len);
+ unsigned char *p = (unsigned char *)result.data();
+ i2d_DSAPublicKey(dsa_pkey, &p);
+ p = (unsigned char *)result.data();
+
+ // put the DER public key back into openssl
+ evp.reset();
+ DSA *dsa;
+#ifdef OSSL_097
+ dsa = d2i_DSAPublicKey(NULL, (const unsigned char **)&p, result.size());
#else
- CRYPTO_add(&req->references, 1, CRYPTO_LOCK_X509_REQ);
+ dsa = d2i_DSAPublicKey(NULL, (unsigned char **)&p, result.size());
#endif
- }
- if(crl)
- X509_CRL_up_ref(crl);
- }
-
- return *this;
- }
-
- void reset()
- {
- if(cert)
- {
- X509_free(cert);
- cert = 0;
- }
- if(req)
- {
- X509_REQ_free(req);
- req = 0;
- }
- if(crl)
- {
- X509_CRL_free(crl);
- crl = 0;
- }
- }
-
- bool isNull() const
- {
- return (!cert && !req && !crl);
- }
-
- QByteArray toDER() const
- {
- BIO *bo = BIO_new(BIO_s_mem());
- if(cert)
- i2d_X509_bio(bo, cert);
- else if(req)
- i2d_X509_REQ_bio(bo, req);
- else if(crl)
- i2d_X509_CRL_bio(bo, crl);
- QByteArray buf = bio2ba(bo);
- return buf;
- }
-
- QString toPEM() const
- {
- BIO *bo = BIO_new(BIO_s_mem());
- if(cert)
- PEM_write_bio_X509(bo, cert);
- else if(req)
- PEM_write_bio_X509_REQ(bo, req);
- else if(crl)
- PEM_write_bio_X509_CRL(bo, crl);
- QByteArray buf = bio2ba(bo);
- return QString::fromLatin1(buf);
- }
-
- ConvertResult fromDER(const QByteArray &in, Type t)
- {
- reset();
-
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
-
- if(t == TypeCert)
- cert = d2i_X509_bio(bi, NULL);
- else if(t == TypeReq)
- req = d2i_X509_REQ_bio(bi, NULL);
- else if(t == TypeCRL)
- crl = d2i_X509_CRL_bio(bi, NULL);
-
- BIO_free(bi);
-
- if(isNull())
- return ErrorDecode;
-
- return ConvertGood;
- }
-
- ConvertResult fromPEM(const QString &s, Type t)
- {
- reset();
-
- QByteArray in = s.toLatin1();
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
-
- if(t == TypeCert)
- cert = PEM_read_bio_X509(bi, NULL, passphrase_cb, NULL);
- else if(t == TypeReq)
- req = PEM_read_bio_X509_REQ(bi, NULL, passphrase_cb, NULL);
- else if(t == TypeCRL)
- crl = PEM_read_bio_X509_CRL(bi, NULL, passphrase_cb, NULL);
-
- BIO_free(bi);
-
- if(isNull())
- return ErrorDecode;
-
- return ConvertGood;
- }
-};
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DSA(evp.pkey, dsa);
+ sec = false;
+ }
-// (taken from kdelibs) -- Justin
-//
-// This code is mostly taken from OpenSSL v0.9.5a
-// by Eric Young
-QDateTime ASN1_UTCTIME_QDateTime(const ASN1_UTCTIME *tm, int *isGmt)
-{
- QDateTime qdt;
- char *v;
- int gmt=0;
- int i;
- int y=0,M=0,d=0,h=0,m=0,s=0;
- QDate qdate;
- QTime qtime;
-
- i = tm->length;
- v = (char *)tm->data;
-
- if (i < 10) goto auq_err;
- if (v[i-1] == 'Z') gmt=1;
- for (i=0; i<10; i++)
- if ((v[i] > '9') || (v[i] < '0')) goto auq_err;
- y = (v[0]-'0')*10+(v[1]-'0');
- if (y < 50) y+=100;
- M = (v[2]-'0')*10+(v[3]-'0');
- if ((M > 12) || (M < 1)) goto auq_err;
- d = (v[4]-'0')*10+(v[5]-'0');
- h = (v[6]-'0')*10+(v[7]-'0');
- m = (v[8]-'0')*10+(v[9]-'0');
- if ( (v[10] >= '0') && (v[10] <= '9') &&
- (v[11] >= '0') && (v[11] <= '9'))
- s = (v[10]-'0')*10+(v[11]-'0');
-
- // localize the date and display it.
- qdate.setDate(y+1900, M, d);
- qtime.setHMS(h,m,s);
- qdt.setDate(qdate); qdt.setTime(qtime);
- if (gmt) qdt.setTimeSpec(Qt::UTC);
- auq_err:
- if (isGmt) *isGmt = gmt;
- return qdt;
-}
+ virtual int bits() const
+ {
+ return EVP_PKEY_bits(evp.pkey);
+ }
-class MyCertContext;
-static bool sameChain(STACK_OF(X509) *ossl, const QList<const MyCertContext*> &qca);
+ virtual void startSign(SignatureAlgorithm, SignatureFormat format)
+ {
+ // openssl native format is DER, so transform otherwise
+ if (format != DERSequence) {
+ transformsig = true;
+ } else {
+ transformsig = false;
+ }
+
+ evp.startSign(EVP_sha1());
+ }
-// TODO: support read/write of multiple info values with the same name
-class MyCertContext : public CertContext
-{
-public:
- X509Item item;
- CertContextProps _props;
-
- MyCertContext(Provider *p) : CertContext(p)
- {
- //printf("[%p] ** created\n", this);
- }
-
- MyCertContext(const MyCertContext &from) : CertContext(from), item(from.item), _props(from._props)
- {
- //printf("[%p] ** created as copy (from [%p])\n", this, &from);
- }
-
- ~MyCertContext()
- {
- //printf("[%p] ** deleted\n", this);
- }
-
- virtual Provider::Context *clone() const
- {
- return new MyCertContext(*this);
- }
-
- virtual QByteArray toDER() const
- {
- return item.toDER();
- }
-
- virtual QString toPEM() const
- {
- return item.toPEM();
- }
-
- virtual ConvertResult fromDER(const QByteArray &a)
- {
- _props = CertContextProps();
- ConvertResult r = item.fromDER(a, X509Item::TypeCert);
- if(r == ConvertGood)
- make_props();
- return r;
- }
-
- virtual ConvertResult fromPEM(const QString &s)
- {
- _props = CertContextProps();
- ConvertResult r = item.fromPEM(s, X509Item::TypeCert);
- if(r == ConvertGood)
- make_props();
- return r;
- }
-
- void fromX509(X509 *x)
- {
- X509_up_ref(x);
- item.cert = x;
- make_props();
- }
-
- virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv)
- {
- _props = CertContextProps();
- item.reset();
-
- CertificateInfo info = opts.info();
-
- // Note: removing default constraints, let the app choose these if it wants
- Constraints constraints = opts.constraints();
- // constraints - logic from Botan
- /*Constraints constraints;
- if(opts.isCA())
- {
- constraints += KeyCertificateSign;
- constraints += CRLSign;
- }
- else
- constraints = find_constraints(priv, opts.constraints());*/
-
- EVP_PKEY *pk = static_cast<const MyPKeyContext *>(&priv)->get_pkey();
- X509_EXTENSION *ex;
-
- const EVP_MD *md;
- if(priv.key()->type() == PKey::RSA)
- md = EVP_sha1();
- else if(priv.key()->type() == PKey::DSA)
- md = EVP_sha1();
- else
- return false;
-
- // create
- X509 *x = X509_new();
- X509_set_version(x, 2);
-
- // serial
- BIGNUM *bn = bi2bn(opts.serialNumber());
- BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(x));
- BN_free(bn);
-
- // validity period
- ASN1_TIME_set(X509_get_notBefore(x), opts.notValidBefore().toTime_t());
- ASN1_TIME_set(X509_get_notAfter(x), opts.notValidAfter().toTime_t());
-
- // public key
- X509_set_pubkey(x, pk);
-
- // subject
- X509_NAME *name = new_cert_name(info);
- X509_set_subject_name(x, name);
-
- // issuer == subject
- X509_set_issuer_name(x, name);
-
- // subject key id
- ex = new_subject_key_id(x);
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // CA mode
- ex = new_basic_constraints(opts.isCA(), opts.pathLimit());
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // subject alt name
- ex = new_cert_subject_alt_name(info);
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // key usage
- ex = new_cert_key_usage(constraints);
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // extended key usage
- ex = new_cert_ext_key_usage(constraints);
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // policies
- ex = new_cert_policies(opts.policies());
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // finished
- X509_sign(x, pk, md);
-
- item.cert = x;
- make_props();
- return true;
- }
-
- virtual const CertContextProps *props() const
- {
- //printf("[%p] grabbing props\n", this);
- return &_props;
- }
-
- virtual bool compare(const CertContext *other) const
- {
- const CertContextProps *a = &_props;
- const CertContextProps *b = other->props();
-
- PublicKey akey, bkey;
- PKeyContext *ac = subjectPublicKey();
- akey.change(ac);
- PKeyContext *bc = other->subjectPublicKey();
- bkey.change(bc);
-
- // logic from Botan
- if(a->sig != b->sig || a->sigalgo != b->sigalgo || akey != bkey)
- return false;
-
- if(a->issuer != b->issuer || a->subject != b->subject)
- return false;
- if(a->serial != b->serial || a->version != b->version)
- return false;
- if(a->start != b->start || a->end != b->end)
- return false;
-
- return true;
- }
-
- // does a new
- virtual PKeyContext *subjectPublicKey() const
- {
- MyPKeyContext *kc = new MyPKeyContext(provider());
- EVP_PKEY *pkey = X509_get_pubkey(item.cert);
- PKeyBase *kb = kc->pkeyToBase(pkey, false);
- kc->setKey(kb);
- return kc;
- }
-
- virtual bool isIssuerOf(const CertContext *other) const
- {
-
- // to check a single issuer, we make a list of 1
- STACK_OF(X509) *untrusted_list = sk_X509_new_null();
-
- const MyCertContext *our_cc = this;
- X509 *x = our_cc->item.cert;
- X509_up_ref(x);
- sk_X509_push(untrusted_list, x);
-
- const MyCertContext *other_cc = static_cast<const MyCertContext *>(other);
- X509 *ox = other_cc->item.cert;
-
- X509_STORE *store = X509_STORE_new();
-
- X509_STORE_CTX *ctx = X509_STORE_CTX_new();
- X509_STORE_CTX_init(ctx, store, ox, untrusted_list);
-
- // we don't care about the verify result here
- X509_verify_cert(ctx);
-
- // grab the chain, which may not be fully populated
- STACK_OF(X509) *chain = X509_STORE_CTX_get_chain(ctx);
-
- bool ok = false;
-
- // chain should be exactly 2 items
- QList<const MyCertContext*> expected;
- expected += other_cc;
- expected += our_cc;
- if(chain && sameChain(chain, expected))
- ok = true;
-
- // cleanup
- X509_STORE_CTX_free(ctx);
- X509_STORE_free(store);
- sk_X509_pop_free(untrusted_list, X509_free);
-
- return ok;
- }
-
- // implemented later because it depends on MyCRLContext
- virtual Validity validate(const QList<CertContext*> &trusted, const QList<CertContext*> &untrusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const;
-
- virtual Validity validate_chain(const QList<CertContext*> &chain, const QList<CertContext*> &trusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const;
-
- void make_props()
- {
- X509 *x = item.cert;
- CertContextProps p;
-
- p.version = X509_get_version(x);
-
- ASN1_INTEGER *ai = X509_get_serialNumber(x);
- if(ai)
- {
- char *rep = i2s_ASN1_INTEGER(NULL, ai);
- QString str = rep;
- OPENSSL_free(rep);
- p.serial.fromString(str);
- }
-
- p.start = ASN1_UTCTIME_QDateTime(X509_get_notBefore(x), NULL);
- p.end = ASN1_UTCTIME_QDateTime(X509_get_notAfter(x), NULL);
-
- CertificateInfo subject, issuer;
-
- subject = get_cert_name(X509_get_subject_name(x));
- issuer = get_cert_name(X509_get_issuer_name(x));
-
- p.isSelfSigned = ( X509_V_OK == X509_check_issued( x, x ) );
-
- p.isCA = false;
- p.pathLimit = 0;
- int pos = X509_get_ext_by_NID(x, NID_basic_constraints, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- get_basic_constraints(ex, &p.isCA, &p.pathLimit);
- }
-
- pos = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- subject.unite(get_cert_alt_name(ex));
- }
-
- pos = X509_get_ext_by_NID(x, NID_issuer_alt_name, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- issuer.unite(get_cert_alt_name(ex));
- }
-
- pos = X509_get_ext_by_NID(x, NID_key_usage, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- p.constraints = get_cert_key_usage(ex);
- }
-
- pos = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- p.constraints += get_cert_ext_key_usage(ex);
- }
-
- pos = X509_get_ext_by_NID(x, NID_certificate_policies, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- p.policies = get_cert_policies(ex);
- }
+ virtual void startVerify(SignatureAlgorithm, SignatureFormat format)
+ {
+ // openssl native format is DER, so transform otherwise
+ if (format != DERSequence) {
+ transformsig = true;
+ } else {
+ transformsig = false;
+ }
+
+ evp.startVerify(EVP_sha1());
+ }
-#ifdef OSSL_110
- const
-#endif
- ASN1_BIT_STRING *signature;
-
- X509_get0_signature(&signature, NULL, x);
- if(signature)
- {
- p.sig = QByteArray(signature->length, 0);
- for (int i=0; i< signature->length; i++)
- p.sig[i] = signature->data[i];
- }
-
-
- switch( X509_get_signature_nid(x) )
- {
- case NID_sha1WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA1;
- break;
- case NID_md5WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_MD5;
- break;
-#ifdef HAVE_OPENSSL_MD2
- case NID_md2WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_MD2;
- break;
-#endif
- case NID_ripemd160WithRSA:
- p.sigalgo = QCA::EMSA3_RIPEMD160;
- break;
- case NID_dsaWithSHA1:
- p.sigalgo = QCA::EMSA1_SHA1;
- break;
- case NID_sha224WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA224;
- break;
- case NID_sha256WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA256;
- break;
- case NID_sha384WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA384;
- break;
- case NID_sha512WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA512;
- break;
- default:
- qDebug() << "Unknown signature value: " << X509_get_signature_nid(x);
- p.sigalgo = QCA::SignatureUnknown;
- }
-
- pos = X509_get_ext_by_NID(x, NID_subject_key_identifier, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- p.subjectId += get_cert_subject_key_id(ex);
- }
-
- pos = X509_get_ext_by_NID(x, NID_authority_key_identifier, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_get_ext(x, pos);
- if(ex)
- p.issuerId += get_cert_issuer_key_id(ex);
- }
-
- // FIXME: super hack
- CertificateOptions opts;
- opts.setInfo(subject);
- p.subject = opts.infoOrdered();
- opts.setInfo(issuer);
- p.issuer = opts.infoOrdered();
-
- _props = p;
- //printf("[%p] made props: [%s]\n", this, _props.subject[CommonName].toLatin1().data());
- }
-};
+ virtual void update(const MemoryRegion &in)
+ {
+ evp.update(in);
+ }
-bool sameChain(STACK_OF(X509) *ossl, const QList<const MyCertContext*> &qca)
-{
- if(sk_X509_num(ossl) != qca.count())
- return false;
-
- for(int n = 0; n < sk_X509_num(ossl); ++n)
- {
- X509 *a = sk_X509_value(ossl, n);
- X509 *b = qca[n]->item.cert;
- if(X509_cmp(a, b) != 0)
- return false;
- }
-
- return true;
-}
+ virtual QByteArray endSign()
+ {
+ SecureArray out = evp.endSign();
+ if (transformsig) {
+ return dsasig_der_to_raw(out).toByteArray();
+ } else {
+ return out.toByteArray();
+ }
+ }
+
+ virtual bool endVerify(const QByteArray &sig)
+ {
+ SecureArray in;
+ if (transformsig) {
+ in = dsasig_raw_to_der(sig);
+ } else {
+ in = sig;
+ }
+ return evp.endVerify(in);
+ }
+
+ virtual void createPrivate(const DLGroup &domain, bool block)
+ {
+ evp.reset();
+
+ keymaker = new DSAKeyMaker(domain, !block ? this : 0);
+ wasBlocking = block;
+ if (block) {
+ keymaker->run();
+ km_finished();
+ } else {
+ connect(keymaker, SIGNAL(finished()), SLOT(km_finished()));
+ keymaker->start();
+ }
+ }
+
+ virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x)
+ {
+ evp.reset();
+
+ DSA *dsa = DSA_new();
+ BIGNUM *bnp = bi2bn(domain.p());
+ BIGNUM *bnq = bi2bn(domain.q());
+ BIGNUM *bng = bi2bn(domain.g());
+ BIGNUM *bnpub_key = bi2bn(y);
+ BIGNUM *bnpriv_key = bi2bn(x);
+
+ if (!DSA_set0_pqg(dsa, bnp, bnq, bng)
+ || !DSA_set0_key(dsa, bnpub_key, bnpriv_key)) {
+ DSA_free(dsa);
+ return;
+ }
+
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DSA(evp.pkey, dsa);
+ sec = true;
+ }
+
+ virtual void createPublic(const DLGroup &domain, const BigInteger &y)
+ {
+ evp.reset();
+
+ DSA *dsa = DSA_new();
+ BIGNUM *bnp = bi2bn(domain.p());
+ BIGNUM *bnq = bi2bn(domain.q());
+ BIGNUM *bng = bi2bn(domain.g());
+ BIGNUM *bnpub_key = bi2bn(y);
+
+ if (!DSA_set0_pqg(dsa, bnp, bnq, bng)
+ || !DSA_set0_key(dsa, bnpub_key, NULL)) {
+ DSA_free(dsa);
+ return;
+ }
+
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DSA(evp.pkey, dsa);
+ sec = false;
+ }
+
+ virtual DLGroup domain() const
+ {
+ DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey);
+ const BIGNUM *bnp, *bnq, *bng;
+ DSA_get0_pqg(dsa, &bnp, &bnq, &bng);
+ return DLGroup(bn2bi(bnp), bn2bi(bnq), bn2bi(bng));
+ }
+
+ virtual BigInteger y() const
+ {
+ DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey);
+ const BIGNUM *bnpub_key;
+ DSA_get0_key(dsa, &bnpub_key, NULL);
+ return bn2bi(bnpub_key);
+ }
+
+ virtual BigInteger x() const
+ {
+ DSA *dsa = EVP_PKEY_get0_DSA(evp.pkey);
+ const BIGNUM *bnpriv_key;
+ DSA_get0_key(dsa, NULL, &bnpriv_key);
+ return bn2bi(bnpriv_key);
+ }
+
+private slots:
+ void km_finished()
+ {
+ DSA *dsa = keymaker->takeResult();
+ if (wasBlocking) {
+ delete keymaker;
+ } else {
+ keymaker->deleteLater();
+ }
+ keymaker = 0;
+
+ if (dsa) {
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DSA(evp.pkey, dsa);
+ sec = true;
+ }
+
+ if (!wasBlocking) {
+ emit finished();
+ }
+ }
+};
//----------------------------------------------------------------------------
-// MyCAContext
+// DHKey
//----------------------------------------------------------------------------
-// Thanks to Pascal Patry
-class MyCAContext : public CAContext
+class DHKeyMaker : public QThread
{
+ Q_OBJECT
public:
- X509Item caCert;
- MyPKeyContext *privateKey;
-
- MyCAContext(Provider *p) : CAContext(p)
- {
- privateKey = 0;
- }
-
- MyCAContext(const MyCAContext &from) : CAContext(from), caCert(from.caCert)
- {
- privateKey = static_cast<MyPKeyContext*>(from.privateKey -> clone());
- }
-
- ~MyCAContext()
- {
- delete privateKey;
- }
-
- virtual CertContext *certificate() const
- {
- MyCertContext *cert = new MyCertContext(provider());
-
- cert->fromX509(caCert.cert);
- return cert;
- }
-
- virtual CertContext *createCertificate(const PKeyContext &pub, const CertificateOptions &opts) const
- {
- // TODO: implement
- Q_UNUSED(pub)
- Q_UNUSED(opts)
- return 0;
- }
-
- virtual CRLContext *createCRL(const QDateTime &nextUpdate) const
- {
- // TODO: implement
- Q_UNUSED(nextUpdate)
- return 0;
- }
-
- virtual void setup(const CertContext &cert, const PKeyContext &priv)
- {
- caCert = static_cast<const MyCertContext&>(cert).item;
- delete privateKey;
- privateKey = 0;
- privateKey = static_cast<MyPKeyContext*>(priv.clone());
- }
-
- virtual CertContext *signRequest(const CSRContext &req, const QDateTime &notValidAfter) const
- {
- MyCertContext *cert = 0;
- const EVP_MD *md = 0;
- X509 *x = 0;
- const CertContextProps &props = *req.props();
- CertificateOptions subjectOpts;
- X509_NAME *subjectName = 0;
- X509_EXTENSION *ex = 0;
-
- if(privateKey -> key()->type() == PKey::RSA)
- md = EVP_sha1();
- else if(privateKey -> key()->type() == PKey::DSA)
- md = EVP_sha1();
- else
- return 0;
-
- cert = new MyCertContext(provider());
-
- subjectOpts.setInfoOrdered(props.subject);
- subjectName = new_cert_name(subjectOpts.info());
-
- // create
- x = X509_new();
- X509_set_version(x, 2);
-
- // serial
- BIGNUM *bn = bi2bn(props.serial);
- BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(x));
- BN_free(bn);
-
- // validity period
- ASN1_TIME_set(X509_get_notBefore(x), QDateTime::currentDateTime().toUTC().toTime_t());
- ASN1_TIME_set(X509_get_notAfter(x), notValidAfter.toTime_t());
-
- X509_set_pubkey(x, static_cast<const MyPKeyContext*>(req.subjectPublicKey()) -> get_pkey());
- X509_set_subject_name(x, subjectName);
- X509_set_issuer_name(x, X509_get_subject_name(caCert.cert));
-
- // subject key id
- ex = new_subject_key_id(x);
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // CA mode
- ex = new_basic_constraints(props.isCA, props.pathLimit);
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // subject alt name
- ex = new_cert_subject_alt_name(subjectOpts.info());
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // key usage
- ex = new_cert_key_usage(props.constraints);
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // extended key usage
- ex = new_cert_ext_key_usage(props.constraints);
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- // policies
- ex = new_cert_policies(props.policies);
- if(ex)
- {
- X509_add_ext(x, ex, -1);
- X509_EXTENSION_free(ex);
- }
-
- if(!X509_sign(x, privateKey->get_pkey(), md))
- {
- X509_free(x);
- delete cert;
- return 0;
- }
-
- cert->fromX509(x);
- X509_free(x);
- return cert;
- }
-
- virtual CRLContext *updateCRL(const CRLContext &crl, const QList<CRLEntry> &entries, const QDateTime &nextUpdate) const
- {
- // TODO: implement
- Q_UNUSED(crl)
- Q_UNUSED(entries)
- Q_UNUSED(nextUpdate)
- return 0;
- }
-
- virtual Provider::Context *clone() const
- {
- return new MyCAContext(*this);
- }
+ DLGroup domain;
+ DH *result;
+
+ DHKeyMaker(const DLGroup &_domain, QObject *parent = 0) : QThread(parent), domain(_domain), result(0)
+ {
+ }
+
+ ~DHKeyMaker()
+ {
+ wait();
+ if (result) {
+ DH_free(result);
+ }
+ }
+
+ virtual void run()
+ {
+ DH *dh = DH_new();
+ BIGNUM *bnp = bi2bn(domain.p());
+ BIGNUM *bng = bi2bn(domain.g());
+ if (!DH_set0_pqg(dh, bnp, NULL, bng)
+ || !DH_generate_key(dh)) {
+ DH_free(dh);
+ return;
+ }
+ result = dh;
+ }
+
+ DH *takeResult()
+ {
+ DH *dh = result;
+ result = 0;
+ return dh;
+ }
};
-//----------------------------------------------------------------------------
-// MyCSRContext
-//----------------------------------------------------------------------------
-class MyCSRContext : public CSRContext
+class DHKey : public DHContext
{
+ Q_OBJECT
public:
- X509Item item;
- CertContextProps _props;
-
- MyCSRContext(Provider *p) : CSRContext(p)
- {
- }
-
- MyCSRContext(const MyCSRContext &from) : CSRContext(from), item(from.item), _props(from._props)
- {
- }
-
- virtual Provider::Context *clone() const
- {
- return new MyCSRContext(*this);
- }
-
- virtual QByteArray toDER() const
- {
- return item.toDER();
- }
-
- virtual QString toPEM() const
- {
- return item.toPEM();
- }
-
- virtual ConvertResult fromDER(const QByteArray &a)
- {
- _props = CertContextProps();
- ConvertResult r = item.fromDER(a, X509Item::TypeReq);
- if(r == ConvertGood)
- make_props();
- return r;
- }
-
- virtual ConvertResult fromPEM(const QString &s)
- {
- _props = CertContextProps();
- ConvertResult r = item.fromPEM(s, X509Item::TypeReq);
- if(r == ConvertGood)
- make_props();
- return r;
- }
-
- virtual bool canUseFormat(CertificateRequestFormat f) const
- {
- if(f == PKCS10)
- return true;
- return false;
- }
-
- virtual bool createRequest(const CertificateOptions &opts, const PKeyContext &priv)
- {
- _props = CertContextProps();
- item.reset();
-
- CertificateInfo info = opts.info();
-
- // Note: removing default constraints, let the app choose these if it wants
- Constraints constraints = opts.constraints();
- // constraints - logic from Botan
- /*Constraints constraints;
- if(opts.isCA())
- {
- constraints += KeyCertificateSign;
- constraints += CRLSign;
- }
- else
- constraints = find_constraints(priv, opts.constraints());*/
-
- EVP_PKEY *pk = static_cast<const MyPKeyContext *>(&priv)->get_pkey();
- X509_EXTENSION *ex;
-
- const EVP_MD *md;
- if(priv.key()->type() == PKey::RSA)
- md = EVP_sha1();
- else if(priv.key()->type() == PKey::DSA)
- md = EVP_sha1();
- else
- return false;
-
- // create
- X509_REQ *x = X509_REQ_new();
-
- // public key
- X509_REQ_set_pubkey(x, pk);
-
- // subject
- X509_NAME *name = new_cert_name(info);
- X509_REQ_set_subject_name(x, name);
-
- // challenge
- QByteArray cs = opts.challenge().toLatin1();
- if(!cs.isEmpty())
- X509_REQ_add1_attr_by_NID(x, NID_pkcs9_challengePassword, MBSTRING_UTF8, (const unsigned char *)cs.data(), -1);
-
- STACK_OF(X509_EXTENSION) *exts = sk_X509_EXTENSION_new_null();
-
- // CA mode
- ex = new_basic_constraints(opts.isCA(), opts.pathLimit());
- if(ex)
- sk_X509_EXTENSION_push(exts, ex);
-
- // subject alt name
- ex = new_cert_subject_alt_name(info);
- if(ex)
- sk_X509_EXTENSION_push(exts, ex);
-
- // key usage
- ex = new_cert_key_usage(constraints);
- if(ex)
- sk_X509_EXTENSION_push(exts, ex);
-
- // extended key usage
- ex = new_cert_ext_key_usage(constraints);
- if(ex)
- sk_X509_EXTENSION_push(exts, ex);
-
- // policies
- ex = new_cert_policies(opts.policies());
- if(ex)
- sk_X509_EXTENSION_push(exts, ex);
-
- if(sk_X509_EXTENSION_num(exts) > 0)
- X509_REQ_add_extensions(x, exts);
- sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
-
- // finished
- X509_REQ_sign(x, pk, md);
-
- item.req = x;
- make_props();
- return true;
- }
-
- virtual const CertContextProps *props() const
- {
- return &_props;
- }
-
- virtual bool compare(const CSRContext *other) const
- {
- const CertContextProps *a = &_props;
- const CertContextProps *b = other->props();
-
- PublicKey akey, bkey;
- PKeyContext *ac = subjectPublicKey();
- akey.change(ac);
- PKeyContext *bc = other->subjectPublicKey();
- bkey.change(bc);
-
- if(a->sig != b->sig || a->sigalgo != b->sigalgo || akey != bkey)
- return false;
-
- // TODO: Anything else we should compare?
-
- return true;
- }
-
- virtual PKeyContext *subjectPublicKey() const // does a new
- {
- MyPKeyContext *kc = new MyPKeyContext(provider());
- EVP_PKEY *pkey = X509_REQ_get_pubkey(item.req);
- PKeyBase *kb = kc->pkeyToBase(pkey, false);
- kc->setKey(kb);
- return kc;
- }
-
- virtual QString toSPKAC() const
- {
- return QString();
- }
-
- virtual ConvertResult fromSPKAC(const QString &s)
- {
- Q_UNUSED(s);
- return ErrorDecode;
- }
-
- void make_props()
- {
- X509_REQ *x = item.req;
- CertContextProps p;
-
- // TODO: QString challenge;
-
- p.format = PKCS10;
-
- CertificateInfo subject;
-
- subject = get_cert_name(X509_REQ_get_subject_name(x));
-
- STACK_OF(X509_EXTENSION) *exts = X509_REQ_get_extensions(x);
-
- p.isCA = false;
- p.pathLimit = 0;
- int pos = X509v3_get_ext_by_NID(exts, NID_basic_constraints, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
- if(ex)
- get_basic_constraints(ex, &p.isCA, &p.pathLimit);
- }
-
- pos = X509v3_get_ext_by_NID(exts, NID_subject_alt_name, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
- if(ex)
- subject.unite(get_cert_alt_name(ex));
- }
-
- pos = X509v3_get_ext_by_NID(exts, NID_key_usage, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
- if(ex)
- p.constraints = get_cert_key_usage(ex);
- }
-
- pos = X509v3_get_ext_by_NID(exts, NID_ext_key_usage, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
- if(ex)
- p.constraints += get_cert_ext_key_usage(ex);
- }
-
- pos = X509v3_get_ext_by_NID(exts, NID_certificate_policies, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
- if(ex)
- p.policies = get_cert_policies(ex);
- }
-
- sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
-
- const ASN1_BIT_STRING *signature;
-
- X509_REQ_get0_signature(x, &signature, NULL);
- if(signature)
- {
- p.sig = QByteArray(signature->length, 0);
- for (int i=0; i< signature->length; i++)
- p.sig[i] = signature->data[i];
- }
-
- switch( X509_REQ_get_signature_nid(x) )
- {
- case NID_sha1WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA1;
- break;
- case NID_md5WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_MD5;
- break;
-#ifdef HAVE_OPENSSL_MD2
- case NID_md2WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_MD2;
- break;
-#endif
- case NID_ripemd160WithRSA:
- p.sigalgo = QCA::EMSA3_RIPEMD160;
- break;
- case NID_dsaWithSHA1:
- p.sigalgo = QCA::EMSA1_SHA1;
- break;
- default:
- qDebug() << "Unknown signature value: " << X509_REQ_get_signature_nid(x);
- p.sigalgo = QCA::SignatureUnknown;
- }
-
- // FIXME: super hack
- CertificateOptions opts;
- opts.setInfo(subject);
- p.subject = opts.infoOrdered();
-
- _props = p;
- }
-};
+ EVPKey evp;
+ DHKeyMaker *keymaker;
+ bool wasBlocking;
+ bool sec;
+
+ DHKey(Provider *p) : DHContext(p)
+ {
+ keymaker = 0;
+ sec = false;
+ }
+
+ DHKey(const DHKey &from) : DHContext(from.provider()), evp(from.evp)
+ {
+ keymaker = 0;
+ sec = from.sec;
+ }
+
+ ~DHKey()
+ {
+ delete keymaker;
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new DHKey(*this);
+ }
+
+ virtual bool isNull() const
+ {
+ return (evp.pkey ? false : true);
+ }
+
+ virtual PKey::Type type() const
+ {
+ return PKey::DH;
+ }
+
+ virtual bool isPrivate() const
+ {
+ return sec;
+ }
+
+ virtual bool canExport() const
+ {
+ return true;
+ }
+
+ virtual void convertToPublic()
+ {
+ if (!sec) {
+ return;
+ }
+
+ DH *orig = EVP_PKEY_get0_DH(evp.pkey);
+ DH *dh = DH_new();
+ const BIGNUM *bnp, *bng, *bnpub_key;
+ DH_get0_pqg(orig, &bnp, NULL, &bng);
+ DH_get0_key(orig, &bnpub_key, NULL);
+
+ DH_set0_key(dh, BN_dup(bnpub_key), NULL);
+ DH_set0_pqg(dh, BN_dup(bnp), NULL, BN_dup(bng));
+
+ evp.reset();
+
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DH(evp.pkey, dh);
+ sec = false;
+ }
+
+ virtual int bits() const
+ {
+ return EVP_PKEY_bits(evp.pkey);
+ }
+
+ virtual SymmetricKey deriveKey(const PKeyBase &theirs)
+ {
+ DH *dh = EVP_PKEY_get0_DH(evp.pkey);
+ DH *them = EVP_PKEY_get0_DH(static_cast<const DHKey *>(&theirs)->evp.pkey);
+ const BIGNUM *bnpub_key;
+ DH_get0_key(them, &bnpub_key, NULL);
+
+ SecureArray result(DH_size(dh));
+ int ret = DH_compute_key((unsigned char *)result.data(), bnpub_key, dh);
+ if (ret <= 0) {
+ return SymmetricKey();
+ }
+ result.resize(ret);
+ return SymmetricKey(result);
+ }
+
+ virtual void createPrivate(const DLGroup &domain, bool block)
+ {
+ evp.reset();
+
+ keymaker = new DHKeyMaker(domain, !block ? this : 0);
+ wasBlocking = block;
+ if (block) {
+ keymaker->run();
+ km_finished();
+ } else {
+ connect(keymaker, SIGNAL(finished()), SLOT(km_finished()));
+ keymaker->start();
+ }
+ }
+
+ virtual void createPrivate(const DLGroup &domain, const BigInteger &y, const BigInteger &x)
+ {
+ evp.reset();
+
+ DH *dh = DH_new();
+ BIGNUM *bnp = bi2bn(domain.p());
+ BIGNUM *bng = bi2bn(domain.g());
+ BIGNUM *bnpub_key = bi2bn(y);
+ BIGNUM *bnpriv_key = bi2bn(x);
+
+ if (!DH_set0_key(dh, bnpub_key, bnpriv_key)
+ || !DH_set0_pqg(dh, bnp, NULL, bng)) {
+ DH_free(dh);
+ return;
+ }
+
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DH(evp.pkey, dh);
+ sec = true;
+ }
+
+ virtual void createPublic(const DLGroup &domain, const BigInteger &y)
+ {
+ evp.reset();
+
+ DH *dh = DH_new();
+ BIGNUM *bnp = bi2bn(domain.p());
+ BIGNUM *bng = bi2bn(domain.g());
+ BIGNUM *bnpub_key = bi2bn(y);
+
+ if (!DH_set0_key(dh, bnpub_key, NULL)
+ || !DH_set0_pqg(dh, bnp, NULL, bng)) {
+ DH_free(dh);
+ return;
+ }
+
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DH(evp.pkey, dh);
+ sec = false;
+ }
+
+ virtual DLGroup domain() const
+ {
+ DH *dh = EVP_PKEY_get0_DH(evp.pkey);
+ const BIGNUM *bnp, *bng;
+ DH_get0_pqg(dh, &bnp, NULL, &bng);
+ return DLGroup(bn2bi(bnp), bn2bi(bng));
+ }
+
+ virtual BigInteger y() const
+ {
+ DH *dh = EVP_PKEY_get0_DH(evp.pkey);
+ const BIGNUM *bnpub_key;
+ DH_get0_key(dh, &bnpub_key, NULL);
+ return bn2bi(bnpub_key);
+ }
+
+ virtual BigInteger x() const
+ {
+ DH *dh = EVP_PKEY_get0_DH(evp.pkey);
+ const BIGNUM *bnpriv_key;
+ DH_get0_key(dh, NULL, &bnpriv_key);
+ return bn2bi(bnpriv_key);
+ }
+
+private slots:
+ void km_finished()
+ {
+ DH *dh = keymaker->takeResult();
+ if (wasBlocking) {
+ delete keymaker;
+ } else {
+ keymaker->deleteLater();
+ }
+ keymaker = 0;
+
+ if (dh) {
+ evp.pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_DH(evp.pkey, dh);
+ sec = true;
+ }
+
+ if (!wasBlocking) {
+ emit finished();
+ }
+ }
+};
+
+//----------------------------------------------------------------------------
+// QCA-based RSA_METHOD
+//----------------------------------------------------------------------------
+
+// only supports EMSA3_Raw for now
+class QCA_RSA_METHOD
+{
+public:
+ RSAPrivateKey key;
+
+ QCA_RSA_METHOD(RSAPrivateKey _key, RSA *rsa)
+ {
+ key = _key;
+ RSA_set_method(rsa, rsa_method());
+#ifndef OSSL_110
+ rsa->flags |= RSA_FLAG_SIGN_VER;
+#endif
+ RSA_set_app_data(rsa, this);
+ BIGNUM *bnn = bi2bn(_key.n());
+ BIGNUM *bne = bi2bn(_key.e());
+
+ RSA_set0_key(rsa, bnn, bne, NULL);
+ }
+
+ RSA_METHOD *rsa_method()
+ {
+ static RSA_METHOD *ops = 0;
+
+ if (!ops) {
+ ops = RSA_meth_dup(RSA_get_default_method());
+ RSA_meth_set_priv_enc(ops, NULL); //pkcs11_rsa_encrypt
+ RSA_meth_set_priv_dec(ops, rsa_priv_dec); //pkcs11_rsa_encrypt
+#ifdef OSSL_110
+ RSA_meth_set_sign(ops, NULL);
+#else
+ RSA_meth_set_sign(ops, rsa_sign);
+#endif
+ RSA_meth_set_verify(ops, NULL); //pkcs11_rsa_verify
+ RSA_meth_set_finish(ops, rsa_finish);
+ }
+ return ops;
+ }
+
+ static int rsa_priv_dec(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding)
+ {
+ QCA::EncryptionAlgorithm algo;
+
+ if (padding == RSA_PKCS1_PADDING) {
+ algo = QCA::EME_PKCS1v15;
+ } else if (padding == RSA_PKCS1_OAEP_PADDING) {
+ algo = QCA::EME_PKCS1_OAEP;
+ } else {
+ RSAerr(RSA_F_RSA_EAY_PRIVATE_DECRYPT, RSA_R_UNKNOWN_PADDING_TYPE);
+ return -1;
+ }
+
+ QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa);
+
+ QCA::SecureArray input;
+ input.resize(flen);
+ memcpy(input.data(), from, input.size());
+
+ QCA::SecureArray output;
+
+ if (self->key.decrypt(input, &output, algo)) {
+ memcpy(to, output.data(), output.size());
+ return output.size();
+ }
+
+ // XXX: An error should be set in this case too.
+ return -1;
+ }
+
+#ifndef OSSL_110
+ static int rsa_sign(int type, const unsigned char *m, unsigned int m_len, unsigned char *sigret, unsigned int *siglen, const RSA *rsa)
+ {
+ QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa);
+
+ // TODO: this is disgusting
+
+ unsigned char *p, *tmps = NULL;
+ const unsigned char *s = NULL;
+ int i, j;
+ j = 0;
+
+ if (type == NID_md5_sha1) {
+ } else {
+ // make X509 packet
+ X509_SIG sig;
+ ASN1_TYPE parameter;
+
+ X509_ALGOR algor;
+ ASN1_OCTET_STRING digest;
+ int rsa_size = RSA_size(rsa);
+ //int rsa_size = 128;
+ //CK_ULONG sigsize = rsa_size;
+
+ sig.algor = &algor;
+ sig.algor->algorithm = OBJ_nid2obj(type);
+ if (sig.algor->algorithm == NULL) {
+ //RSAerr(RSA_F_RSA_SIGN,RSA_R_UNKNOWN_ALGORITHM_TYPE);
+ return 0;
+ }
+ if (sig.algor->algorithm->length == 0) {
+ //RSAerr(RSA_F_RSA_SIGN,RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD);
+ return 0;
+ }
+ parameter.type = V_ASN1_NULL;
+ parameter.value.ptr = NULL;
+ sig.algor->parameter = &parameter;
+
+ sig.digest = &digest;
+ sig.digest->data = (unsigned char *)m; /* TMP UGLY CAST */
+ sig.digest->length = m_len;
+
+ i = i2d_X509_SIG(&sig, NULL);
+
+ j = rsa_size;
+ if (i > (j - RSA_PKCS1_PADDING_SIZE)) {
+ //RSAerr(RSA_F_RSA_SIGN,RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY);
+ return 0;
+ }
+
+ tmps = (unsigned char *)OPENSSL_malloc((unsigned int)j + 1);
+ if (tmps == NULL) {
+ //RSAerr(RSA_F_RSA_SIGN,ERR_R_MALLOC_FAILURE);
+ return 0;
+ }
+ p = tmps;
+ i2d_X509_SIG(&sig, &p);
+ s = tmps;
+ m = s;
+ m_len = i;
+ }
+
+ SecureArray input;
+ input.resize(m_len);
+ memcpy(input.data(), m, input.size());
+ SecureArray result = self->key.signMessage(input, EMSA3_Raw);
+
+ if (tmps) {
+ OPENSSL_cleanse(tmps, (unsigned int)j + 1);
+ OPENSSL_free(tmps);
+ }
+
+ // TODO: even though we return error here, PKCS7_sign will
+ // not return error. what gives?
+ if (result.isEmpty()) {
+ return 0;
+ }
+
+ memcpy(sigret, result.data(), result.size());
+ *siglen = result.size();
+
+ return 1;
+ }
+#endif
+
+ static int rsa_finish(RSA *rsa)
+ {
+ QCA_RSA_METHOD *self = (QCA_RSA_METHOD *)RSA_get_app_data(rsa);
+ delete self;
+ return 1;
+ }
+};
+
+static RSA *createFromExisting(const RSAPrivateKey &key)
+{
+ RSA *r = RSA_new();
+ new QCA_RSA_METHOD(key, r); // will delete itself on RSA_free
+ return r;
+}
+
+//----------------------------------------------------------------------------
+// MyPKeyContext
+//----------------------------------------------------------------------------
+class MyPKeyContext : public PKeyContext
+{
+public:
+ PKeyBase *k;
+
+ MyPKeyContext(Provider *p) : PKeyContext(p)
+ {
+ k = 0;
+ }
+
+ ~MyPKeyContext()
+ {
+ delete k;
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ MyPKeyContext *c = new MyPKeyContext(*this);
+ c->k = (PKeyBase *)k->clone();
+ return c;
+ }
+
+ virtual QList<PKey::Type> supportedTypes() const
+ {
+ QList<PKey::Type> list;
+ list += PKey::RSA;
+ list += PKey::DSA;
+ list += PKey::DH;
+ return list;
+ }
+
+ virtual QList<PKey::Type> supportedIOTypes() const
+ {
+ QList<PKey::Type> list;
+ list += PKey::RSA;
+ list += PKey::DSA;
+ return list;
+ }
+
+ virtual QList<PBEAlgorithm> supportedPBEAlgorithms() const
+ {
+ QList<PBEAlgorithm> list;
+ list += PBES2_DES_SHA1;
+ list += PBES2_TripleDES_SHA1;
+ return list;
+ }
+
+ virtual PKeyBase *key()
+ {
+ return k;
+ }
+
+ virtual const PKeyBase *key() const
+ {
+ return k;
+ }
+
+ virtual void setKey(PKeyBase *key)
+ {
+ k = key;
+ }
+
+ virtual bool importKey(const PKeyBase *key)
+ {
+ Q_UNUSED(key);
+ return false;
+ }
+
+ EVP_PKEY *get_pkey() const
+ {
+ PKey::Type t = k->type();
+ if (t == PKey::RSA) {
+ return static_cast<RSAKey *>(k)->evp.pkey;
+ } else if (t == PKey::DSA) {
+ return static_cast<DSAKey *>(k)->evp.pkey;
+ } else {
+ return static_cast<DHKey *>(k)->evp.pkey;
+ }
+ }
+
+ PKeyBase *pkeyToBase(EVP_PKEY *pkey, bool sec) const
+ {
+ PKeyBase *nk = 0;
+ int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
+ if (pkey_type == EVP_PKEY_RSA) {
+ RSAKey *c = new RSAKey(provider());
+ c->evp.pkey = pkey;
+ c->sec = sec;
+ nk = c;
+ } else if (pkey_type == EVP_PKEY_DSA) {
+ DSAKey *c = new DSAKey(provider());
+ c->evp.pkey = pkey;
+ c->sec = sec;
+ nk = c;
+ } else if (pkey_type == EVP_PKEY_DH) {
+ DHKey *c = new DHKey(provider());
+ c->evp.pkey = pkey;
+ c->sec = sec;
+ nk = c;
+ } else {
+ EVP_PKEY_free(pkey);
+ }
+ return nk;
+ }
+
+ virtual QByteArray publicToDER() const
+ {
+ EVP_PKEY *pkey = get_pkey();
+
+ int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
+
+ // OpenSSL does not have DH import/export support
+ if (pkey_type == EVP_PKEY_DH) {
+ return QByteArray();
+ }
+
+ BIO *bo = BIO_new(BIO_s_mem());
+ i2d_PUBKEY_bio(bo, pkey);
+ QByteArray buf = bio2ba(bo);
+ return buf;
+ }
+
+ virtual QString publicToPEM() const
+ {
+ EVP_PKEY *pkey = get_pkey();
+
+ int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
+
+ // OpenSSL does not have DH import/export support
+ if (pkey_type == EVP_PKEY_DH) {
+ return QString();
+ }
+
+ BIO *bo = BIO_new(BIO_s_mem());
+ PEM_write_bio_PUBKEY(bo, pkey);
+ QByteArray buf = bio2ba(bo);
+ return QString::fromLatin1(buf);
+ }
+
+ virtual ConvertResult publicFromDER(const QByteArray &in)
+ {
+ delete k;
+ k = 0;
+
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ EVP_PKEY *pkey = d2i_PUBKEY_bio(bi, NULL);
+ BIO_free(bi);
+
+ if (!pkey) {
+ return ErrorDecode;
+ }
+
+ k = pkeyToBase(pkey, false);
+ if (k) {
+ return ConvertGood;
+ } else {
+ return ErrorDecode;
+ }
+ }
+
+ virtual ConvertResult publicFromPEM(const QString &s)
+ {
+ delete k;
+ k = 0;
+
+ QByteArray in = s.toLatin1();
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ EVP_PKEY *pkey = PEM_read_bio_PUBKEY(bi, NULL, passphrase_cb, NULL);
+ BIO_free(bi);
+
+ if (!pkey) {
+ return ErrorDecode;
+ }
+
+ k = pkeyToBase(pkey, false);
+ if (k) {
+ return ConvertGood;
+ } else {
+ return ErrorDecode;
+ }
+ }
+
+ virtual SecureArray privateToDER(const SecureArray &passphrase, PBEAlgorithm pbe) const
+ {
+ //if(pbe == PBEDefault)
+ // pbe = PBES2_TripleDES_SHA1;
+
+ const EVP_CIPHER *cipher = 0;
+ if (pbe == PBES2_TripleDES_SHA1) {
+ cipher = EVP_des_ede3_cbc();
+ } else if (pbe == PBES2_DES_SHA1) {
+ cipher = EVP_des_cbc();
+ }
+
+ if (!cipher) {
+ return SecureArray();
+ }
+
+ EVP_PKEY *pkey = get_pkey();
+ int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
+
+ // OpenSSL does not have DH import/export support
+ if (pkey_type == EVP_PKEY_DH) {
+ return SecureArray();
+ }
+
+ BIO *bo = BIO_new(BIO_s_mem());
+ if (!passphrase.isEmpty()) {
+ i2d_PKCS8PrivateKey_bio(bo, pkey, cipher, NULL, 0, NULL, (void *)passphrase.data());
+ } else {
+ i2d_PKCS8PrivateKey_bio(bo, pkey, NULL, NULL, 0, NULL, NULL);
+ }
+ SecureArray buf = bio2buf(bo);
+ return buf;
+ }
+
+ virtual QString privateToPEM(const SecureArray &passphrase, PBEAlgorithm pbe) const
+ {
+ //if(pbe == PBEDefault)
+ // pbe = PBES2_TripleDES_SHA1;
+
+ const EVP_CIPHER *cipher = 0;
+ if (pbe == PBES2_TripleDES_SHA1) {
+ cipher = EVP_des_ede3_cbc();
+ } else if (pbe == PBES2_DES_SHA1) {
+ cipher = EVP_des_cbc();
+ }
+
+ if (!cipher) {
+ return QString();
+ }
+
+ EVP_PKEY *pkey = get_pkey();
+ int pkey_type = EVP_PKEY_type(EVP_PKEY_id(pkey));
+
+ // OpenSSL does not have DH import/export support
+ if (pkey_type == EVP_PKEY_DH) {
+ return QString();
+ }
+
+ BIO *bo = BIO_new(BIO_s_mem());
+ if (!passphrase.isEmpty()) {
+ PEM_write_bio_PKCS8PrivateKey(bo, pkey, cipher, NULL, 0, NULL, (void *)passphrase.data());
+ } else {
+ PEM_write_bio_PKCS8PrivateKey(bo, pkey, NULL, NULL, 0, NULL, NULL);
+ }
+ SecureArray buf = bio2buf(bo);
+ return QString::fromLatin1(buf.toByteArray());
+ }
+
+ virtual ConvertResult privateFromDER(const SecureArray &in, const SecureArray &passphrase)
+ {
+ delete k;
+ k = 0;
+
+ EVP_PKEY *pkey;
+ if (!passphrase.isEmpty()) {
+ pkey = qca_d2i_PKCS8PrivateKey(in, NULL, NULL, (void *)passphrase.data());
+ } else {
+ pkey = qca_d2i_PKCS8PrivateKey(in, NULL, passphrase_cb, NULL);
+ }
+
+ if (!pkey) {
+ return ErrorDecode;
+ }
+
+ k = pkeyToBase(pkey, true);
+ if (k) {
+ return ConvertGood;
+ } else {
+ return ErrorDecode;
+ }
+ }
+
+ virtual ConvertResult privateFromPEM(const QString &s, const SecureArray &passphrase)
+ {
+ delete k;
+ k = 0;
+
+ QByteArray in = s.toLatin1();
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ EVP_PKEY *pkey;
+ if (!passphrase.isEmpty()) {
+ pkey = PEM_read_bio_PrivateKey(bi, NULL, NULL, (void *)passphrase.data());
+ } else {
+ pkey = PEM_read_bio_PrivateKey(bi, NULL, passphrase_cb, NULL);
+ }
+ BIO_free(bi);
+
+ if (!pkey) {
+ return ErrorDecode;
+ }
+
+ k = pkeyToBase(pkey, true);
+ if (k) {
+ return ConvertGood;
+ } else {
+ return ErrorDecode;
+ }
+ }
+};
+
+//----------------------------------------------------------------------------
+// MyCertContext
+//----------------------------------------------------------------------------
+class X509Item
+{
+public:
+ X509 *cert;
+ X509_REQ *req;
+ X509_CRL *crl;
+
+ enum Type { TypeCert, TypeReq, TypeCRL };
+
+ X509Item()
+ {
+ cert = 0;
+ req = 0;
+ crl = 0;
+ }
+
+ X509Item(const X509Item &from)
+ {
+ cert = 0;
+ req = 0;
+ crl = 0;
+ *this = from;
+ }
+
+ ~X509Item()
+ {
+ reset();
+ }
+
+ X509Item &operator=(const X509Item &from)
+ {
+ if (this != &from) {
+ reset();
+ cert = from.cert;
+ req = from.req;
+ crl = from.crl;
+
+ if (cert) {
+ X509_up_ref(cert);
+ }
+ if (req) {
+#ifdef OSSL_110
+ // Not exposed, so copy
+ req = X509_REQ_dup(req);
+#else
+ CRYPTO_add(&req->references, 1, CRYPTO_LOCK_X509_REQ);
+#endif
+ }
+ if (crl) {
+ X509_CRL_up_ref(crl);
+ }
+ }
+
+ return *this;
+ }
+
+ void reset()
+ {
+ if (cert) {
+ X509_free(cert);
+ cert = 0;
+ }
+ if (req) {
+ X509_REQ_free(req);
+ req = 0;
+ }
+ if (crl) {
+ X509_CRL_free(crl);
+ crl = 0;
+ }
+ }
+
+ bool isNull() const
+ {
+ return (!cert && !req && !crl);
+ }
+
+ QByteArray toDER() const
+ {
+ BIO *bo = BIO_new(BIO_s_mem());
+ if (cert) {
+ i2d_X509_bio(bo, cert);
+ } else if (req) {
+ i2d_X509_REQ_bio(bo, req);
+ } else if (crl) {
+ i2d_X509_CRL_bio(bo, crl);
+ }
+ QByteArray buf = bio2ba(bo);
+ return buf;
+ }
+
+ QString toPEM() const
+ {
+ BIO *bo = BIO_new(BIO_s_mem());
+ if (cert) {
+ PEM_write_bio_X509(bo, cert);
+ } else if (req) {
+ PEM_write_bio_X509_REQ(bo, req);
+ } else if (crl) {
+ PEM_write_bio_X509_CRL(bo, crl);
+ }
+ QByteArray buf = bio2ba(bo);
+ return QString::fromLatin1(buf);
+ }
+
+ ConvertResult fromDER(const QByteArray &in, Type t)
+ {
+ reset();
+
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+
+ if (t == TypeCert) {
+ cert = d2i_X509_bio(bi, NULL);
+ } else if (t == TypeReq) {
+ req = d2i_X509_REQ_bio(bi, NULL);
+ } else if (t == TypeCRL) {
+ crl = d2i_X509_CRL_bio(bi, NULL);
+ }
+
+ BIO_free(bi);
+
+ if (isNull()) {
+ return ErrorDecode;
+ }
+
+ return ConvertGood;
+ }
+
+ ConvertResult fromPEM(const QString &s, Type t)
+ {
+ reset();
+
+ QByteArray in = s.toLatin1();
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+
+ if (t == TypeCert) {
+ cert = PEM_read_bio_X509(bi, NULL, passphrase_cb, NULL);
+ } else if (t == TypeReq) {
+ req = PEM_read_bio_X509_REQ(bi, NULL, passphrase_cb, NULL);
+ } else if (t == TypeCRL) {
+ crl = PEM_read_bio_X509_CRL(bi, NULL, passphrase_cb, NULL);
+ }
+
+ BIO_free(bi);
+
+ if (isNull()) {
+ return ErrorDecode;
+ }
+
+ return ConvertGood;
+ }
+};
+
+// (taken from kdelibs) -- Justin
+//
+// This code is mostly taken from OpenSSL v0.9.5a
+// by Eric Young
+QDateTime ASN1_UTCTIME_QDateTime(const ASN1_UTCTIME *tm, int *isGmt)
+{
+ QDateTime qdt;
+ char *v;
+ int gmt = 0;
+ int i;
+ int y = 0, M = 0, d = 0, h = 0, m = 0, s = 0;
+ QDate qdate;
+ QTime qtime;
+
+ i = tm->length;
+ v = (char *)tm->data;
+
+ if (i < 10) {
+ goto auq_err;
+ }
+ if (v[i - 1] == 'Z') {
+ gmt = 1;
+ }
+ for (i = 0; i < 10; i++)
+ if ((v[i] > '9') || (v[i] < '0')) {
+ goto auq_err;
+ }
+ y = (v[0] - '0') * 10 + (v[1] - '0');
+ if (y < 50) {
+ y += 100;
+ }
+ M = (v[2] - '0') * 10 + (v[3] - '0');
+ if ((M > 12) || (M < 1)) {
+ goto auq_err;
+ }
+ d = (v[4] - '0') * 10 + (v[5] - '0');
+ h = (v[6] - '0') * 10 + (v[7] - '0');
+ m = (v[8] - '0') * 10 + (v[9] - '0');
+ if ((v[10] >= '0') && (v[10] <= '9') &&
+ (v[11] >= '0') && (v[11] <= '9')) {
+ s = (v[10] - '0') * 10 + (v[11] - '0');
+ }
+
+ // localize the date and display it.
+ qdate.setDate(y + 1900, M, d);
+ qtime.setHMS(h, m, s);
+ qdt.setDate(qdate); qdt.setTime(qtime);
+ if (gmt) {
+ qdt.setTimeSpec(Qt::UTC);
+ }
+auq_err:
+ if (isGmt) {
+ *isGmt = gmt;
+ }
+ return qdt;
+}
+
+class MyCertContext;
+static bool sameChain(STACK_OF(X509) *ossl, const QList<const MyCertContext *> &qca);
+
+// TODO: support read/write of multiple info values with the same name
+class MyCertContext : public CertContext
+{
+public:
+ X509Item item;
+ CertContextProps _props;
+
+ MyCertContext(Provider *p) : CertContext(p)
+ {
+ //printf("[%p] ** created\n", this);
+ }
+
+ MyCertContext(const MyCertContext &from) : CertContext(from), item(from.item), _props(from._props)
+ {
+ //printf("[%p] ** created as copy (from [%p])\n", this, &from);
+ }
+
+ ~MyCertContext()
+ {
+ //printf("[%p] ** deleted\n", this);
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new MyCertContext(*this);
+ }
+
+ virtual QByteArray toDER() const
+ {
+ return item.toDER();
+ }
+
+ virtual QString toPEM() const
+ {
+ return item.toPEM();
+ }
+
+ virtual ConvertResult fromDER(const QByteArray &a)
+ {
+ _props = CertContextProps();
+ ConvertResult r = item.fromDER(a, X509Item::TypeCert);
+ if (r == ConvertGood) {
+ make_props();
+ }
+ return r;
+ }
+
+ virtual ConvertResult fromPEM(const QString &s)
+ {
+ _props = CertContextProps();
+ ConvertResult r = item.fromPEM(s, X509Item::TypeCert);
+ if (r == ConvertGood) {
+ make_props();
+ }
+ return r;
+ }
+
+ void fromX509(X509 *x)
+ {
+ X509_up_ref(x);
+ item.cert = x;
+ make_props();
+ }
+
+ virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv)
+ {
+ _props = CertContextProps();
+ item.reset();
+
+ CertificateInfo info = opts.info();
+
+ // Note: removing default constraints, let the app choose these if it wants
+ Constraints constraints = opts.constraints();
+ // constraints - logic from Botan
+ /*Constraints constraints;
+ if(opts.isCA())
+ {
+ constraints += KeyCertificateSign;
+ constraints += CRLSign;
+ }
+ else
+ constraints = find_constraints(priv, opts.constraints());*/
+
+ EVP_PKEY *pk = static_cast<const MyPKeyContext *>(&priv)->get_pkey();
+ X509_EXTENSION *ex;
+
+ const EVP_MD *md;
+ if (priv.key()->type() == PKey::RSA) {
+ md = EVP_sha1();
+ } else if (priv.key()->type() == PKey::DSA) {
+ md = EVP_sha1();
+ } else {
+ return false;
+ }
+
+ // create
+ X509 *x = X509_new();
+ X509_set_version(x, 2);
+
+ // serial
+ BIGNUM *bn = bi2bn(opts.serialNumber());
+ BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(x));
+ BN_free(bn);
+
+ // validity period
+ ASN1_TIME_set(X509_get_notBefore(x), opts.notValidBefore().toTime_t());
+ ASN1_TIME_set(X509_get_notAfter(x), opts.notValidAfter().toTime_t());
+
+ // public key
+ X509_set_pubkey(x, pk);
+
+ // subject
+ X509_NAME *name = new_cert_name(info);
+ X509_set_subject_name(x, name);
+
+ // issuer == subject
+ X509_set_issuer_name(x, name);
+
+ // subject key id
+ ex = new_subject_key_id(x);
+ {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // CA mode
+ ex = new_basic_constraints(opts.isCA(), opts.pathLimit());
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // subject alt name
+ ex = new_cert_subject_alt_name(info);
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // key usage
+ ex = new_cert_key_usage(constraints);
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // extended key usage
+ ex = new_cert_ext_key_usage(constraints);
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // policies
+ ex = new_cert_policies(opts.policies());
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // finished
+ X509_sign(x, pk, md);
+
+ item.cert = x;
+ make_props();
+ return true;
+ }
+
+ virtual const CertContextProps *props() const
+ {
+ //printf("[%p] grabbing props\n", this);
+ return &_props;
+ }
+
+ virtual bool compare(const CertContext *other) const
+ {
+ const CertContextProps *a = &_props;
+ const CertContextProps *b = other->props();
+
+ PublicKey akey, bkey;
+ PKeyContext *ac = subjectPublicKey();
+ akey.change(ac);
+ PKeyContext *bc = other->subjectPublicKey();
+ bkey.change(bc);
+
+ // logic from Botan
+ if (a->sig != b->sig || a->sigalgo != b->sigalgo || akey != bkey) {
+ return false;
+ }
+
+ if (a->issuer != b->issuer || a->subject != b->subject) {
+ return false;
+ }
+ if (a->serial != b->serial || a->version != b->version) {
+ return false;
+ }
+ if (a->start != b->start || a->end != b->end) {
+ return false;
+ }
+
+ return true;
+ }
+
+ // does a new
+ virtual PKeyContext *subjectPublicKey() const
+ {
+ MyPKeyContext *kc = new MyPKeyContext(provider());
+ EVP_PKEY *pkey = X509_get_pubkey(item.cert);
+ PKeyBase *kb = kc->pkeyToBase(pkey, false);
+ kc->setKey(kb);
+ return kc;
+ }
+
+ virtual bool isIssuerOf(const CertContext *other) const
+ {
+
+ // to check a single issuer, we make a list of 1
+ STACK_OF(X509) *untrusted_list = sk_X509_new_null();
+
+ const MyCertContext *our_cc = this;
+ X509 *x = our_cc->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(untrusted_list, x);
+
+ const MyCertContext *other_cc = static_cast<const MyCertContext *>(other);
+ X509 *ox = other_cc->item.cert;
+
+ X509_STORE *store = X509_STORE_new();
+
+ X509_STORE_CTX *ctx = X509_STORE_CTX_new();
+ X509_STORE_CTX_init(ctx, store, ox, untrusted_list);
+
+ // we don't care about the verify result here
+ X509_verify_cert(ctx);
+
+ // grab the chain, which may not be fully populated
+ STACK_OF(X509) *chain = X509_STORE_CTX_get_chain(ctx);
+
+ bool ok = false;
+
+ // chain should be exactly 2 items
+ QList<const MyCertContext *> expected;
+ expected += other_cc;
+ expected += our_cc;
+ if (chain && sameChain(chain, expected)) {
+ ok = true;
+ }
+
+ // cleanup
+ X509_STORE_CTX_free(ctx);
+ X509_STORE_free(store);
+ sk_X509_pop_free(untrusted_list, X509_free);
+
+ return ok;
+ }
+
+ // implemented later because it depends on MyCRLContext
+ virtual Validity validate(const QList<CertContext *> &trusted, const QList<CertContext *> &untrusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const;
+
+ virtual Validity validate_chain(const QList<CertContext *> &chain, const QList<CertContext *> &trusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const;
+
+ void make_props()
+ {
+ X509 *x = item.cert;
+ CertContextProps p;
+
+ p.version = X509_get_version(x);
+
+ ASN1_INTEGER *ai = X509_get_serialNumber(x);
+ if (ai) {
+ char *rep = i2s_ASN1_INTEGER(NULL, ai);
+ QString str = rep;
+ OPENSSL_free(rep);
+ p.serial.fromString(str);
+ }
+
+ p.start = ASN1_UTCTIME_QDateTime(X509_get_notBefore(x), NULL);
+ p.end = ASN1_UTCTIME_QDateTime(X509_get_notAfter(x), NULL);
+
+ CertificateInfo subject, issuer;
+
+ subject = get_cert_name(X509_get_subject_name(x));
+ issuer = get_cert_name(X509_get_issuer_name(x));
+
+ p.isSelfSigned = (X509_V_OK == X509_check_issued(x, x));
+
+ p.isCA = false;
+ p.pathLimit = 0;
+ int pos = X509_get_ext_by_NID(x, NID_basic_constraints, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ get_basic_constraints(ex, &p.isCA, &p.pathLimit);
+ }
+ }
+
+ pos = X509_get_ext_by_NID(x, NID_subject_alt_name, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ subject.unite(get_cert_alt_name(ex));
+ }
+ }
+
+ pos = X509_get_ext_by_NID(x, NID_issuer_alt_name, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ issuer.unite(get_cert_alt_name(ex));
+ }
+ }
+
+ pos = X509_get_ext_by_NID(x, NID_key_usage, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ p.constraints = get_cert_key_usage(ex);
+ }
+ }
+
+ pos = X509_get_ext_by_NID(x, NID_ext_key_usage, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ p.constraints += get_cert_ext_key_usage(ex);
+ }
+ }
+
+ pos = X509_get_ext_by_NID(x, NID_certificate_policies, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ p.policies = get_cert_policies(ex);
+ }
+ }
+
+#ifdef OSSL_110
+ const
+#endif
+ ASN1_BIT_STRING *signature;
+
+ X509_get0_signature(&signature, NULL, x);
+ if (signature) {
+ p.sig = QByteArray(signature->length, 0);
+ for (int i = 0; i < signature->length; i++) {
+ p.sig[i] = signature->data[i];
+ }
+ }
+
+ switch (X509_get_signature_nid(x)) {
+ case NID_sha1WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA1;
+ break;
+ case NID_md5WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_MD5;
+ break;
+#ifdef HAVE_OPENSSL_MD2
+ case NID_md2WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_MD2;
+ break;
+#endif
+ case NID_ripemd160WithRSA:
+ p.sigalgo = QCA::EMSA3_RIPEMD160;
+ break;
+ case NID_dsaWithSHA1:
+ p.sigalgo = QCA::EMSA1_SHA1;
+ break;
+ case NID_sha224WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA224;
+ break;
+ case NID_sha256WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA256;
+ break;
+ case NID_sha384WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA384;
+ break;
+ case NID_sha512WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA512;
+ break;
+ default:
+ qDebug() << "Unknown signature value: " << X509_get_signature_nid(x);
+ p.sigalgo = QCA::SignatureUnknown;
+ }
+
+ pos = X509_get_ext_by_NID(x, NID_subject_key_identifier, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ p.subjectId += get_cert_subject_key_id(ex);
+ }
+ }
+
+ pos = X509_get_ext_by_NID(x, NID_authority_key_identifier, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_get_ext(x, pos);
+ if (ex) {
+ p.issuerId += get_cert_issuer_key_id(ex);
+ }
+ }
+
+ // FIXME: super hack
+ CertificateOptions opts;
+ opts.setInfo(subject);
+ p.subject = opts.infoOrdered();
+ opts.setInfo(issuer);
+ p.issuer = opts.infoOrdered();
+
+ _props = p;
+ //printf("[%p] made props: [%s]\n", this, _props.subject[CommonName].toLatin1().data());
+ }
+};
+
+bool sameChain(STACK_OF(X509) *ossl, const QList<const MyCertContext *> &qca)
+{
+ if (sk_X509_num(ossl) != qca.count()) {
+ return false;
+ }
+
+ for (int n = 0; n < sk_X509_num(ossl); ++n) {
+ X509 *a = sk_X509_value(ossl, n);
+ X509 *b = qca[n]->item.cert;
+ if (X509_cmp(a, b) != 0) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+//----------------------------------------------------------------------------
+// MyCAContext
+//----------------------------------------------------------------------------
+// Thanks to Pascal Patry
+class MyCAContext : public CAContext
+{
+public:
+ X509Item caCert;
+ MyPKeyContext *privateKey;
+
+ MyCAContext(Provider *p) : CAContext(p)
+ {
+ privateKey = 0;
+ }
+
+ MyCAContext(const MyCAContext &from) : CAContext(from), caCert(from.caCert)
+ {
+ privateKey = static_cast<MyPKeyContext *>(from.privateKey -> clone());
+ }
+
+ ~MyCAContext()
+ {
+ delete privateKey;
+ }
+
+ virtual CertContext *certificate() const
+ {
+ MyCertContext *cert = new MyCertContext(provider());
+
+ cert->fromX509(caCert.cert);
+ return cert;
+ }
+
+ virtual CertContext *createCertificate(const PKeyContext &pub, const CertificateOptions &opts) const
+ {
+ // TODO: implement
+ Q_UNUSED(pub)
+ Q_UNUSED(opts)
+ return 0;
+ }
+
+ virtual CRLContext *createCRL(const QDateTime &nextUpdate) const
+ {
+ // TODO: implement
+ Q_UNUSED(nextUpdate)
+ return 0;
+ }
+
+ virtual void setup(const CertContext &cert, const PKeyContext &priv)
+ {
+ caCert = static_cast<const MyCertContext &>(cert).item;
+ delete privateKey;
+ privateKey = 0;
+ privateKey = static_cast<MyPKeyContext *>(priv.clone());
+ }
+
+ virtual CertContext *signRequest(const CSRContext &req, const QDateTime &notValidAfter) const
+ {
+ MyCertContext *cert = 0;
+ const EVP_MD *md = 0;
+ X509 *x = 0;
+ const CertContextProps &props = *req.props();
+ CertificateOptions subjectOpts;
+ X509_NAME *subjectName = 0;
+ X509_EXTENSION *ex = 0;
+
+ if (privateKey -> key()->type() == PKey::RSA) {
+ md = EVP_sha1();
+ } else if (privateKey -> key()->type() == PKey::DSA) {
+ md = EVP_sha1();
+ } else {
+ return 0;
+ }
+
+ cert = new MyCertContext(provider());
+
+ subjectOpts.setInfoOrdered(props.subject);
+ subjectName = new_cert_name(subjectOpts.info());
+
+ // create
+ x = X509_new();
+ X509_set_version(x, 2);
+
+ // serial
+ BIGNUM *bn = bi2bn(props.serial);
+ BN_to_ASN1_INTEGER(bn, X509_get_serialNumber(x));
+ BN_free(bn);
+
+ // validity period
+ ASN1_TIME_set(X509_get_notBefore(x), QDateTime::currentDateTime().toUTC().toTime_t());
+ ASN1_TIME_set(X509_get_notAfter(x), notValidAfter.toTime_t());
+
+ X509_set_pubkey(x, static_cast<const MyPKeyContext *>(req.subjectPublicKey()) -> get_pkey());
+ X509_set_subject_name(x, subjectName);
+ X509_set_issuer_name(x, X509_get_subject_name(caCert.cert));
+
+ // subject key id
+ ex = new_subject_key_id(x);
+ {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // CA mode
+ ex = new_basic_constraints(props.isCA, props.pathLimit);
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // subject alt name
+ ex = new_cert_subject_alt_name(subjectOpts.info());
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // key usage
+ ex = new_cert_key_usage(props.constraints);
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // extended key usage
+ ex = new_cert_ext_key_usage(props.constraints);
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ // policies
+ ex = new_cert_policies(props.policies);
+ if (ex) {
+ X509_add_ext(x, ex, -1);
+ X509_EXTENSION_free(ex);
+ }
+
+ if (!X509_sign(x, privateKey->get_pkey(), md)) {
+ X509_free(x);
+ delete cert;
+ return 0;
+ }
+
+ cert->fromX509(x);
+ X509_free(x);
+ return cert;
+ }
+
+ virtual CRLContext *updateCRL(const CRLContext &crl, const QList<CRLEntry> &entries, const QDateTime &nextUpdate) const
+ {
+ // TODO: implement
+ Q_UNUSED(crl)
+ Q_UNUSED(entries)
+ Q_UNUSED(nextUpdate)
+ return 0;
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new MyCAContext(*this);
+ }
+};
+
+//----------------------------------------------------------------------------
+// MyCSRContext
+//----------------------------------------------------------------------------
+class MyCSRContext : public CSRContext
+{
+public:
+ X509Item item;
+ CertContextProps _props;
+
+ MyCSRContext(Provider *p) : CSRContext(p)
+ {
+ }
+
+ MyCSRContext(const MyCSRContext &from) : CSRContext(from), item(from.item), _props(from._props)
+ {
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new MyCSRContext(*this);
+ }
+
+ virtual QByteArray toDER() const
+ {
+ return item.toDER();
+ }
+
+ virtual QString toPEM() const
+ {
+ return item.toPEM();
+ }
+
+ virtual ConvertResult fromDER(const QByteArray &a)
+ {
+ _props = CertContextProps();
+ ConvertResult r = item.fromDER(a, X509Item::TypeReq);
+ if (r == ConvertGood) {
+ make_props();
+ }
+ return r;
+ }
+
+ virtual ConvertResult fromPEM(const QString &s)
+ {
+ _props = CertContextProps();
+ ConvertResult r = item.fromPEM(s, X509Item::TypeReq);
+ if (r == ConvertGood) {
+ make_props();
+ }
+ return r;
+ }
+
+ virtual bool canUseFormat(CertificateRequestFormat f) const
+ {
+ if (f == PKCS10) {
+ return true;
+ }
+ return false;
+ }
+
+ virtual bool createRequest(const CertificateOptions &opts, const PKeyContext &priv)
+ {
+ _props = CertContextProps();
+ item.reset();
+
+ CertificateInfo info = opts.info();
+
+ // Note: removing default constraints, let the app choose these if it wants
+ Constraints constraints = opts.constraints();
+ // constraints - logic from Botan
+ /*Constraints constraints;
+ if(opts.isCA())
+ {
+ constraints += KeyCertificateSign;
+ constraints += CRLSign;
+ }
+ else
+ constraints = find_constraints(priv, opts.constraints());*/
+
+ EVP_PKEY *pk = static_cast<const MyPKeyContext *>(&priv)->get_pkey();
+ X509_EXTENSION *ex;
+
+ const EVP_MD *md;
+ if (priv.key()->type() == PKey::RSA) {
+ md = EVP_sha1();
+ } else if (priv.key()->type() == PKey::DSA) {
+ md = EVP_sha1();
+ } else {
+ return false;
+ }
+
+ // create
+ X509_REQ *x = X509_REQ_new();
+
+ // public key
+ X509_REQ_set_pubkey(x, pk);
+
+ // subject
+ X509_NAME *name = new_cert_name(info);
+ X509_REQ_set_subject_name(x, name);
+
+ // challenge
+ QByteArray cs = opts.challenge().toLatin1();
+ if (!cs.isEmpty()) {
+ X509_REQ_add1_attr_by_NID(x, NID_pkcs9_challengePassword, MBSTRING_UTF8, (const unsigned char *)cs.data(), -1);
+ }
+
+ STACK_OF(X509_EXTENSION) *exts = sk_X509_EXTENSION_new_null();
+
+ // CA mode
+ ex = new_basic_constraints(opts.isCA(), opts.pathLimit());
+ if (ex) {
+ sk_X509_EXTENSION_push(exts, ex);
+ }
+
+ // subject alt name
+ ex = new_cert_subject_alt_name(info);
+ if (ex) {
+ sk_X509_EXTENSION_push(exts, ex);
+ }
+
+ // key usage
+ ex = new_cert_key_usage(constraints);
+ if (ex) {
+ sk_X509_EXTENSION_push(exts, ex);
+ }
+
+ // extended key usage
+ ex = new_cert_ext_key_usage(constraints);
+ if (ex) {
+ sk_X509_EXTENSION_push(exts, ex);
+ }
+
+ // policies
+ ex = new_cert_policies(opts.policies());
+ if (ex) {
+ sk_X509_EXTENSION_push(exts, ex);
+ }
+
+ if (sk_X509_EXTENSION_num(exts) > 0) {
+ X509_REQ_add_extensions(x, exts);
+ }
+ sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
+
+ // finished
+ X509_REQ_sign(x, pk, md);
+
+ item.req = x;
+ make_props();
+ return true;
+ }
+
+ virtual const CertContextProps *props() const
+ {
+ return &_props;
+ }
+
+ virtual bool compare(const CSRContext *other) const
+ {
+ const CertContextProps *a = &_props;
+ const CertContextProps *b = other->props();
+
+ PublicKey akey, bkey;
+ PKeyContext *ac = subjectPublicKey();
+ akey.change(ac);
+ PKeyContext *bc = other->subjectPublicKey();
+ bkey.change(bc);
+
+ if (a->sig != b->sig || a->sigalgo != b->sigalgo || akey != bkey) {
+ return false;
+ }
+
+ // TODO: Anything else we should compare?
+
+ return true;
+ }
+
+ virtual PKeyContext *subjectPublicKey() const // does a new
+ {
+ MyPKeyContext *kc = new MyPKeyContext(provider());
+ EVP_PKEY *pkey = X509_REQ_get_pubkey(item.req);
+ PKeyBase *kb = kc->pkeyToBase(pkey, false);
+ kc->setKey(kb);
+ return kc;
+ }
+
+ virtual QString toSPKAC() const
+ {
+ return QString();
+ }
+
+ virtual ConvertResult fromSPKAC(const QString &s)
+ {
+ Q_UNUSED(s);
+ return ErrorDecode;
+ }
+
+ void make_props()
+ {
+ X509_REQ *x = item.req;
+ CertContextProps p;
+
+ // TODO: QString challenge;
+
+ p.format = PKCS10;
+
+ CertificateInfo subject;
+
+ subject = get_cert_name(X509_REQ_get_subject_name(x));
+
+ STACK_OF(X509_EXTENSION) *exts = X509_REQ_get_extensions(x);
+
+ p.isCA = false;
+ p.pathLimit = 0;
+ int pos = X509v3_get_ext_by_NID(exts, NID_basic_constraints, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
+ if (ex) {
+ get_basic_constraints(ex, &p.isCA, &p.pathLimit);
+ }
+ }
+
+ pos = X509v3_get_ext_by_NID(exts, NID_subject_alt_name, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
+ if (ex) {
+ subject.unite(get_cert_alt_name(ex));
+ }
+ }
+
+ pos = X509v3_get_ext_by_NID(exts, NID_key_usage, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
+ if (ex) {
+ p.constraints = get_cert_key_usage(ex);
+ }
+ }
+
+ pos = X509v3_get_ext_by_NID(exts, NID_ext_key_usage, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
+ if (ex) {
+ p.constraints += get_cert_ext_key_usage(ex);
+ }
+ }
+
+ pos = X509v3_get_ext_by_NID(exts, NID_certificate_policies, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509v3_get_ext(exts, pos);
+ if (ex) {
+ p.policies = get_cert_policies(ex);
+ }
+ }
+
+ sk_X509_EXTENSION_pop_free(exts, X509_EXTENSION_free);
+
+ const ASN1_BIT_STRING *signature;
+
+ X509_REQ_get0_signature(x, &signature, NULL);
+ if (signature) {
+ p.sig = QByteArray(signature->length, 0);
+ for (int i = 0; i < signature->length; i++) {
+ p.sig[i] = signature->data[i];
+ }
+ }
+
+ switch (X509_REQ_get_signature_nid(x)) {
+ case NID_sha1WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA1;
+ break;
+ case NID_md5WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_MD5;
+ break;
+#ifdef HAVE_OPENSSL_MD2
+ case NID_md2WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_MD2;
+ break;
+#endif
+ case NID_ripemd160WithRSA:
+ p.sigalgo = QCA::EMSA3_RIPEMD160;
+ break;
+ case NID_dsaWithSHA1:
+ p.sigalgo = QCA::EMSA1_SHA1;
+ break;
+ default:
+ qDebug() << "Unknown signature value: " << X509_REQ_get_signature_nid(x);
+ p.sigalgo = QCA::SignatureUnknown;
+ }
+
+ // FIXME: super hack
+ CertificateOptions opts;
+ opts.setInfo(subject);
+ p.subject = opts.infoOrdered();
+
+ _props = p;
+ }
+};
+
+//----------------------------------------------------------------------------
+// MyCRLContext
+//----------------------------------------------------------------------------
+class MyCRLContext : public CRLContext
+{
+public:
+ X509Item item;
+ CRLContextProps _props;
+
+ MyCRLContext(Provider *p) : CRLContext(p)
+ {
+ }
+
+ MyCRLContext(const MyCRLContext &from) : CRLContext(from), item(from.item)
+ {
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new MyCRLContext(*this);
+ }
+
+ virtual QByteArray toDER() const
+ {
+ return item.toDER();
+ }
+
+ virtual QString toPEM() const
+ {
+ return item.toPEM();
+ }
+
+ virtual ConvertResult fromDER(const QByteArray &a)
+ {
+ _props = CRLContextProps();
+ ConvertResult r = item.fromDER(a, X509Item::TypeCRL);
+ if (r == ConvertGood) {
+ make_props();
+ }
+ return r;
+ }
+
+ virtual ConvertResult fromPEM(const QString &s)
+ {
+ ConvertResult r = item.fromPEM(s, X509Item::TypeCRL);
+ if (r == ConvertGood) {
+ make_props();
+ }
+ return r;
+ }
+
+ void fromX509(X509_CRL *x)
+ {
+ X509_CRL_up_ref(x);
+ item.crl = x;
+ make_props();
+ }
+
+ virtual const CRLContextProps *props() const
+ {
+ return &_props;
+ }
+
+ virtual bool compare(const CRLContext *other) const
+ {
+ const CRLContextProps *a = &_props;
+ const CRLContextProps *b = other->props();
+
+ if (a->issuer != b->issuer) {
+ return false;
+ }
+ if (a->number != b->number) {
+ return false;
+ }
+ if (a->thisUpdate != b->thisUpdate) {
+ return false;
+ }
+ if (a->nextUpdate != b->nextUpdate) {
+ return false;
+ }
+ if (a->revoked != b->revoked) {
+ return false;
+ }
+ if (a->sig != b->sig) {
+ return false;
+ }
+ if (a->sigalgo != b->sigalgo) {
+ return false;
+ }
+ if (a->issuerId != b->issuerId) {
+ return false;
+ }
+
+ return true;
+ }
+
+ void make_props()
+ {
+ X509_CRL *x = item.crl;
+
+ CRLContextProps p;
+
+ CertificateInfo issuer;
+
+ issuer = get_cert_name(X509_CRL_get_issuer(x));
+
+ p.thisUpdate = ASN1_UTCTIME_QDateTime(X509_CRL_get0_lastUpdate(x), NULL);
+ p.nextUpdate = ASN1_UTCTIME_QDateTime(X509_CRL_get0_nextUpdate(x), NULL);
+
+ STACK_OF(X509_REVOKED)* revokeStack = X509_CRL_get_REVOKED(x);
+
+ for (int i = 0; i < sk_X509_REVOKED_num(revokeStack); ++i) {
+ X509_REVOKED *rev = sk_X509_REVOKED_value(revokeStack, i);
+ BigInteger serial = bn2bi(ASN1_INTEGER_to_BN(X509_REVOKED_get0_serialNumber(rev), NULL));
+ QDateTime time = ASN1_UTCTIME_QDateTime(X509_REVOKED_get0_revocationDate(rev), NULL);
+ QCA::CRLEntry::Reason reason = QCA::CRLEntry::Unspecified;
+ int pos = X509_REVOKED_get_ext_by_NID(rev, NID_crl_reason, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_REVOKED_get_ext(rev, pos);
+ if (ex) {
+ int *result = (int *) X509V3_EXT_d2i(ex);
+ switch (*result) {
+ case 0:
+ reason = QCA::CRLEntry::Unspecified;
+ break;
+ case 1:
+ reason = QCA::CRLEntry::KeyCompromise;
+ break;
+ case 2:
+ reason = QCA::CRLEntry::CACompromise;
+ break;
+ case 3:
+ reason = QCA::CRLEntry::AffiliationChanged;
+ break;
+ case 4:
+ reason = QCA::CRLEntry::Superseded;
+ break;
+ case 5:
+ reason = QCA::CRLEntry::CessationOfOperation;
+ break;
+ case 6:
+ reason = QCA::CRLEntry::CertificateHold;
+ break;
+ case 8:
+ reason = QCA::CRLEntry::RemoveFromCRL;
+ break;
+ case 9:
+ reason = QCA::CRLEntry::PrivilegeWithdrawn;
+ break;
+ case 10:
+ reason = QCA::CRLEntry::AACompromise;
+ break;
+ default:
+ reason = QCA::CRLEntry::Unspecified;
+ break;
+ }
+ ASN1_INTEGER_free((ASN1_INTEGER *)result);
+ }
+ }
+ CRLEntry thisEntry(serial, time, reason);
+ p.revoked.append(thisEntry);
+ }
+
+ const ASN1_BIT_STRING *signature;
+
+ X509_CRL_get0_signature(x, &signature, NULL);
+ if (signature) {
+ p.sig = QByteArray(signature->length, 0);
+ for (int i = 0; i < signature->length; i++) {
+ p.sig[i] = signature->data[i];
+ }
+ }
+
+ switch (X509_CRL_get_signature_nid(x)) {
+ case NID_sha1WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA1;
+ break;
+ case NID_md5WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_MD5;
+ break;
+#ifdef HAVE_OPENSSL_MD2
+ case NID_md2WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_MD2;
+ break;
+#endif
+ case NID_ripemd160WithRSA:
+ p.sigalgo = QCA::EMSA3_RIPEMD160;
+ break;
+ case NID_dsaWithSHA1:
+ p.sigalgo = QCA::EMSA1_SHA1;
+ break;
+ case NID_sha224WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA224;
+ break;
+ case NID_sha256WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA256;
+ break;
+ case NID_sha384WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA384;
+ break;
+ case NID_sha512WithRSAEncryption:
+ p.sigalgo = QCA::EMSA3_SHA512;
+ break;
+ default:
+ qWarning() << "Unknown signature value: " << X509_CRL_get_signature_nid(x);
+ p.sigalgo = QCA::SignatureUnknown;
+ }
+
+ int pos = X509_CRL_get_ext_by_NID(x, NID_authority_key_identifier, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_CRL_get_ext(x, pos);
+ if (ex) {
+ p.issuerId += get_cert_issuer_key_id(ex);
+ }
+ }
+
+ p.number = -1;
+ pos = X509_CRL_get_ext_by_NID(x, NID_crl_number, -1);
+ if (pos != -1) {
+ X509_EXTENSION *ex = X509_CRL_get_ext(x, pos);
+ if (ex) {
+ int *result = (int *) X509V3_EXT_d2i(ex);
+ p.number = (*result);
+ ASN1_INTEGER_free((ASN1_INTEGER *)result);
+ }
+ }
+
+ // FIXME: super hack
+ CertificateOptions opts;
+ opts.setInfo(issuer);
+ p.issuer = opts.infoOrdered();
+
+ _props = p;
+ }
+};
+
+//----------------------------------------------------------------------------
+// MyCertCollectionContext
+//----------------------------------------------------------------------------
+class MyCertCollectionContext : public CertCollectionContext
+{
+ Q_OBJECT
+public:
+ MyCertCollectionContext(Provider *p) : CertCollectionContext(p)
+ {
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new MyCertCollectionContext(*this);
+ }
+
+ virtual QByteArray toPKCS7(const QList<CertContext *> &certs, const QList<CRLContext *> &crls) const
+ {
+ // TODO: implement
+ Q_UNUSED(certs);
+ Q_UNUSED(crls);
+ return QByteArray();
+ }
+
+ virtual ConvertResult fromPKCS7(const QByteArray &a, QList<CertContext *> *certs, QList<CRLContext *> *crls) const
+ {
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, a.data(), a.size());
+ PKCS7 *p7 = d2i_PKCS7_bio(bi, NULL);
+ BIO_free(bi);
+ if (!p7) {
+ return ErrorDecode;
+ }
+
+ STACK_OF(X509) *xcerts = 0;
+ STACK_OF(X509_CRL) *xcrls = 0;
+
+ int i = OBJ_obj2nid(p7->type);
+ if (i == NID_pkcs7_signed) {
+ xcerts = p7->d.sign->cert;
+ xcrls = p7->d.sign->crl;
+ } else if (i == NID_pkcs7_signedAndEnveloped) {
+ xcerts = p7->d.signed_and_enveloped->cert;
+ xcrls = p7->d.signed_and_enveloped->crl;
+ }
+
+ QList<CertContext *> _certs;
+ QList<CRLContext *> _crls;
+
+ if (xcerts) {
+ for (int n = 0; n < sk_X509_num(xcerts); ++n) {
+ MyCertContext *cc = new MyCertContext(provider());
+ cc->fromX509(sk_X509_value(xcerts, n));
+ _certs += cc;
+ }
+ }
+ if (xcrls) {
+ for (int n = 0; n < sk_X509_CRL_num(xcrls); ++n) {
+ MyCRLContext *cc = new MyCRLContext(provider());
+ cc->fromX509(sk_X509_CRL_value(xcrls, n));
+ _crls += cc;
+ }
+ }
+
+ PKCS7_free(p7);
+
+ *certs = _certs;
+ *crls = _crls;
+
+ return ConvertGood;
+ }
+};
+
+static bool usage_check(const MyCertContext &cc, UsageMode u)
+{
+ if (cc._props.constraints.isEmpty()) {
+ // then any usage is OK
+ return true;
+ }
+
+ switch (u) {
+ case UsageAny :
+ return true;
+ break;
+ case UsageTLSServer :
+ return cc._props.constraints.contains(ServerAuth);
+ break;
+ case UsageTLSClient :
+ return cc._props.constraints.contains(ClientAuth);
+ break;
+ case UsageCodeSigning :
+ return cc._props.constraints.contains(CodeSigning);
+ break;
+ case UsageEmailProtection :
+ return cc._props.constraints.contains(EmailProtection);
+ break;
+ case UsageTimeStamping :
+ return cc._props.constraints.contains(TimeStamping);
+ break;
+ case UsageCRLSigning :
+ return cc._props.constraints.contains(CRLSign);
+ break;
+ default:
+ return true;
+ }
+}
+
+Validity MyCertContext::validate(const QList<CertContext *> &trusted, const QList<CertContext *> &untrusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const
+{
+ // TODO
+ Q_UNUSED(vf);
+
+ STACK_OF(X509) *trusted_list = sk_X509_new_null();
+ STACK_OF(X509) *untrusted_list = sk_X509_new_null();
+ QList<X509_CRL *> crl_list;
+
+ int n;
+ for (n = 0; n < trusted.count(); ++n) {
+ const MyCertContext *cc = static_cast<const MyCertContext *>(trusted[n]);
+ X509 *x = cc->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(trusted_list, x);
+ }
+ for (n = 0; n < untrusted.count(); ++n) {
+ const MyCertContext *cc = static_cast<const MyCertContext *>(untrusted[n]);
+ X509 *x = cc->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(untrusted_list, x);
+ }
+ for (n = 0; n < crls.count(); ++n) {
+ const MyCRLContext *cc = static_cast<const MyCRLContext *>(crls[n]);
+ X509_CRL *x = cc->item.crl;
+ X509_CRL_up_ref(x);
+ crl_list.append(x);
+ }
+
+ const MyCertContext *cc = this;
+ X509 *x = cc->item.cert;
+
+ // verification happens through a store "context"
+ X509_STORE_CTX *ctx = X509_STORE_CTX_new();
+
+ // make a store of crls
+ X509_STORE *store = X509_STORE_new();
+ for (int n = 0; n < crl_list.count(); ++n) {
+ X509_STORE_add_crl(store, crl_list[n]);
+ }
+
+ // the first initialization handles untrusted certs, crls, and target cert
+ X509_STORE_CTX_init(ctx, store, x, untrusted_list);
+
+ // this initializes the trusted certs
+ X509_STORE_CTX_trusted_stack(ctx, trusted_list);
+
+ // verify!
+ int ret = X509_verify_cert(ctx);
+ int err = -1;
+ if (!ret) {
+ err = X509_STORE_CTX_get_error(ctx);
+ }
+
+ // cleanup
+ X509_STORE_CTX_free(ctx);
+ X509_STORE_free(store);
+
+ sk_X509_pop_free(trusted_list, X509_free);
+ sk_X509_pop_free(untrusted_list, X509_free);
+ for (int n = 0; n < crl_list.count(); ++n) {
+ X509_CRL_free(crl_list[n]);
+ }
+
+ if (!ret) {
+ return convert_verify_error(err);
+ }
+
+ if (!usage_check(*cc, u)) {
+ return ErrorInvalidPurpose;
+ }
+
+ return ValidityGood;
+}
+
+Validity MyCertContext::validate_chain(const QList<CertContext *> &chain, const QList<CertContext *> &trusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const
+{
+ // TODO
+ Q_UNUSED(vf);
+
+ STACK_OF(X509) *trusted_list = sk_X509_new_null();
+ STACK_OF(X509) *untrusted_list = sk_X509_new_null();
+ QList<X509_CRL *> crl_list;
+
+ int n;
+ for (n = 0; n < trusted.count(); ++n) {
+ const MyCertContext *cc = static_cast<const MyCertContext *>(trusted[n]);
+ X509 *x = cc->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(trusted_list, x);
+ }
+ for (n = 1; n < chain.count(); ++n) {
+ const MyCertContext *cc = static_cast<const MyCertContext *>(chain[n]);
+ X509 *x = cc->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(untrusted_list, x);
+ }
+ for (n = 0; n < crls.count(); ++n) {
+ const MyCRLContext *cc = static_cast<const MyCRLContext *>(crls[n]);
+ X509_CRL *x = cc->item.crl;
+ X509_CRL_up_ref(x);
+ crl_list.append(x);
+ }
+
+ const MyCertContext *cc = static_cast<const MyCertContext *>(chain[0]);
+ X509 *x = cc->item.cert;
+
+ // verification happens through a store "context"
+ X509_STORE_CTX *ctx = X509_STORE_CTX_new();
+
+ // make a store of crls
+ X509_STORE *store = X509_STORE_new();
+ for (int n = 0; n < crl_list.count(); ++n) {
+ X509_STORE_add_crl(store, crl_list[n]);
+ }
+
+ // the first initialization handles untrusted certs, crls, and target cert
+ X509_STORE_CTX_init(ctx, store, x, untrusted_list);
+
+ // this initializes the trusted certs
+ X509_STORE_CTX_trusted_stack(ctx, trusted_list);
+
+ // verify!
+ int ret = X509_verify_cert(ctx);
+ int err = -1;
+ if (!ret) {
+ err = X509_STORE_CTX_get_error(ctx);
+ }
+
+ // grab the chain, which may not be fully populated
+ STACK_OF(X509) *xchain = X509_STORE_CTX_get_chain(ctx);
+
+ // make sure the chain is what we expect. the reason we need to do
+ // this is because I don't think openssl cares about the order of
+ // input. that is, if there's a chain A<-B<-C, and we input A as
+ // the base cert, with B and C as the issuers, we will get a
+ // successful validation regardless of whether the issuer list is
+ // in the order B,C or C,B. we don't want an input chain of A,C,B
+ // to be considered correct, so we must account for that here.
+ QList<const MyCertContext *> expected;
+ for (int n = 0; n < chain.count(); ++n) {
+ expected += static_cast<const MyCertContext *>(chain[n]);
+ }
+ if (!xchain || !sameChain(xchain, expected)) {
+ err = ErrorValidityUnknown;
+ }
+
+ // cleanup
+ X509_STORE_CTX_free(ctx);
+ X509_STORE_free(store);
+
+ sk_X509_pop_free(trusted_list, X509_free);
+ sk_X509_pop_free(untrusted_list, X509_free);
+ for (int n = 0; n < crl_list.count(); ++n) {
+ X509_CRL_free(crl_list[n]);
+ }
+
+ if (!ret) {
+ return convert_verify_error(err);
+ }
+
+ if (!usage_check(*cc, u)) {
+ return ErrorInvalidPurpose;
+ }
+
+ return ValidityGood;
+}
+
+class MyPKCS12Context : public PKCS12Context
+{
+public:
+ MyPKCS12Context(Provider *p) : PKCS12Context(p)
+ {
+ }
+
+ ~MyPKCS12Context()
+ {
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual QByteArray toPKCS12(const QString &name, const QList<const CertContext *> &chain, const PKeyContext &priv, const SecureArray &passphrase) const
+ {
+ if (chain.count() < 1) {
+ return QByteArray();
+ }
+
+ X509 *cert = static_cast<const MyCertContext *>(chain[0])->item.cert;
+ STACK_OF(X509) *ca = sk_X509_new_null();
+ if (chain.count() > 1) {
+ for (int n = 1; n < chain.count(); ++n) {
+ X509 *x = static_cast<const MyCertContext *>(chain[n])->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(ca, x);
+ }
+ }
+ const MyPKeyContext &pk = static_cast<const MyPKeyContext &>(priv);
+ PKCS12 *p12 = PKCS12_create((char *)passphrase.data(), (char *)name.toLatin1().data(), pk.get_pkey(), cert, ca, 0, 0, 0, 0, 0);
+ sk_X509_pop_free(ca, X509_free);
+
+ if (!p12) {
+ return QByteArray();
+ }
+
+ BIO *bo = BIO_new(BIO_s_mem());
+ i2d_PKCS12_bio(bo, p12);
+ QByteArray out = bio2ba(bo);
+ return out;
+ }
+
+ virtual ConvertResult fromPKCS12(const QByteArray &in, const SecureArray &passphrase, QString *name, QList<CertContext *> *chain, PKeyContext **priv) const
+ {
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ PKCS12 *p12 = d2i_PKCS12_bio(bi, NULL);
+ if (!p12) {
+ return ErrorDecode;
+ }
+
+ EVP_PKEY *pkey;
+ X509 *cert;
+ STACK_OF(X509) *ca = NULL;
+ if (!PKCS12_parse(p12, passphrase.data(), &pkey, &cert, &ca)) {
+ PKCS12_free(p12);
+ return ErrorDecode;
+ }
+ PKCS12_free(p12);
+
+ // require private key
+ if (!pkey) {
+ if (cert) {
+ X509_free(cert);
+ }
+ if (ca) {
+ sk_X509_pop_free(ca, X509_free);
+ }
+ return ErrorDecode;
+ }
+
+ // TODO: require cert
+
+ int aliasLength;
+ char *aliasData = (char *)X509_alias_get0(cert, &aliasLength);
+ *name = QString::fromLatin1(aliasData, aliasLength);
+
+ MyPKeyContext *pk = new MyPKeyContext(provider());
+ PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free()
+ pk->k = k;
+ *priv = pk;
+
+ QList<CertContext *> certs;
+ if (cert) {
+ MyCertContext *cc = new MyCertContext(provider());
+ cc->fromX509(cert);
+ certs.append(cc);
+ X509_free(cert);
+ }
+ if (ca) {
+ // TODO: reorder in chain-order?
+ // TODO: throw out certs that don't fit the chain?
+ for (int n = 0; n < sk_X509_num(ca); ++n) {
+ MyCertContext *cc = new MyCertContext(provider());
+ cc->fromX509(sk_X509_value(ca, n));
+ certs.append(cc);
+ }
+ sk_X509_pop_free(ca, X509_free);
+ }
+
+ // reorder, throw out
+ QCA::CertificateChain ch;
+ for (int n = 0; n < certs.count(); ++n) {
+ QCA::Certificate cert;
+ cert.change(certs[n]);
+ ch += cert;
+ }
+ certs.clear();
+ ch = ch.complete(QList<QCA::Certificate>());
+ for (int n = 0; n < ch.count(); ++n) {
+ MyCertContext *cc = (MyCertContext *)ch[n].context();
+ certs += (new MyCertContext(*cc));
+ }
+ ch.clear();
+
+ *chain = certs;
+ return ConvertGood;
+ }
+};
+
+//==========================================================
+static QString cipherIDtoString(const TLS::Version &version, const unsigned long &cipherID)
+{
+ if (TLS::TLS_v1 == version) {
+ switch (cipherID & 0xFFFF) {
+ case 0x0000:
+ // RFC 2246 A.5
+ return QString("TLS_NULL_WITH_NULL_NULL");
+ break;
+ case 0x0001:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_WITH_NULL_MD5");
+ break;
+ case 0x0002:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_WITH_NULL_SHA");
+ break;
+ case 0x0003:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_EXPORT_WITH_RC4_40_MD5");
+ break;
+ case 0x0004:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_WITH_RC4_128_MD5");
+ break;
+ case 0x0005:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_WITH_RC4_128_SHA");
+ break;
+ case 0x0006:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5");
+ break;
+ case 0x0007:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_WITH_IDEA_CBC_SHA");
+ break;
+ case 0x0008:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x0009:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_WITH_DES_CBC_SHA");
+ break;
+ case 0x000A:
+ // RFC 2246 A.5
+ return QString("TLS_RSA_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x000B:
+ // RFC 2246 A.5
+ return QString("TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x000C:
+ // RFC 2246 A.5
+ return QString("TLS_DH_DSS_WITH_DES_CBC_SHA");
+ break;
+ case 0x000D:
+ // RFC 2246 A.5
+ return QString("TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x000E:
+ // RFC 2246 A.5
+ return QString("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x000F:
+ // RFC 2246 A.5
+ return QString("TLS_DH_RSA_WITH_DES_CBC_SHA");
+ break;
+ case 0x0010:
+ // RFC 2246 A.5
+ return QString("TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0011:
+ // RFC 2246 A.5
+ return QString("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x0012:
+ // RFC 2246 A.5
+ return QString("TLS_DHE_DSS_WITH_DES_CBC_SHA");
+ break;
+ case 0x0013:
+ // RFC 2246 A.5
+ return QString("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0014:
+ // RFC 2246 A.5
+ return QString("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x0015:
+ // RFC 2246 A.5
+ return QString("TLS_DHE_RSA_WITH_DES_CBC_SHA");
+ break;
+ case 0x0016:
+ // RFC 2246 A.5
+ return QString("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0017:
+ // RFC 2246 A.5
+ return QString("TLS_DH_anon_EXPORT_WITH_RC4_40_MD5");
+ break;
+ case 0x0018:
+ // RFC 2246 A.5
+ return QString("TLS_DH_anon_WITH_RC4_128_MD5");
+ break;
+ case 0x0019:
+ // RFC 2246 A.5
+ return QString("TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x001A:
+ // RFC 2246 A.5
+ return QString("TLS_DH_anon_WITH_DES_CBC_SHA");
+ break;
+ case 0x001B:
+ // RFC 2246 A.5
+ return QString("TLS_DH_anon_WITH_3DES_EDE_CBC_SHA");
+ break;
+
+ // 0x001C and 0x001D are reserved to avoid collision with SSL3 Fortezza.
+ case 0x001E:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_DES_CBC_SHA");
+ break;
+ case 0x001F:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0020:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_RC4_128_SHA");
+ break;
+ case 0x0021:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_IDEA_CBC_SHA");
+ break;
+ case 0x0022:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_DES_CBC_MD5");
+ break;
+ case 0x0023:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_3DES_EDE_CBC_MD5");
+ break;
+ case 0x0024:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_RC4_128_MD5");
+ break;
+ case 0x0025:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_WITH_IDEA_CBC_MD5");
+ break;
+ case 0x0026:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA");
+ break;
+ case 0x0027:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA");
+ break;
+ case 0x0028:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_EXPORT_WITH_RC4_40_SHA");
+ break;
+ case 0x0029:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5");
+ break;
+ case 0x002A:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5");
+ break;
+ case 0x002B:
+ // RFC 2712 Section 3
+ return QString("TLS_KRB5_EXPORT_WITH_RC4_40_MD5");
+ break;
+
+ case 0x002F:
+ // RFC 3268
+ return QString("TLS_RSA_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0030:
+ // RFC 3268
+ return QString("TLS_DH_DSS_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0031:
+ // RFC 3268
+ return QString("TLS_DH_RSA_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0032:
+ // RFC 3268
+ return QString("TLS_DHE_DSS_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0033:
+ // RFC 3268
+ return QString("TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0034:
+ // RFC 3268
+ return QString("TLS_DH_anon_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0035:
+ // RFC 3268
+ return QString("TLS_RSA_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0036:
+ // RFC 3268
+ return QString("TLS_DH_DSS_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0037:
+ // RFC 3268
+ return QString("TLS_DH_RSA_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0038:
+ // RFC 3268
+ return QString("TLS_DHE_DSS_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0039:
+ // RFC 3268
+ return QString("TLS_DHE_RSA_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x003A:
+ // RFC 3268
+ return QString("TLS_DH_anon_WITH_AES_256_CBC_SHA");
+ break;
+
+ // TODO: 0x0041 -> 0x0046 are from RFC4132 (Camellia)
+
+ case 0x0060:
+ // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
+ return QString("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_MD5");
+ break;
+ case 0x0061:
+ // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
+ return QString("TLS_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5");
+ break;
+ case 0x0062:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("TLS_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA");
+ break;
+ case 0x0063:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("TLS_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA");
+ break;
+ case 0x0064:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_SHA");
+ break;
+ case 0x0065:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("TLS_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA");
+ break;
+ case 0x0066:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("TLS_CK_DHE_DSS_WITH_RC4_128_SHA");
+ break;
+
+ // TODO: 0x0084 -> 0x0089 are from RFC4132 (Camellia)
+
+ // TODO: 0x008A -> 0x0095 are from RFC4279 (PSK)
+
+ // TODO: 0xC000 -> 0xC019 are from the ECC draft
+
+ default:
+ return QString("TLS algo to be added: %1").arg(cipherID & 0xffff, 0, 16);
+ break;
+ }
+ } else if (TLS::SSL_v3 == version) {
+ switch (cipherID & 0xFFFF) {
+ case 0x0000:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_NULL_WITH_NULL_NULL");
+ break;
+ case 0x0001:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_WITH_NULL_MD5");
+ break;
+ case 0x0002:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_WITH_NULL_SHA");
+ break;
+ case 0x0003:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_EXPORT_WITH_RC4_40_MD5");
+ break;
+ case 0x0004:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_WITH_RC4_128_MD5");
+ break;
+ case 0x0005:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_WITH_RC4_128_SHA");
+ break;
+ case 0x0006:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5");
+ break;
+ case 0x0007:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_WITH_IDEA_CBC_SHA");
+ break;
+ case 0x0008:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x0009:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_WITH_DES_CBC_SHA");
+ break;
+ case 0x000A:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_RSA_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x000B:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x000C:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_DSS_WITH_DES_CBC_SHA");
+ break;
+ case 0x000D:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x000E:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_RSA_WITH_DES_CBC_SHA");
+ break;
+ case 0x000F:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_RSA_WITH_DES_CBC_SHA");
+ break;
+ case 0x0010:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0011:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x0012:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DHE_DSS_WITH_DES_CBC_SHA");
+ break;
+ case 0x0013:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0014:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x0015:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DHE_RSA_WITH_DES_CBC_SHA");
+ break;
+ case 0x0016:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0017:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SL_DH_anon_EXPORT_WITH_RC4_40_MD5");
+ break;
+ case 0x0018:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_anon_WITH_RC4_128_MD5");
+ break;
+ case 0x0019:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
+ break;
+ case 0x001A:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_anon_WITH_DES_CBC_SHA");
+ break;
+ case 0x001B:
+ // From the Netscape SSL3 Draft (nov 1996)
+ return QString("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA");
+ break;
+
+ // TODO: Sort out the Fortezza mess...
+
+ // These aren't in the Netscape SSL3 draft, but openssl does
+ // allow you to use them with SSL3.
+ case 0x001E:
+ return QString("SSL_KRB5_WITH_DES_CBC_SHA");
+ break;
+ case 0x001F:
+ return QString("SSL_KRB5_WITH_3DES_EDE_CBC_SHA");
+ break;
+ case 0x0020:
+ return QString("SSL_KRB5_WITH_RC4_128_SHA");
+ break;
+ case 0x0021:
+ return QString("SSL_KRB5_WITH_IDEA_CBC_SHA");
+ break;
+ case 0x0022:
+ return QString("SSL_KRB5_WITH_DES_CBC_MD5");
+ break;
+ case 0x0023:
+ return QString("SSL_KRB5_WITH_3DES_EDE_CBC_MD5");
+ break;
+ case 0x0024:
+ return QString("SSL_KRB5_WITH_RC4_128_MD5");
+ break;
+ case 0x0025:
+ return QString("SSL_KRB5_WITH_IDEA_CBC_MD5");
+ break;
+ case 0x0026:
+ return QString("SSL_KRB5_EXPORT_WITH_DES_CBC_40_SHA");
+ break;
+ case 0x0027:
+ return QString("SSL_KRB5_EXPORT_WITH_RC2_CBC_40_SHA");
+ break;
+ case 0x0028:
+ return QString("SSL_KRB5_EXPORT_WITH_RC4_40_SHA");
+ break;
+ case 0x0029:
+ return QString("SSL_KRB5_EXPORT_WITH_DES_CBC_40_MD5");
+ break;
+ case 0x002A:
+ return QString("SSL_KRB5_EXPORT_WITH_RC2_CBC_40_MD5");
+ break;
+ case 0x002B:
+ return QString("SSL_KRB5_EXPORT_WITH_RC4_40_MD5");
+ break;
+ case 0x002F:
+ return QString("SSL_RSA_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0030:
+ return QString("SSL_DH_DSS_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0031:
+ return QString("SSL_DH_RSA_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0032:
+ return QString("SSL_DHE_DSS_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0033:
+ return QString("SSL_DHE_RSA_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0034:
+ return QString("SSL_DH_anon_WITH_AES_128_CBC_SHA");
+ break;
+ case 0x0035:
+ return QString("SSL_RSA_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0036:
+ return QString("SSL_DH_DSS_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0037:
+ return QString("SSL_DH_RSA_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0038:
+ return QString("SSL_DHE_DSS_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0039:
+ return QString("SSL_DHE_RSA_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x003A:
+ return QString("SSL_DH_anon_WITH_AES_256_CBC_SHA");
+ break;
+ case 0x0060:
+ // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
+ return QString("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_MD5");
+ break;
+ case 0x0061:
+ // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
+ return QString("SSL_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5");
+ break;
+ case 0x0062:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("SSL_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA");
+ break;
+ case 0x0063:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("SSL_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA");
+ break;
+ case 0x0064:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_SHA");
+ break;
+ case 0x0065:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("SSL_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA");
+ break;
+ case 0x0066:
+ // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
+ return QString("SSL_CK_DHE_DSS_WITH_RC4_128_SHA");
+ break;
+ default:
+ return QString("SSL3 to be added: %1").arg(cipherID & 0xffff, 0, 16);
+ break;
+ }
+ } else if (TLS::SSL_v2 == version) {
+ switch (cipherID & 0xffffff) {
+ case 0x010080:
+ // From the Netscape SSL2 Draft Section C.4 (nov 1994)
+ return QString("SSL_CK_RC4_128_WITH_MD5");
+ break;
+ case 0x020080:
+ // From the Netscape SSL2 Draft Section C.4 (nov 1994)
+ return QString("SSL_CK_RC4_128_EXPORT40_WITH_MD5");
+ break;
+ case 0x030080:
+ // From the Netscape SSL2 Draft Section C.4 (nov 1994)
+ return QString("SSL_CK_RC2_128_CBC_WITH_MD5");
+ break;
+ case 0x040080:
+ // From the Netscape SSL2 Draft Section C.4 (nov 1994)
+ return QString("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5");
+ break;
+ case 0x050080:
+ // From the Netscape SSL2 Draft Section C.4 (nov 1994)
+ return QString("SSL_CK_RC4_128_EXPORT40_WITH_MD5");
+ break;
+ case 0x060040:
+ // From the Netscape SSL2 Draft Section C.4 (nov 1994)
+ return QString("SSL_CK_DES_64_CBC_WITH_MD5");
+ break;
+ case 0x0700C0:
+ // From the Netscape SSL2 Draft Section C.4 (nov 1994)
+ return QString("SSL_CK_DES_192_EDE3_CBC_WITH_MD5");
+ break;
+ case 0x080080:
+ // From the openssl source, which says "MS hack"
+ return QString("SSL_CK_RC4_64_WITH_MD5");
+ break;
+ default:
+ return QString("SSL2 to be added: %1").arg(cipherID & 0xffffff, 0, 16);
+ break;
+ }
+ } else {
+ return QString("Unknown version!");
+ }
+}
+
+// TODO: test to ensure there is no cert-test lag
+static bool ssl_init = false;
+class MyTLSContext : public TLSContext
+{
+public:
+ enum { Good, TryAgain, Bad };
+ enum { Idle, Connect, Accept, Handshake, Active, Closing };
+
+ bool serv; // true if we are acting as a server
+ int mode;
+ QByteArray sendQueue;
+ QByteArray recvQueue;
+
+ CertificateCollection trusted;
+ Certificate cert, peercert; // TODO: support cert chains
+ PrivateKey key;
+ QString targetHostName;
+
+ Result result_result;
+ QByteArray result_to_net;
+ int result_encoded;
+ QByteArray result_plain;
+
+ SSL *ssl;
+#if OPENSSL_VERSION_NUMBER >= 0x00909000L
+ const SSL_METHOD *method;
+#else
+ SSL_METHOD *method;
+#endif
+ SSL_CTX *context;
+ BIO *rbio, *wbio;
+ Validity vr;
+ bool v_eof;
+
+ MyTLSContext(Provider *p) : TLSContext(p, "tls")
+ {
+ if (!ssl_init) {
+ SSL_library_init();
+ SSL_load_error_strings();
+ ssl_init = true;
+ }
+
+ ssl = 0;
+ context = 0;
+ reset();
+ }
+
+ ~MyTLSContext()
+ {
+ reset();
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual void reset()
+ {
+ if (ssl) {
+ SSL_free(ssl);
+ ssl = 0;
+ }
+ if (context) {
+ SSL_CTX_free(context);
+ context = 0;
+ }
+
+ cert = Certificate();
+ key = PrivateKey();
+
+ sendQueue.resize(0);
+ recvQueue.resize(0);
+ mode = Idle;
+ peercert = Certificate();
+ vr = ErrorValidityUnknown;
+ v_eof = false;
+ }
+
+ // dummy verification function for SSL_set_verify()
+ static int ssl_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
+ {
+ Q_UNUSED(preverify_ok);
+ Q_UNUSED(x509_ctx);
+
+ // don't terminate handshake in case of verification failure
+ return 1;
+ }
+
+ virtual QStringList supportedCipherSuites(const TLS::Version &version) const
+ {
+ OpenSSL_add_ssl_algorithms();
+ SSL_CTX *ctx = 0;
+ switch (version) {
+#if !defined(OPENSSL_NO_SSL2) && !defined(OSSL_110)
+ case TLS::SSL_v2:
+ ctx = SSL_CTX_new(SSLv2_client_method());
+ break;
+#endif
+#ifndef OPENSSL_NO_SSL3_METHOD
+ case TLS::SSL_v3:
+ ctx = SSL_CTX_new(SSLv3_client_method());
+ break;
+#endif
+ case TLS::TLS_v1:
+ ctx = SSL_CTX_new(TLSv1_client_method());
+ break;
+ case TLS::DTLS_v1:
+ default:
+ /* should not happen - should be in a "dtls" provider*/
+ qWarning("Unexpected enum in cipherSuites");
+ ctx = 0;
+ }
+ if (NULL == ctx) {
+ return QStringList();
+ }
+
+ SSL *ssl = SSL_new(ctx);
+ if (NULL == ssl) {
+ SSL_CTX_free(ctx);
+ return QStringList();
+ }
+
+ STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl);
+ QStringList cipherList;
+ for (int i = 0; i < sk_SSL_CIPHER_num(sk); ++i) {
+ const SSL_CIPHER *thisCipher = sk_SSL_CIPHER_value(sk, i);
+ cipherList += cipherIDtoString(version, SSL_CIPHER_get_id(thisCipher));
+ }
+
+ SSL_free(ssl);
+ SSL_CTX_free(ctx);
+
+ return cipherList;
+ }
+
+ virtual bool canCompress() const
+ {
+ // TODO
+ return false;
+ }
+
+ virtual bool canSetHostName() const
+ {
+ // TODO
+ return false;
+ }
+
+ virtual int maxSSF() const
+ {
+ // TODO
+ return 256;
+ }
+
+ virtual void setConstraints(int minSSF, int maxSSF)
+ {
+ // TODO
+ Q_UNUSED(minSSF);
+ Q_UNUSED(maxSSF);
+ }
+
+ virtual void setConstraints(const QStringList &cipherSuiteList)
+ {
+ // TODO
+ Q_UNUSED(cipherSuiteList);
+ }
+
+ virtual void setup(bool serverMode, const QString &hostName, bool compress)
+ {
+ serv = serverMode;
+ if (false == serverMode) {
+ // client
+ targetHostName = hostName;
+ }
+ Q_UNUSED(compress); // TODO
+ }
+
+ virtual void setTrustedCertificates(const CertificateCollection &_trusted)
+ {
+ trusted = _trusted;
+ }
+
+ virtual void setIssuerList(const QList<CertificateInfoOrdered> &issuerList)
+ {
+ Q_UNUSED(issuerList); // TODO
+ }
+
+ virtual void setCertificate(const CertificateChain &_cert, const PrivateKey &_key)
+ {
+ if (!_cert.isEmpty()) {
+ cert = _cert.primary(); // TODO: take the whole chain
+ }
+ key = _key;
+ }
+
+ virtual void setSessionId(const TLSSessionContext &id)
+ {
+ // TODO
+ Q_UNUSED(id);
+ }
+
+ virtual void shutdown()
+ {
+ mode = Closing;
+ }
+
+ virtual void start()
+ {
+ bool ok;
+ if (serv) {
+ ok = priv_startServer();
+ } else {
+ ok = priv_startClient();
+ }
+ result_result = ok ? Success : Error;
+
+ doResultsReady();
+ }
+
+ virtual void update(const QByteArray &from_net, const QByteArray &from_app)
+ {
+ if (mode == Active) {
+ bool ok = true;
+ if (!from_app.isEmpty()) {
+ ok = priv_encode(from_app, &result_to_net, &result_encoded);
+ }
+ if (ok) {
+ ok = priv_decode(from_net, &result_plain, &result_to_net);
+ }
+ result_result = ok ? Success : Error;
+ } else if (mode == Closing) {
+ result_result = priv_shutdown(from_net, &result_to_net);
+ } else {
+ result_result = priv_handshake(from_net, &result_to_net);
+ }
+
+ //printf("update (from_net=%d, to_net=%d, from_app=%d, to_app=%d)\n", from_net.size(), result_to_net.size(), from_app.size(), result_plain.size());
+
+ doResultsReady();
+ }
+
+ bool priv_startClient()
+ {
+ //serv = false;
+ method = SSLv23_client_method();
+ if (!init()) {
+ return false;
+ }
+ mode = Connect;
+ return true;
+ }
+
+ bool priv_startServer()
+ {
+ //serv = true;
+ method = SSLv23_server_method();
+ if (!init()) {
+ return false;
+ }
+ mode = Accept;
+ return true;
+ }
+
+ Result priv_handshake(const QByteArray &from_net, QByteArray *to_net)
+ {
+ if (!from_net.isEmpty()) {
+ BIO_write(rbio, from_net.data(), from_net.size());
+ }
+
+ if (mode == Connect) {
+ int ret = doConnect();
+ if (ret == Good) {
+ mode = Handshake;
+ } else if (ret == Bad) {
+ reset();
+ return Error;
+ }
+ }
+
+ if (mode == Accept) {
+ int ret = doAccept();
+ if (ret == Good) {
+ getCert();
+ mode = Active;
+ } else if (ret == Bad) {
+ reset();
+ return Error;
+ }
+ }
+
+ if (mode == Handshake) {
+ int ret = doHandshake();
+ if (ret == Good) {
+ getCert();
+ mode = Active;
+ } else if (ret == Bad) {
+ reset();
+ return Error;
+ }
+ }
+
+ // process outgoing
+ *to_net = readOutgoing();
+
+ if (mode == Active) {
+ return Success;
+ } else {
+ return Continue;
+ }
+ }
+
+ Result priv_shutdown(const QByteArray &from_net, QByteArray *to_net)
+ {
+ if (!from_net.isEmpty()) {
+ BIO_write(rbio, from_net.data(), from_net.size());
+ }
+
+ int ret = doShutdown();
+ if (ret == Bad) {
+ reset();
+ return Error;
+ }
+
+ *to_net = readOutgoing();
+
+ if (ret == Good) {
+ mode = Idle;
+ return Success;
+ } else {
+ //mode = Closing;
+ return Continue;
+ }
+ }
+
+ bool priv_encode(const QByteArray &plain, QByteArray *to_net, int *enc)
+ {
+ if (mode != Active) {
+ return false;
+ }
+ sendQueue.append(plain);
+
+ int encoded = 0;
+ if (sendQueue.size() > 0) {
+ int ret = SSL_write(ssl, sendQueue.data(), sendQueue.size());
+
+ enum { Good, Continue, Done, Error };
+ int m;
+ if (ret <= 0) {
+ int x = SSL_get_error(ssl, ret);
+ if (x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) {
+ m = Continue;
+ } else if (x == SSL_ERROR_ZERO_RETURN) {
+ m = Done;
+ } else {
+ m = Error;
+ }
+ } else {
+ m = Good;
+ encoded = ret;
+ int newsize = sendQueue.size() - encoded;
+ char *r = sendQueue.data();
+ memmove(r, r + encoded, newsize);
+ sendQueue.resize(newsize);
+ }
+
+ if (m == Done) {
+ sendQueue.resize(0);
+ v_eof = true;
+ return false;
+ }
+ if (m == Error) {
+ sendQueue.resize(0);
+ return false;
+ }
+ }
+
+ *to_net += readOutgoing();
+ *enc = encoded;
+ return true;
+ }
+
+ bool priv_decode(const QByteArray &from_net, QByteArray *plain, QByteArray *to_net)
+ {
+ if (mode != Active) {
+ return false;
+ }
+ if (!from_net.isEmpty()) {
+ BIO_write(rbio, from_net.data(), from_net.size());
+ }
+
+ QByteArray a;
+ while (!v_eof) {
+ a.resize(8192);
+ int ret = SSL_read(ssl, a.data(), a.size());
+ //printf("SSL_read = %d\n", ret);
+ if (ret > 0) {
+ if (ret != (int)a.size()) {
+ a.resize(ret);
+ }
+ //printf("SSL_read chunk: [%s]\n", qPrintable(arrayToHex(a)));
+ recvQueue.append(a);
+ } else if (ret <= 0) {
+ ERR_print_errors_fp(stdout);
+ int x = SSL_get_error(ssl, ret);
+ //printf("SSL_read error = %d\n", x);
+ if (x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) {
+ break;
+ } else if (x == SSL_ERROR_ZERO_RETURN) {
+ v_eof = true;
+ } else {
+ return false;
+ }
+ }
+ }
+
+ *plain = recvQueue;
+ recvQueue.resize(0);
+
+ // could be outgoing data also
+ *to_net += readOutgoing();
+ return true;
+ }
+
+ virtual bool waitForResultsReady(int msecs)
+ {
+ // TODO: for now, all operations block anyway
+ Q_UNUSED(msecs);
+ return true;
+ }
+
+ virtual Result result() const
+ {
+ return result_result;
+ }
+
+ virtual QByteArray to_net()
+ {
+ QByteArray a = result_to_net;
+ result_to_net.clear();
+ return a;
+ }
+
+ virtual int encoded() const
+ {
+ return result_encoded;
+ }
+
+ virtual QByteArray to_app()
+ {
+ QByteArray a = result_plain;
+ result_plain.clear();
+ return a;
+ }
+
+ virtual bool eof() const
+ {
+ return v_eof;
+ }
+
+ virtual bool clientHelloReceived() const
+ {
+ // TODO
+ return false;
+ }
+
+ virtual bool serverHelloReceived() const
+ {
+ // TODO
+ return false;
+ }
+
+ virtual QString hostName() const
+ {
+ // TODO
+ return QString();
+ }
-//----------------------------------------------------------------------------
-// MyCRLContext
-//----------------------------------------------------------------------------
-class MyCRLContext : public CRLContext
-{
-public:
- X509Item item;
- CRLContextProps _props;
-
- MyCRLContext(Provider *p) : CRLContext(p)
- {
- }
-
- MyCRLContext(const MyCRLContext &from) : CRLContext(from), item(from.item)
- {
- }
-
- virtual Provider::Context *clone() const
- {
- return new MyCRLContext(*this);
- }
-
- virtual QByteArray toDER() const
- {
- return item.toDER();
- }
-
- virtual QString toPEM() const
- {
- return item.toPEM();
- }
-
- virtual ConvertResult fromDER(const QByteArray &a)
- {
- _props = CRLContextProps();
- ConvertResult r = item.fromDER(a, X509Item::TypeCRL);
- if(r == ConvertGood)
- make_props();
- return r;
- }
-
- virtual ConvertResult fromPEM(const QString &s)
- {
- ConvertResult r = item.fromPEM(s, X509Item::TypeCRL);
- if(r == ConvertGood)
- make_props();
- return r;
- }
-
- void fromX509(X509_CRL *x)
- {
- X509_CRL_up_ref(x);
- item.crl = x;
- make_props();
- }
-
- virtual const CRLContextProps *props() const
- {
- return &_props;
- }
-
- virtual bool compare(const CRLContext *other) const
- {
- const CRLContextProps *a = &_props;
- const CRLContextProps *b = other->props();
-
- if(a->issuer != b->issuer)
- return false;
- if(a->number != b->number)
- return false;
- if(a->thisUpdate != b->thisUpdate)
- return false;
- if(a->nextUpdate != b->nextUpdate)
- return false;
- if(a->revoked != b->revoked)
- return false;
- if(a->sig != b->sig)
- return false;
- if(a->sigalgo != b->sigalgo)
- return false;
- if(a->issuerId != b->issuerId)
- return false;
-
- return true;
- }
-
- void make_props()
- {
- X509_CRL *x = item.crl;
-
- CRLContextProps p;
-
- CertificateInfo issuer;
-
- issuer = get_cert_name(X509_CRL_get_issuer(x));
-
- p.thisUpdate = ASN1_UTCTIME_QDateTime(X509_CRL_get0_lastUpdate(x), NULL);
- p.nextUpdate = ASN1_UTCTIME_QDateTime(X509_CRL_get0_nextUpdate(x), NULL);
-
- STACK_OF(X509_REVOKED)* revokeStack = X509_CRL_get_REVOKED(x);
-
- for (int i = 0; i < sk_X509_REVOKED_num(revokeStack); ++i) {
- X509_REVOKED *rev = sk_X509_REVOKED_value(revokeStack, i);
- BigInteger serial = bn2bi(ASN1_INTEGER_to_BN(X509_REVOKED_get0_serialNumber(rev), NULL));
- QDateTime time = ASN1_UTCTIME_QDateTime( X509_REVOKED_get0_revocationDate(rev), NULL);
- QCA::CRLEntry::Reason reason = QCA::CRLEntry::Unspecified;
- int pos = X509_REVOKED_get_ext_by_NID(rev, NID_crl_reason, -1);
- if (pos != -1) {
- X509_EXTENSION *ex = X509_REVOKED_get_ext(rev, pos);
- if(ex) {
- int *result = (int*) X509V3_EXT_d2i(ex);
- switch (*result) {
- case 0:
- reason = QCA::CRLEntry::Unspecified;
- break;
- case 1:
- reason = QCA::CRLEntry::KeyCompromise;
- break;
- case 2:
- reason = QCA::CRLEntry::CACompromise;
- break;
- case 3:
- reason = QCA::CRLEntry::AffiliationChanged;
- break;
- case 4:
- reason = QCA::CRLEntry::Superseded;
- break;
- case 5:
- reason = QCA::CRLEntry::CessationOfOperation;
- break;
- case 6:
- reason = QCA::CRLEntry::CertificateHold;
- break;
- case 8:
- reason = QCA::CRLEntry::RemoveFromCRL;
- break;
- case 9:
- reason = QCA::CRLEntry::PrivilegeWithdrawn;
- break;
- case 10:
- reason = QCA::CRLEntry::AACompromise;
- break;
- default:
- reason = QCA::CRLEntry::Unspecified;
- break;
- }
- ASN1_INTEGER_free((ASN1_INTEGER*)result);
- }
- }
- CRLEntry thisEntry( serial, time, reason);
- p.revoked.append(thisEntry);
- }
-
- const ASN1_BIT_STRING *signature;
-
- X509_CRL_get0_signature(x, &signature, NULL);
- if(signature)
- {
- p.sig = QByteArray(signature->length, 0);
- for (int i=0; i< signature->length; i++)
- p.sig[i] = signature->data[i];
- }
-
-
- switch( X509_CRL_get_signature_nid(x) )
- {
- case NID_sha1WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA1;
- break;
- case NID_md5WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_MD5;
- break;
-#ifdef HAVE_OPENSSL_MD2
- case NID_md2WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_MD2;
- break;
-#endif
- case NID_ripemd160WithRSA:
- p.sigalgo = QCA::EMSA3_RIPEMD160;
- break;
- case NID_dsaWithSHA1:
- p.sigalgo = QCA::EMSA1_SHA1;
- break;
- case NID_sha224WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA224;
- break;
- case NID_sha256WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA256;
- break;
- case NID_sha384WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA384;
- break;
- case NID_sha512WithRSAEncryption:
- p.sigalgo = QCA::EMSA3_SHA512;
- break;
- default:
- qWarning() << "Unknown signature value: " << X509_CRL_get_signature_nid(x);
- p.sigalgo = QCA::SignatureUnknown;
- }
-
- int pos = X509_CRL_get_ext_by_NID(x, NID_authority_key_identifier, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_CRL_get_ext(x, pos);
- if(ex)
- p.issuerId += get_cert_issuer_key_id(ex);
- }
-
- p.number = -1;
- pos = X509_CRL_get_ext_by_NID(x, NID_crl_number, -1);
- if(pos != -1)
- {
- X509_EXTENSION *ex = X509_CRL_get_ext(x, pos);
- if(ex) {
- int *result = (int*) X509V3_EXT_d2i(ex);
- p.number = (*result);
- ASN1_INTEGER_free((ASN1_INTEGER*)result);
- }
- }
-
- // FIXME: super hack
- CertificateOptions opts;
- opts.setInfo(issuer);
- p.issuer = opts.infoOrdered();
-
- _props = p;
- }
-};
+ virtual bool certificateRequested() const
+ {
+ // TODO
+ return false;
+ }
-//----------------------------------------------------------------------------
-// MyCertCollectionContext
-//----------------------------------------------------------------------------
-class MyCertCollectionContext : public CertCollectionContext
-{
- Q_OBJECT
-public:
- MyCertCollectionContext(Provider *p) : CertCollectionContext(p)
- {
- }
-
- virtual Provider::Context *clone() const
- {
- return new MyCertCollectionContext(*this);
- }
-
- virtual QByteArray toPKCS7(const QList<CertContext*> &certs, const QList<CRLContext*> &crls) const
- {
- // TODO: implement
- Q_UNUSED(certs);
- Q_UNUSED(crls);
- return QByteArray();
- }
-
- virtual ConvertResult fromPKCS7(const QByteArray &a, QList<CertContext*> *certs, QList<CRLContext*> *crls) const
- {
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, a.data(), a.size());
- PKCS7 *p7 = d2i_PKCS7_bio(bi, NULL);
- BIO_free(bi);
- if(!p7)
- return ErrorDecode;
-
- STACK_OF(X509) *xcerts = 0;
- STACK_OF(X509_CRL) *xcrls = 0;
-
- int i = OBJ_obj2nid(p7->type);
- if(i == NID_pkcs7_signed)
- {
- xcerts = p7->d.sign->cert;
- xcrls = p7->d.sign->crl;
- }
- else if(i == NID_pkcs7_signedAndEnveloped)
- {
- xcerts = p7->d.signed_and_enveloped->cert;
- xcrls = p7->d.signed_and_enveloped->crl;
- }
-
- QList<CertContext*> _certs;
- QList<CRLContext*> _crls;
-
- if(xcerts)
- {
- for(int n = 0; n < sk_X509_num(xcerts); ++n)
- {
- MyCertContext *cc = new MyCertContext(provider());
- cc->fromX509(sk_X509_value(xcerts, n));
- _certs += cc;
- }
- }
- if(xcrls)
- {
- for(int n = 0; n < sk_X509_CRL_num(xcrls); ++n)
- {
- MyCRLContext *cc = new MyCRLContext(provider());
- cc->fromX509(sk_X509_CRL_value(xcrls, n));
- _crls += cc;
- }
- }
-
- PKCS7_free(p7);
-
- *certs = _certs;
- *crls = _crls;
-
- return ConvertGood;
- }
-};
+ virtual QList<CertificateInfoOrdered> issuerList() const
+ {
+ // TODO
+ return QList<CertificateInfoOrdered>();
+ }
-static bool usage_check(const MyCertContext &cc, UsageMode u)
-{
- if (cc._props.constraints.isEmpty() ) {
- // then any usage is OK
- return true;
- }
-
- switch (u)
- {
- case UsageAny :
- return true;
- break;
- case UsageTLSServer :
- return cc._props.constraints.contains(ServerAuth);
- break;
- case UsageTLSClient :
- return cc._props.constraints.contains(ClientAuth);
- break;
- case UsageCodeSigning :
- return cc._props.constraints.contains(CodeSigning);
- break;
- case UsageEmailProtection :
- return cc._props.constraints.contains(EmailProtection);
- break;
- case UsageTimeStamping :
- return cc._props.constraints.contains(TimeStamping);
- break;
- case UsageCRLSigning :
- return cc._props.constraints.contains(CRLSign);
- break;
- default:
- return true;
- }
-}
+ virtual SessionInfo sessionInfo() const
+ {
+ SessionInfo sessInfo;
-Validity MyCertContext::validate(const QList<CertContext*> &trusted, const QList<CertContext*> &untrusted, const QList<CRLContext*> &crls, UsageMode u, ValidateFlags vf) const
-{
- // TODO
- Q_UNUSED(vf);
-
- STACK_OF(X509) *trusted_list = sk_X509_new_null();
- STACK_OF(X509) *untrusted_list = sk_X509_new_null();
- QList<X509_CRL*> crl_list;
-
- int n;
- for(n = 0; n < trusted.count(); ++n)
- {
- const MyCertContext *cc = static_cast<const MyCertContext *>(trusted[n]);
- X509 *x = cc->item.cert;
- X509_up_ref(x);
- sk_X509_push(trusted_list, x);
- }
- for(n = 0; n < untrusted.count(); ++n)
- {
- const MyCertContext *cc = static_cast<const MyCertContext *>(untrusted[n]);
- X509 *x = cc->item.cert;
- X509_up_ref(x);
- sk_X509_push(untrusted_list, x);
- }
- for(n = 0; n < crls.count(); ++n)
- {
- const MyCRLContext *cc = static_cast<const MyCRLContext *>(crls[n]);
- X509_CRL *x = cc->item.crl;
- X509_CRL_up_ref(x);
- crl_list.append(x);
- }
-
- const MyCertContext *cc = this;
- X509 *x = cc->item.cert;
-
- // verification happens through a store "context"
- X509_STORE_CTX *ctx = X509_STORE_CTX_new();
-
- // make a store of crls
- X509_STORE *store = X509_STORE_new();
- for(int n = 0; n < crl_list.count(); ++n)
- X509_STORE_add_crl(store, crl_list[n]);
-
- // the first initialization handles untrusted certs, crls, and target cert
- X509_STORE_CTX_init(ctx, store, x, untrusted_list);
-
- // this initializes the trusted certs
- X509_STORE_CTX_trusted_stack(ctx, trusted_list);
-
- // verify!
- int ret = X509_verify_cert(ctx);
- int err = -1;
- if(!ret)
- err = X509_STORE_CTX_get_error(ctx);
-
- // cleanup
- X509_STORE_CTX_free(ctx);
- X509_STORE_free(store);
-
- sk_X509_pop_free(trusted_list, X509_free);
- sk_X509_pop_free(untrusted_list, X509_free);
- for(int n = 0; n < crl_list.count(); ++n)
- X509_CRL_free(crl_list[n]);
-
- if(!ret)
- return convert_verify_error(err);
-
- if(!usage_check(*cc, u))
- return ErrorInvalidPurpose;
-
- return ValidityGood;
-}
+ SSL_SESSION *session = SSL_get0_session(ssl);
+ sessInfo.isCompressed = (0 != SSL_SESSION_get_compress_id(session));
+ int ssl_version = SSL_version(ssl);
-Validity MyCertContext::validate_chain(const QList<CertContext*> &chain, const QList<CertContext*> &trusted, const QList<CRLContext*> &crls, UsageMode u, ValidateFlags vf) const
-{
- // TODO
- Q_UNUSED(vf);
-
- STACK_OF(X509) *trusted_list = sk_X509_new_null();
- STACK_OF(X509) *untrusted_list = sk_X509_new_null();
- QList<X509_CRL*> crl_list;
-
- int n;
- for(n = 0; n < trusted.count(); ++n)
- {
- const MyCertContext *cc = static_cast<const MyCertContext *>(trusted[n]);
- X509 *x = cc->item.cert;
- X509_up_ref(x);
- sk_X509_push(trusted_list, x);
- }
- for(n = 1; n < chain.count(); ++n)
- {
- const MyCertContext *cc = static_cast<const MyCertContext *>(chain[n]);
- X509 *x = cc->item.cert;
- X509_up_ref(x);
- sk_X509_push(untrusted_list, x);
- }
- for(n = 0; n < crls.count(); ++n)
- {
- const MyCRLContext *cc = static_cast<const MyCRLContext *>(crls[n]);
- X509_CRL *x = cc->item.crl;
- X509_CRL_up_ref(x);
- crl_list.append(x);
- }
-
- const MyCertContext *cc = static_cast<const MyCertContext *>(chain[0]);
- X509 *x = cc->item.cert;
-
- // verification happens through a store "context"
- X509_STORE_CTX *ctx = X509_STORE_CTX_new();
-
- // make a store of crls
- X509_STORE *store = X509_STORE_new();
- for(int n = 0; n < crl_list.count(); ++n)
- X509_STORE_add_crl(store, crl_list[n]);
-
- // the first initialization handles untrusted certs, crls, and target cert
- X509_STORE_CTX_init(ctx, store, x, untrusted_list);
-
- // this initializes the trusted certs
- X509_STORE_CTX_trusted_stack(ctx, trusted_list);
-
- // verify!
- int ret = X509_verify_cert(ctx);
- int err = -1;
- if(!ret)
- err = X509_STORE_CTX_get_error(ctx);
-
- // grab the chain, which may not be fully populated
- STACK_OF(X509) *xchain = X509_STORE_CTX_get_chain(ctx);
-
- // make sure the chain is what we expect. the reason we need to do
- // this is because I don't think openssl cares about the order of
- // input. that is, if there's a chain A<-B<-C, and we input A as
- // the base cert, with B and C as the issuers, we will get a
- // successful validation regardless of whether the issuer list is
- // in the order B,C or C,B. we don't want an input chain of A,C,B
- // to be considered correct, so we must account for that here.
- QList<const MyCertContext*> expected;
- for(int n = 0; n < chain.count(); ++n)
- expected += static_cast<const MyCertContext *>(chain[n]);
- if(!xchain || !sameChain(xchain, expected))
- err = ErrorValidityUnknown;
-
- // cleanup
- X509_STORE_CTX_free(ctx);
- X509_STORE_free(store);
-
- sk_X509_pop_free(trusted_list, X509_free);
- sk_X509_pop_free(untrusted_list, X509_free);
- for(int n = 0; n < crl_list.count(); ++n)
- X509_CRL_free(crl_list[n]);
-
- if(!ret)
- return convert_verify_error(err);
-
- if(!usage_check(*cc, u))
- return ErrorInvalidPurpose;
-
- return ValidityGood;
-}
+ if (ssl_version == TLS1_VERSION) {
+ sessInfo.version = TLS::TLS_v1;
+ } else if (ssl_version == SSL3_VERSION) {
+ sessInfo.version = TLS::SSL_v3;
+ } else if (ssl_version == SSL2_VERSION) {
+ sessInfo.version = TLS::SSL_v2;
+ } else {
+ qDebug("unexpected version response");
+ sessInfo.version = TLS::TLS_v1;
+ }
-class MyPKCS12Context : public PKCS12Context
-{
-public:
- MyPKCS12Context(Provider *p) : PKCS12Context(p)
- {
- }
-
- ~MyPKCS12Context()
- {
- }
-
- virtual Provider::Context *clone() const
- {
- return 0;
- }
-
- virtual QByteArray toPKCS12(const QString &name, const QList<const CertContext*> &chain, const PKeyContext &priv, const SecureArray &passphrase) const
- {
- if(chain.count() < 1)
- return QByteArray();
-
- X509 *cert = static_cast<const MyCertContext *>(chain[0])->item.cert;
- STACK_OF(X509) *ca = sk_X509_new_null();
- if(chain.count() > 1)
- {
- for(int n = 1; n < chain.count(); ++n)
- {
- X509 *x = static_cast<const MyCertContext *>(chain[n])->item.cert;
- X509_up_ref(x);
- sk_X509_push(ca, x);
- }
- }
- const MyPKeyContext &pk = static_cast<const MyPKeyContext &>(priv);
- PKCS12 *p12 = PKCS12_create((char *)passphrase.data(), (char *)name.toLatin1().data(), pk.get_pkey(), cert, ca, 0, 0, 0, 0, 0);
- sk_X509_pop_free(ca, X509_free);
-
- if(!p12)
- return QByteArray();
-
- BIO *bo = BIO_new(BIO_s_mem());
- i2d_PKCS12_bio(bo, p12);
- QByteArray out = bio2ba(bo);
- return out;
- }
-
- virtual ConvertResult fromPKCS12(const QByteArray &in, const SecureArray &passphrase, QString *name, QList<CertContext*> *chain, PKeyContext **priv) const
- {
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- PKCS12 *p12 = d2i_PKCS12_bio(bi, NULL);
- if(!p12)
- return ErrorDecode;
-
- EVP_PKEY *pkey;
- X509 *cert;
- STACK_OF(X509) *ca = NULL;
- if(!PKCS12_parse(p12, passphrase.data(), &pkey, &cert, &ca))
- {
- PKCS12_free(p12);
- return ErrorDecode;
- }
- PKCS12_free(p12);
-
- // require private key
- if(!pkey)
- {
- if(cert)
- X509_free(cert);
- if(ca)
- sk_X509_pop_free(ca, X509_free);
- return ErrorDecode;
- }
-
- // TODO: require cert
-
- int aliasLength;
- char *aliasData = (char*)X509_alias_get0(cert, &aliasLength);
- *name = QString::fromLatin1(aliasData, aliasLength);
-
- MyPKeyContext *pk = new MyPKeyContext(provider());
- PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free()
- pk->k = k;
- *priv = pk;
-
- QList<CertContext*> certs;
- if(cert)
- {
- MyCertContext *cc = new MyCertContext(provider());
- cc->fromX509(cert);
- certs.append(cc);
- X509_free(cert);
- }
- if(ca)
- {
- // TODO: reorder in chain-order?
- // TODO: throw out certs that don't fit the chain?
- for(int n = 0; n < sk_X509_num(ca); ++n)
- {
- MyCertContext *cc = new MyCertContext(provider());
- cc->fromX509(sk_X509_value(ca, n));
- certs.append(cc);
- }
- sk_X509_pop_free(ca, X509_free);
- }
-
- // reorder, throw out
- QCA::CertificateChain ch;
- for(int n = 0; n < certs.count(); ++n)
- {
- QCA::Certificate cert;
- cert.change(certs[n]);
- ch += cert;
- }
- certs.clear();
- ch = ch.complete(QList<QCA::Certificate>());
- for(int n = 0; n < ch.count(); ++n)
- {
- MyCertContext *cc = (MyCertContext *)ch[n].context();
- certs += (new MyCertContext(*cc));
- }
- ch.clear();
-
- *chain = certs;
- return ConvertGood;
- }
-};
+ sessInfo.cipherSuite = cipherIDtoString(sessInfo.version,
+ SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
-//==========================================================
-static QString cipherIDtoString( const TLS::Version &version, const unsigned long &cipherID)
-{
- if (TLS::TLS_v1 == version) {
- switch( cipherID & 0xFFFF ) {
- case 0x0000:
- // RFC 2246 A.5
- return QString("TLS_NULL_WITH_NULL_NULL");
- break;
- case 0x0001:
- // RFC 2246 A.5
- return QString("TLS_RSA_WITH_NULL_MD5");
- break;
- case 0x0002:
- // RFC 2246 A.5
- return QString("TLS_RSA_WITH_NULL_SHA");
- break;
- case 0x0003:
- // RFC 2246 A.5
- return QString("TLS_RSA_EXPORT_WITH_RC4_40_MD5");
- break;
- case 0x0004:
- // RFC 2246 A.5
- return QString("TLS_RSA_WITH_RC4_128_MD5");
- break;
- case 0x0005:
- // RFC 2246 A.5
- return QString("TLS_RSA_WITH_RC4_128_SHA");
- break;
- case 0x0006:
- // RFC 2246 A.5
- return QString("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5");
- break;
- case 0x0007:
- // RFC 2246 A.5
- return QString("TLS_RSA_WITH_IDEA_CBC_SHA");
- break;
- case 0x0008:
- // RFC 2246 A.5
- return QString("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x0009:
- // RFC 2246 A.5
- return QString("TLS_RSA_WITH_DES_CBC_SHA");
- break;
- case 0x000A:
- // RFC 2246 A.5
- return QString("TLS_RSA_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x000B:
- // RFC 2246 A.5
- return QString("TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x000C:
- // RFC 2246 A.5
- return QString("TLS_DH_DSS_WITH_DES_CBC_SHA");
- break;
- case 0x000D:
- // RFC 2246 A.5
- return QString("TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x000E:
- // RFC 2246 A.5
- return QString("TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x000F:
- // RFC 2246 A.5
- return QString("TLS_DH_RSA_WITH_DES_CBC_SHA");
- break;
- case 0x0010:
- // RFC 2246 A.5
- return QString("TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0011:
- // RFC 2246 A.5
- return QString("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x0012:
- // RFC 2246 A.5
- return QString("TLS_DHE_DSS_WITH_DES_CBC_SHA");
- break;
- case 0x0013:
- // RFC 2246 A.5
- return QString("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0014:
- // RFC 2246 A.5
- return QString("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x0015:
- // RFC 2246 A.5
- return QString("TLS_DHE_RSA_WITH_DES_CBC_SHA");
- break;
- case 0x0016:
- // RFC 2246 A.5
- return QString("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0017:
- // RFC 2246 A.5
- return QString("TLS_DH_anon_EXPORT_WITH_RC4_40_MD5");
- break;
- case 0x0018:
- // RFC 2246 A.5
- return QString("TLS_DH_anon_WITH_RC4_128_MD5");
- break;
- case 0x0019:
- // RFC 2246 A.5
- return QString("TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x001A:
- // RFC 2246 A.5
- return QString("TLS_DH_anon_WITH_DES_CBC_SHA");
- break;
- case 0x001B:
- // RFC 2246 A.5
- return QString("TLS_DH_anon_WITH_3DES_EDE_CBC_SHA");
- break;
-
- // 0x001C and 0x001D are reserved to avoid collision with SSL3 Fortezza.
- case 0x001E:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_DES_CBC_SHA");
- break;
- case 0x001F:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0020:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_RC4_128_SHA");
- break;
- case 0x0021:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_IDEA_CBC_SHA");
- break;
- case 0x0022:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_DES_CBC_MD5");
- break;
- case 0x0023:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_3DES_EDE_CBC_MD5");
- break;
- case 0x0024:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_RC4_128_MD5");
- break;
- case 0x0025:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_WITH_IDEA_CBC_MD5");
- break;
- case 0x0026:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA");
- break;
- case 0x0027:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA");
- break;
- case 0x0028:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_EXPORT_WITH_RC4_40_SHA");
- break;
- case 0x0029:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5");
- break;
- case 0x002A:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5");
- break;
- case 0x002B:
- // RFC 2712 Section 3
- return QString("TLS_KRB5_EXPORT_WITH_RC4_40_MD5");
- break;
-
- case 0x002F:
- // RFC 3268
- return QString("TLS_RSA_WITH_AES_128_CBC_SHA");
- break;
- case 0x0030:
- // RFC 3268
- return QString("TLS_DH_DSS_WITH_AES_128_CBC_SHA");
- break;
- case 0x0031:
- // RFC 3268
- return QString("TLS_DH_RSA_WITH_AES_128_CBC_SHA");
- break;
- case 0x0032:
- // RFC 3268
- return QString("TLS_DHE_DSS_WITH_AES_128_CBC_SHA");
- break;
- case 0x0033:
- // RFC 3268
- return QString("TLS_DHE_RSA_WITH_AES_128_CBC_SHA");
- break;
- case 0x0034:
- // RFC 3268
- return QString("TLS_DH_anon_WITH_AES_128_CBC_SHA");
- break;
- case 0x0035:
- // RFC 3268
- return QString("TLS_RSA_WITH_AES_256_CBC_SHA");
- break;
- case 0x0036:
- // RFC 3268
- return QString("TLS_DH_DSS_WITH_AES_256_CBC_SHA");
- break;
- case 0x0037:
- // RFC 3268
- return QString("TLS_DH_RSA_WITH_AES_256_CBC_SHA");
- break;
- case 0x0038:
- // RFC 3268
- return QString("TLS_DHE_DSS_WITH_AES_256_CBC_SHA");
- break;
- case 0x0039:
- // RFC 3268
- return QString("TLS_DHE_RSA_WITH_AES_256_CBC_SHA");
- break;
- case 0x003A:
- // RFC 3268
- return QString("TLS_DH_anon_WITH_AES_256_CBC_SHA");
- break;
-
- // TODO: 0x0041 -> 0x0046 are from RFC4132 (Camellia)
-
- case 0x0060:
- // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
- return QString("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_MD5");
- break;
- case 0x0061:
- // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
- return QString("TLS_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5");
- break;
- case 0x0062:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("TLS_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA");
- break;
- case 0x0063:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("TLS_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA");
- break;
- case 0x0064:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("TLS_CK_RSA_EXPORT1024_WITH_RC4_56_SHA");
- break;
- case 0x0065:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("TLS_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA");
- break;
- case 0x0066:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("TLS_CK_DHE_DSS_WITH_RC4_128_SHA");
- break;
-
- // TODO: 0x0084 -> 0x0089 are from RFC4132 (Camellia)
-
- // TODO: 0x008A -> 0x0095 are from RFC4279 (PSK)
-
- // TODO: 0xC000 -> 0xC019 are from the ECC draft
-
- default:
- return QString("TLS algo to be added: %1").arg(cipherID & 0xffff, 0, 16);
- break;
- }
- } else if (TLS::SSL_v3 == version) {
- switch( cipherID & 0xFFFF ) {
- case 0x0000:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_NULL_WITH_NULL_NULL");
- break;
- case 0x0001:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_WITH_NULL_MD5");
- break;
- case 0x0002:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_WITH_NULL_SHA");
- break;
- case 0x0003:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_EXPORT_WITH_RC4_40_MD5");
- break;
- case 0x0004:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_WITH_RC4_128_MD5");
- break;
- case 0x0005:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_WITH_RC4_128_SHA");
- break;
- case 0x0006:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5");
- break;
- case 0x0007:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_WITH_IDEA_CBC_SHA");
- break;
- case 0x0008:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x0009:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_WITH_DES_CBC_SHA");
- break;
- case 0x000A:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_RSA_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x000B:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_DSS_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x000C:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_DSS_WITH_DES_CBC_SHA");
- break;
- case 0x000D:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_DSS_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x000E:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_RSA_WITH_DES_CBC_SHA");
- break;
- case 0x000F:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_RSA_WITH_DES_CBC_SHA");
- break;
- case 0x0010:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_RSA_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0011:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x0012:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DHE_DSS_WITH_DES_CBC_SHA");
- break;
- case 0x0013:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0014:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x0015:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DHE_RSA_WITH_DES_CBC_SHA");
- break;
- case 0x0016:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0017:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SL_DH_anon_EXPORT_WITH_RC4_40_MD5");
- break;
- case 0x0018:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_anon_WITH_RC4_128_MD5");
- break;
- case 0x0019:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA");
- break;
- case 0x001A:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_anon_WITH_DES_CBC_SHA");
- break;
- case 0x001B:
- // From the Netscape SSL3 Draft (nov 1996)
- return QString("SSL_DH_anon_WITH_3DES_EDE_CBC_SHA");
- break;
-
- // TODO: Sort out the Fortezza mess...
-
- // These aren't in the Netscape SSL3 draft, but openssl does
- // allow you to use them with SSL3.
- case 0x001E:
- return QString("SSL_KRB5_WITH_DES_CBC_SHA");
- break;
- case 0x001F:
- return QString("SSL_KRB5_WITH_3DES_EDE_CBC_SHA");
- break;
- case 0x0020:
- return QString("SSL_KRB5_WITH_RC4_128_SHA");
- break;
- case 0x0021:
- return QString("SSL_KRB5_WITH_IDEA_CBC_SHA");
- break;
- case 0x0022:
- return QString("SSL_KRB5_WITH_DES_CBC_MD5");
- break;
- case 0x0023:
- return QString("SSL_KRB5_WITH_3DES_EDE_CBC_MD5");
- break;
- case 0x0024:
- return QString("SSL_KRB5_WITH_RC4_128_MD5");
- break;
- case 0x0025:
- return QString("SSL_KRB5_WITH_IDEA_CBC_MD5");
- break;
- case 0x0026:
- return QString("SSL_KRB5_EXPORT_WITH_DES_CBC_40_SHA");
- break;
- case 0x0027:
- return QString("SSL_KRB5_EXPORT_WITH_RC2_CBC_40_SHA");
- break;
- case 0x0028:
- return QString("SSL_KRB5_EXPORT_WITH_RC4_40_SHA");
- break;
- case 0x0029:
- return QString("SSL_KRB5_EXPORT_WITH_DES_CBC_40_MD5");
- break;
- case 0x002A:
- return QString("SSL_KRB5_EXPORT_WITH_RC2_CBC_40_MD5");
- break;
- case 0x002B:
- return QString("SSL_KRB5_EXPORT_WITH_RC4_40_MD5");
- break;
- case 0x002F:
- return QString("SSL_RSA_WITH_AES_128_CBC_SHA");
- break;
- case 0x0030:
- return QString("SSL_DH_DSS_WITH_AES_128_CBC_SHA");
- break;
- case 0x0031:
- return QString("SSL_DH_RSA_WITH_AES_128_CBC_SHA");
- break;
- case 0x0032:
- return QString("SSL_DHE_DSS_WITH_AES_128_CBC_SHA");
- break;
- case 0x0033:
- return QString("SSL_DHE_RSA_WITH_AES_128_CBC_SHA");
- break;
- case 0x0034:
- return QString("SSL_DH_anon_WITH_AES_128_CBC_SHA");
- break;
- case 0x0035:
- return QString("SSL_RSA_WITH_AES_256_CBC_SHA");
- break;
- case 0x0036:
- return QString("SSL_DH_DSS_WITH_AES_256_CBC_SHA");
- break;
- case 0x0037:
- return QString("SSL_DH_RSA_WITH_AES_256_CBC_SHA");
- break;
- case 0x0038:
- return QString("SSL_DHE_DSS_WITH_AES_256_CBC_SHA");
- break;
- case 0x0039:
- return QString("SSL_DHE_RSA_WITH_AES_256_CBC_SHA");
- break;
- case 0x003A:
- return QString("SSL_DH_anon_WITH_AES_256_CBC_SHA");
- break;
- case 0x0060:
- // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
- return QString("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_MD5");
- break;
- case 0x0061:
- // Was meant to be from draft-ietf-tls-56-bit-ciphersuites-01.txt, but isn't
- return QString("SSL_CK_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5");
- break;
- case 0x0062:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("SSL_CK_RSA_EXPORT1024_WITH_DES_CBC_SHA");
- break;
- case 0x0063:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("SSL_CK_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA");
- break;
- case 0x0064:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("SSL_CK_RSA_EXPORT1024_WITH_RC4_56_SHA");
- break;
- case 0x0065:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("SSL_CK_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA");
- break;
- case 0x0066:
- // Apparently from draft-ietf-tls-56-bit-ciphersuites-01.txt
- return QString("SSL_CK_DHE_DSS_WITH_RC4_128_SHA");
- break;
- default:
- return QString("SSL3 to be added: %1").arg(cipherID & 0xffff, 0, 16);
- break;
- }
- } else if (TLS::SSL_v2 == version) {
- switch( cipherID & 0xffffff) {
- case 0x010080:
- // From the Netscape SSL2 Draft Section C.4 (nov 1994)
- return QString("SSL_CK_RC4_128_WITH_MD5");
- break;
- case 0x020080:
- // From the Netscape SSL2 Draft Section C.4 (nov 1994)
- return QString("SSL_CK_RC4_128_EXPORT40_WITH_MD5");
- break;
- case 0x030080:
- // From the Netscape SSL2 Draft Section C.4 (nov 1994)
- return QString("SSL_CK_RC2_128_CBC_WITH_MD5");
- break;
- case 0x040080:
- // From the Netscape SSL2 Draft Section C.4 (nov 1994)
- return QString("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5");
- break;
- case 0x050080:
- // From the Netscape SSL2 Draft Section C.4 (nov 1994)
- return QString("SSL_CK_RC4_128_EXPORT40_WITH_MD5");
- break;
- case 0x060040:
- // From the Netscape SSL2 Draft Section C.4 (nov 1994)
- return QString("SSL_CK_DES_64_CBC_WITH_MD5");
- break;
- case 0x0700C0:
- // From the Netscape SSL2 Draft Section C.4 (nov 1994)
- return QString("SSL_CK_DES_192_EDE3_CBC_WITH_MD5");
- break;
- case 0x080080:
- // From the openssl source, which says "MS hack"
- return QString("SSL_CK_RC4_64_WITH_MD5");
- break;
- default:
- return QString("SSL2 to be added: %1").arg(cipherID & 0xffffff, 0, 16);
- break;
- }
- }
- else {
- return QString("Unknown version!");
- }
-}
+ sessInfo.cipherMaxBits = SSL_get_cipher_bits(ssl, &(sessInfo.cipherBits));
-// TODO: test to ensure there is no cert-test lag
-static bool ssl_init = false;
-class MyTLSContext : public TLSContext
-{
-public:
- enum { Good, TryAgain, Bad };
- enum { Idle, Connect, Accept, Handshake, Active, Closing };
+ sessInfo.id = 0; // TODO: session resuming
- bool serv; // true if we are acting as a server
- int mode;
- QByteArray sendQueue;
- QByteArray recvQueue;
+ return sessInfo;
+ }
- CertificateCollection trusted;
- Certificate cert, peercert; // TODO: support cert chains
- PrivateKey key;
- QString targetHostName;
+ virtual QByteArray unprocessed()
+ {
+ QByteArray a;
+ int size = BIO_pending(rbio);
+ if (size <= 0) {
+ return a;
+ }
+ a.resize(size);
+
+ int r = BIO_read(rbio, a.data(), size);
+ if (r <= 0) {
+ a.resize(0);
+ return a;
+ }
+ if (r != size) {
+ a.resize(r);
+ }
+ return a;
+ }
- Result result_result;
- QByteArray result_to_net;
- int result_encoded;
- QByteArray result_plain;
+ virtual Validity peerCertificateValidity() const
+ {
+ return vr;
+ }
- SSL *ssl;
-#if OPENSSL_VERSION_NUMBER >= 0x00909000L
- const SSL_METHOD *method;
-#else
- SSL_METHOD *method;
-#endif
- SSL_CTX *context;
- BIO *rbio, *wbio;
- Validity vr;
- bool v_eof;
-
- MyTLSContext(Provider *p) : TLSContext(p, "tls")
- {
- if(!ssl_init)
- {
- SSL_library_init();
- SSL_load_error_strings();
- ssl_init = true;
- }
-
- ssl = 0;
- context = 0;
- reset();
- }
-
- ~MyTLSContext()
- {
- reset();
- }
-
- virtual Provider::Context *clone() const
- {
- return 0;
- }
-
- virtual void reset()
- {
- if(ssl)
- {
- SSL_free(ssl);
- ssl = 0;
- }
- if(context)
- {
- SSL_CTX_free(context);
- context = 0;
- }
-
- cert = Certificate();
- key = PrivateKey();
-
- sendQueue.resize(0);
- recvQueue.resize(0);
- mode = Idle;
- peercert = Certificate();
- vr = ErrorValidityUnknown;
- v_eof = false;
- }
-
- // dummy verification function for SSL_set_verify()
- static int ssl_verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx)
- {
- Q_UNUSED(preverify_ok);
- Q_UNUSED(x509_ctx);
-
- // don't terminate handshake in case of verification failure
- return 1;
- }
-
- virtual QStringList supportedCipherSuites(const TLS::Version &version) const
- {
- OpenSSL_add_ssl_algorithms();
- SSL_CTX *ctx = 0;
- switch (version) {
-#if !defined(OPENSSL_NO_SSL2) && !defined(OSSL_110)
- case TLS::SSL_v2:
- ctx = SSL_CTX_new(SSLv2_client_method());
- break;
-#endif
-#ifndef OPENSSL_NO_SSL3_METHOD
- case TLS::SSL_v3:
- ctx = SSL_CTX_new(SSLv3_client_method());
- break;
-#endif
- case TLS::TLS_v1:
- ctx = SSL_CTX_new(TLSv1_client_method());
- break;
- case TLS::DTLS_v1:
- default:
- /* should not happen - should be in a "dtls" provider*/
- qWarning("Unexpected enum in cipherSuites");
- ctx = 0;
- }
- if (NULL == ctx)
- return QStringList();
-
- SSL *ssl = SSL_new(ctx);
- if (NULL == ssl) {
- SSL_CTX_free(ctx);
- return QStringList();
- }
-
- STACK_OF(SSL_CIPHER) *sk = SSL_get_ciphers(ssl);
- QStringList cipherList;
- for(int i = 0; i < sk_SSL_CIPHER_num(sk); ++i) {
- const SSL_CIPHER *thisCipher = sk_SSL_CIPHER_value(sk, i);
- cipherList += cipherIDtoString(version, SSL_CIPHER_get_id(thisCipher));
- }
-
- SSL_free(ssl);
- SSL_CTX_free(ctx);
-
- return cipherList;
- }
-
- virtual bool canCompress() const
- {
- // TODO
- return false;
- }
-
- virtual bool canSetHostName() const
- {
- // TODO
- return false;
- }
-
- virtual int maxSSF() const
- {
- // TODO
- return 256;
- }
-
- virtual void setConstraints(int minSSF, int maxSSF)
- {
- // TODO
- Q_UNUSED(minSSF);
- Q_UNUSED(maxSSF);
- }
-
- virtual void setConstraints(const QStringList &cipherSuiteList)
- {
- // TODO
- Q_UNUSED(cipherSuiteList);
- }
-
- virtual void setup(bool serverMode, const QString &hostName, bool compress)
- {
- serv = serverMode;
- if ( false == serverMode ) {
- // client
- targetHostName = hostName;
- }
- Q_UNUSED(compress); // TODO
- }
-
- virtual void setTrustedCertificates(const CertificateCollection &_trusted)
- {
- trusted = _trusted;
- }
-
- virtual void setIssuerList(const QList<CertificateInfoOrdered> &issuerList)
- {
- Q_UNUSED(issuerList); // TODO
- }
-
- virtual void setCertificate(const CertificateChain &_cert, const PrivateKey &_key)
- {
- if(!_cert.isEmpty())
- cert = _cert.primary(); // TODO: take the whole chain
- key = _key;
- }
-
- virtual void setSessionId(const TLSSessionContext &id)
- {
- // TODO
- Q_UNUSED(id);
- }
-
- virtual void shutdown()
- {
- mode = Closing;
- }
-
- virtual void start()
- {
- bool ok;
- if(serv)
- ok = priv_startServer();
- else
- ok = priv_startClient();
- result_result = ok ? Success : Error;
-
- doResultsReady();
- }
-
- virtual void update(const QByteArray &from_net, const QByteArray &from_app)
- {
- if(mode == Active)
- {
- bool ok = true;
- if(!from_app.isEmpty())
- ok = priv_encode(from_app, &result_to_net, &result_encoded);
- if(ok)
- ok = priv_decode(from_net, &result_plain, &result_to_net);
- result_result = ok ? Success : Error;
- }
- else if(mode == Closing)
- result_result = priv_shutdown(from_net, &result_to_net);
- else
- result_result = priv_handshake(from_net, &result_to_net);
-
- //printf("update (from_net=%d, to_net=%d, from_app=%d, to_app=%d)\n", from_net.size(), result_to_net.size(), from_app.size(), result_plain.size());
-
- doResultsReady();
- }
-
- bool priv_startClient()
- {
- //serv = false;
- method = SSLv23_client_method();
- if(!init())
- return false;
- mode = Connect;
- return true;
- }
-
- bool priv_startServer()
- {
- //serv = true;
- method = SSLv23_server_method();
- if(!init())
- return false;
- mode = Accept;
- return true;
- }
-
- Result priv_handshake(const QByteArray &from_net, QByteArray *to_net)
- {
- if(!from_net.isEmpty())
- BIO_write(rbio, from_net.data(), from_net.size());
-
- if(mode == Connect)
- {
- int ret = doConnect();
- if(ret == Good)
- {
- mode = Handshake;
- }
- else if(ret == Bad)
- {
- reset();
- return Error;
- }
- }
-
- if(mode == Accept)
- {
- int ret = doAccept();
- if(ret == Good)
- {
- getCert();
- mode = Active;
- }
- else if(ret == Bad)
- {
- reset();
- return Error;
- }
- }
-
- if(mode == Handshake)
- {
- int ret = doHandshake();
- if(ret == Good)
- {
- getCert();
- mode = Active;
- }
- else if(ret == Bad)
- {
- reset();
- return Error;
- }
- }
-
- // process outgoing
- *to_net = readOutgoing();
-
- if(mode == Active)
- return Success;
- else
- return Continue;
- }
-
- Result priv_shutdown(const QByteArray &from_net, QByteArray *to_net)
- {
- if(!from_net.isEmpty())
- BIO_write(rbio, from_net.data(), from_net.size());
-
- int ret = doShutdown();
- if(ret == Bad)
- {
- reset();
- return Error;
- }
-
- *to_net = readOutgoing();
-
- if(ret == Good)
- {
- mode = Idle;
- return Success;
- }
- else
- {
- //mode = Closing;
- return Continue;
- }
- }
-
- bool priv_encode(const QByteArray &plain, QByteArray *to_net, int *enc)
- {
- if(mode != Active)
- return false;
- sendQueue.append(plain);
-
- int encoded = 0;
- if(sendQueue.size() > 0)
- {
- int ret = SSL_write(ssl, sendQueue.data(), sendQueue.size());
-
- enum { Good, Continue, Done, Error };
- int m;
- if(ret <= 0)
- {
- int x = SSL_get_error(ssl, ret);
- if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
- m = Continue;
- else if(x == SSL_ERROR_ZERO_RETURN)
- m = Done;
- else
- m = Error;
- }
- else
- {
- m = Good;
- encoded = ret;
- int newsize = sendQueue.size() - encoded;
- char *r = sendQueue.data();
- memmove(r, r + encoded, newsize);
- sendQueue.resize(newsize);
- }
-
- if(m == Done)
- {
- sendQueue.resize(0);
- v_eof = true;
- return false;
- }
- if(m == Error)
- {
- sendQueue.resize(0);
- return false;
- }
- }
-
- *to_net += readOutgoing();
- *enc = encoded;
- return true;
- }
-
- bool priv_decode(const QByteArray &from_net, QByteArray *plain, QByteArray *to_net)
- {
- if(mode != Active)
- return false;
- if(!from_net.isEmpty())
- BIO_write(rbio, from_net.data(), from_net.size());
-
- QByteArray a;
- while(!v_eof) {
- a.resize(8192);
- int ret = SSL_read(ssl, a.data(), a.size());
- //printf("SSL_read = %d\n", ret);
- if(ret > 0)
- {
- if(ret != (int)a.size())
- a.resize(ret);
- //printf("SSL_read chunk: [%s]\n", qPrintable(arrayToHex(a)));
- recvQueue.append(a);
- }
- else if(ret <= 0)
- {
- ERR_print_errors_fp(stdout);
- int x = SSL_get_error(ssl, ret);
- //printf("SSL_read error = %d\n", x);
- if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
- break;
- else if(x == SSL_ERROR_ZERO_RETURN)
- v_eof = true;
- else
- return false;
- }
- }
-
- *plain = recvQueue;
- recvQueue.resize(0);
-
- // could be outgoing data also
- *to_net += readOutgoing();
- return true;
- }
-
- virtual bool waitForResultsReady(int msecs)
- {
- // TODO: for now, all operations block anyway
- Q_UNUSED(msecs);
- return true;
- }
-
- virtual Result result() const
- {
- return result_result;
- }
-
- virtual QByteArray to_net()
- {
- QByteArray a = result_to_net;
- result_to_net.clear();
- return a;
- }
-
- virtual int encoded() const
- {
- return result_encoded;
- }
-
- virtual QByteArray to_app()
- {
- QByteArray a = result_plain;
- result_plain.clear();
- return a;
- }
-
- virtual bool eof() const
- {
- return v_eof;
- }
-
- virtual bool clientHelloReceived() const
- {
- // TODO
- return false;
- }
-
- virtual bool serverHelloReceived() const
- {
- // TODO
- return false;
- }
-
- virtual QString hostName() const
- {
- // TODO
- return QString();
- }
-
- virtual bool certificateRequested() const
- {
- // TODO
- return false;
- }
-
- virtual QList<CertificateInfoOrdered> issuerList() const
- {
- // TODO
- return QList<CertificateInfoOrdered>();
- }
-
- virtual SessionInfo sessionInfo() const
- {
- SessionInfo sessInfo;
-
- SSL_SESSION *session = SSL_get0_session(ssl);
- sessInfo.isCompressed = (0 != SSL_SESSION_get_compress_id(session));
- int ssl_version = SSL_version(ssl);
-
- if (ssl_version == TLS1_VERSION)
- sessInfo.version = TLS::TLS_v1;
- else if (ssl_version == SSL3_VERSION)
- sessInfo.version = TLS::SSL_v3;
- else if (ssl_version == SSL2_VERSION)
- sessInfo.version = TLS::SSL_v2;
- else {
- qDebug("unexpected version response");
- sessInfo.version = TLS::TLS_v1;
- }
-
- sessInfo.cipherSuite = cipherIDtoString( sessInfo.version,
- SSL_CIPHER_get_id(SSL_get_current_cipher(ssl)));
-
- sessInfo.cipherMaxBits = SSL_get_cipher_bits(ssl, &(sessInfo.cipherBits));
-
- sessInfo.id = 0; // TODO: session resuming
-
- return sessInfo;
- }
-
- virtual QByteArray unprocessed()
- {
- QByteArray a;
- int size = BIO_pending(rbio);
- if(size <= 0)
- return a;
- a.resize(size);
-
- int r = BIO_read(rbio, a.data(), size);
- if(r <= 0)
- {
- a.resize(0);
- return a;
- }
- if(r != size)
- a.resize(r);
- return a;
- }
-
- virtual Validity peerCertificateValidity() const
- {
- return vr;
- }
-
- virtual CertificateChain peerCertificateChain() const
- {
- // TODO: support whole chain
- CertificateChain chain;
- chain.append(peercert);
- return chain;
- }
-
- void doResultsReady()
- {
- QMetaObject::invokeMethod(this, "resultsReady", Qt::QueuedConnection);
- }
-
- bool init()
- {
- context = SSL_CTX_new(method);
- if(!context)
- return false;
-
- // setup the cert store
- {
- X509_STORE *store = SSL_CTX_get_cert_store(context);
- QList<Certificate> cert_list = trusted.certificates();
- QList<CRL> crl_list = trusted.crls();
- int n;
- for(n = 0; n < cert_list.count(); ++n)
- {
- const MyCertContext *cc = static_cast<const MyCertContext *>(cert_list[n].context());
- X509 *x = cc->item.cert;
- //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
- X509_STORE_add_cert(store, x);
- }
- for(n = 0; n < crl_list.count(); ++n)
- {
- const MyCRLContext *cc = static_cast<const MyCRLContext *>(crl_list[n].context());
- X509_CRL *x = cc->item.crl;
- //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL);
- X509_STORE_add_crl(store, x);
- }
- }
-
- ssl = SSL_new(context);
- if(!ssl)
- {
- SSL_CTX_free(context);
- context = 0;
- return false;
- }
- SSL_set_ssl_method(ssl, method); // can this return error?
+ virtual CertificateChain peerCertificateChain() const
+ {
+ // TODO: support whole chain
+ CertificateChain chain;
+ chain.append(peercert);
+ return chain;
+ }
+
+ void doResultsReady()
+ {
+ QMetaObject::invokeMethod(this, "resultsReady", Qt::QueuedConnection);
+ }
+
+ bool init()
+ {
+ context = SSL_CTX_new(method);
+ if (!context) {
+ return false;
+ }
+
+ // setup the cert store
+ {
+ X509_STORE *store = SSL_CTX_get_cert_store(context);
+ QList<Certificate> cert_list = trusted.certificates();
+ QList<CRL> crl_list = trusted.crls();
+ int n;
+ for (n = 0; n < cert_list.count(); ++n) {
+ const MyCertContext *cc = static_cast<const MyCertContext *>(cert_list[n].context());
+ X509 *x = cc->item.cert;
+ //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
+ X509_STORE_add_cert(store, x);
+ }
+ for (n = 0; n < crl_list.count(); ++n) {
+ const MyCRLContext *cc = static_cast<const MyCRLContext *>(crl_list[n].context());
+ X509_CRL *x = cc->item.crl;
+ //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL);
+ X509_STORE_add_crl(store, x);
+ }
+ }
+
+ ssl = SSL_new(context);
+ if (!ssl) {
+ SSL_CTX_free(context);
+ context = 0;
+ return false;
+ }
+ SSL_set_ssl_method(ssl, method); // can this return error?
#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
- if ( targetHostName.isEmpty() == false ) {
- // we have a target
- // this might fail, but we ignore that for now
- char *hostname = targetHostName.toLatin1().data();
- SSL_set_tlsext_host_name( ssl, hostname );
- }
+ if (targetHostName.isEmpty() == false) {
+ // we have a target
+ // this might fail, but we ignore that for now
+ char *hostname = targetHostName.toLatin1().data();
+ SSL_set_tlsext_host_name(ssl, hostname);
+ }
#endif
- // setup the memory bio
- rbio = BIO_new(BIO_s_mem());
- wbio = BIO_new(BIO_s_mem());
-
- // this passes control of the bios to ssl. we don't need to free them.
- SSL_set_bio(ssl, rbio, wbio);
-
- // FIXME: move this to after server hello
- // setup the cert to send
- if(!cert.isNull() && !key.isNull())
- {
- PrivateKey nkey = key;
-
- const PKeyContext *tmp_kc = static_cast<const PKeyContext *>(nkey.context());
-
- if(!tmp_kc->sameProvider(this))
- {
- //fprintf(stderr, "experimental: private key supplied by a different provider\n");
-
- // make a pkey pointing to the existing private key
- EVP_PKEY *pkey;
- pkey = EVP_PKEY_new();
- EVP_PKEY_assign_RSA(pkey, createFromExisting(nkey.toRSA()));
-
- // make a new private key object to hold it
- MyPKeyContext *pk = new MyPKeyContext(provider());
- PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free()
- pk->k = k;
- nkey.change(pk);
- }
-
- const MyCertContext *cc = static_cast<const MyCertContext *>(cert.context());
- const MyPKeyContext *kc = static_cast<const MyPKeyContext *>(nkey.context());
-
- if(SSL_use_certificate(ssl, cc->item.cert) != 1)
- {
- SSL_free(ssl);
- SSL_CTX_free(context);
- return false;
- }
- if(SSL_use_PrivateKey(ssl, kc->get_pkey()) != 1)
- {
- SSL_free(ssl);
- SSL_CTX_free(context);
- return false;
- }
- }
-
- // request a certificate from the client, if in server mode
- if(serv)
- {
- SSL_set_verify(ssl,
- SSL_VERIFY_PEER|SSL_VERIFY_CLIENT_ONCE,
- ssl_verify_callback);
- }
-
- return true;
- }
-
- void getCert()
- {
- // verify the certificate
- Validity code = ErrorValidityUnknown;
- STACK_OF(X509) *x_chain = SSL_get_peer_cert_chain(ssl);
- //X509 *x = SSL_get_peer_certificate(ssl);
- if(x_chain)
- {
- CertificateChain chain;
-
- if(serv)
- {
- X509 *x = SSL_get_peer_certificate(ssl);
- MyCertContext *cc = new MyCertContext(provider());
- cc->fromX509(x);
- Certificate cert;
- cert.change(cc);
- chain += cert;
- }
-
- for(int n = 0; n < sk_X509_num(x_chain); ++n)
- {
- X509 *x = sk_X509_value(x_chain, n);
- MyCertContext *cc = new MyCertContext(provider());
- cc->fromX509(x);
- Certificate cert;
- cert.change(cc);
- chain += cert;
- }
-
- peercert = chain.primary();
+ // setup the memory bio
+ rbio = BIO_new(BIO_s_mem());
+ wbio = BIO_new(BIO_s_mem());
+
+ // this passes control of the bios to ssl. we don't need to free them.
+ SSL_set_bio(ssl, rbio, wbio);
+
+ // FIXME: move this to after server hello
+ // setup the cert to send
+ if (!cert.isNull() && !key.isNull()) {
+ PrivateKey nkey = key;
+
+ const PKeyContext *tmp_kc = static_cast<const PKeyContext *>(nkey.context());
+
+ if (!tmp_kc->sameProvider(this)) {
+ //fprintf(stderr, "experimental: private key supplied by a different provider\n");
+
+ // make a pkey pointing to the existing private key
+ EVP_PKEY *pkey;
+ pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_RSA(pkey, createFromExisting(nkey.toRSA()));
+
+ // make a new private key object to hold it
+ MyPKeyContext *pk = new MyPKeyContext(provider());
+ PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free()
+ pk->k = k;
+ nkey.change(pk);
+ }
+
+ const MyCertContext *cc = static_cast<const MyCertContext *>(cert.context());
+ const MyPKeyContext *kc = static_cast<const MyPKeyContext *>(nkey.context());
+
+ if (SSL_use_certificate(ssl, cc->item.cert) != 1) {
+ SSL_free(ssl);
+ SSL_CTX_free(context);
+ return false;
+ }
+ if (SSL_use_PrivateKey(ssl, kc->get_pkey()) != 1) {
+ SSL_free(ssl);
+ SSL_CTX_free(context);
+ return false;
+ }
+ }
+
+ // request a certificate from the client, if in server mode
+ if (serv) {
+ SSL_set_verify(ssl,
+ SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE,
+ ssl_verify_callback);
+ }
+
+ return true;
+ }
+
+ void getCert()
+ {
+ // verify the certificate
+ Validity code = ErrorValidityUnknown;
+ STACK_OF(X509) *x_chain = SSL_get_peer_cert_chain(ssl);
+ //X509 *x = SSL_get_peer_certificate(ssl);
+ if (x_chain) {
+ CertificateChain chain;
+
+ if (serv) {
+ X509 *x = SSL_get_peer_certificate(ssl);
+ MyCertContext *cc = new MyCertContext(provider());
+ cc->fromX509(x);
+ Certificate cert;
+ cert.change(cc);
+ chain += cert;
+ }
+
+ for (int n = 0; n < sk_X509_num(x_chain); ++n) {
+ X509 *x = sk_X509_value(x_chain, n);
+ MyCertContext *cc = new MyCertContext(provider());
+ cc->fromX509(x);
+ Certificate cert;
+ cert.change(cc);
+ chain += cert;
+ }
+
+ peercert = chain.primary();
#ifdef Q_OS_MAC
- code = chain.validate(trusted);
+ code = chain.validate(trusted);
#else
- int ret = SSL_get_verify_result(ssl);
- if(ret == X509_V_OK)
- code = ValidityGood;
- else
- code = convert_verify_error(ret);
+ int ret = SSL_get_verify_result(ssl);
+ if (ret == X509_V_OK) {
+ code = ValidityGood;
+ } else {
+ code = convert_verify_error(ret);
+ }
#endif
- }
- else
- {
- peercert = Certificate();
- }
- vr = code;
- }
-
- int doConnect()
- {
- int ret = SSL_connect(ssl);
- if(ret < 0)
- {
- int x = SSL_get_error(ssl, ret);
- if(x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
- return TryAgain;
- else
- return Bad;
- }
- else if(ret == 0)
- return Bad;
- return Good;
- }
-
- int doAccept()
- {
- int ret = SSL_accept(ssl);
- if(ret < 0)
- {
- int x = SSL_get_error(ssl, ret);
- if(x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
- return TryAgain;
- else
- return Bad;
- }
- else if(ret == 0)
- return Bad;
- return Good;
- }
-
- int doHandshake()
- {
- int ret = SSL_do_handshake(ssl);
- if(ret < 0)
- {
- int x = SSL_get_error(ssl, ret);
- if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
- return TryAgain;
- else
- return Bad;
- }
- else if(ret == 0)
- return Bad;
- return Good;
- }
-
- int doShutdown()
- {
- int ret = SSL_shutdown(ssl);
- if(ret >= 1)
- return Good;
- else
- {
- if(ret == 0)
- return TryAgain;
- int x = SSL_get_error(ssl, ret);
- if(x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE)
- return TryAgain;
- return Bad;
- }
- }
-
- QByteArray readOutgoing()
- {
- QByteArray a;
- int size = BIO_pending(wbio);
- if(size <= 0)
- return a;
- a.resize(size);
-
- int r = BIO_read(wbio, a.data(), size);
- if(r <= 0)
- {
- a.resize(0);
- return a;
- }
- if(r != size)
- a.resize(r);
- return a;
- }
+ } else {
+ peercert = Certificate();
+ }
+ vr = code;
+ }
+
+ int doConnect()
+ {
+ int ret = SSL_connect(ssl);
+ if (ret < 0) {
+ int x = SSL_get_error(ssl, ret);
+ if (x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) {
+ return TryAgain;
+ } else {
+ return Bad;
+ }
+ } else if (ret == 0) {
+ return Bad;
+ }
+ return Good;
+ }
+
+ int doAccept()
+ {
+ int ret = SSL_accept(ssl);
+ if (ret < 0) {
+ int x = SSL_get_error(ssl, ret);
+ if (x == SSL_ERROR_WANT_CONNECT || x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) {
+ return TryAgain;
+ } else {
+ return Bad;
+ }
+ } else if (ret == 0) {
+ return Bad;
+ }
+ return Good;
+ }
+
+ int doHandshake()
+ {
+ int ret = SSL_do_handshake(ssl);
+ if (ret < 0) {
+ int x = SSL_get_error(ssl, ret);
+ if (x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) {
+ return TryAgain;
+ } else {
+ return Bad;
+ }
+ } else if (ret == 0) {
+ return Bad;
+ }
+ return Good;
+ }
+
+ int doShutdown()
+ {
+ int ret = SSL_shutdown(ssl);
+ if (ret >= 1) {
+ return Good;
+ } else {
+ if (ret == 0) {
+ return TryAgain;
+ }
+ int x = SSL_get_error(ssl, ret);
+ if (x == SSL_ERROR_WANT_READ || x == SSL_ERROR_WANT_WRITE) {
+ return TryAgain;
+ }
+ return Bad;
+ }
+ }
+
+ QByteArray readOutgoing()
+ {
+ QByteArray a;
+ int size = BIO_pending(wbio);
+ if (size <= 0) {
+ return a;
+ }
+ a.resize(size);
+
+ int r = BIO_read(wbio, a.data(), size);
+ if (r <= 0) {
+ a.resize(0);
+ return a;
+ }
+ if (r != size) {
+ a.resize(r);
+ }
+ return a;
+ }
};
class CMSContext : public SMSContext
{
public:
- CertificateCollection trustedCerts;
- CertificateCollection untrustedCerts;
- QList<SecureMessageKey> privateKeys;
-
- CMSContext(Provider *p) : SMSContext(p, "cms")
- {
- }
-
- ~CMSContext()
- {
- }
-
- virtual Provider::Context *clone() const
- {
- return 0;
- }
-
- virtual void setTrustedCertificates(const CertificateCollection &trusted)
- {
- trustedCerts = trusted;
- }
-
- virtual void setUntrustedCertificates(const CertificateCollection &untrusted)
- {
- untrustedCerts = untrusted;
- }
-
- virtual void setPrivateKeys(const QList<SecureMessageKey> &keys)
- {
- privateKeys = keys;
- }
-
- virtual MessageContext *createMessage();
+ CertificateCollection trustedCerts;
+ CertificateCollection untrustedCerts;
+ QList<SecureMessageKey> privateKeys;
+
+ CMSContext(Provider *p) : SMSContext(p, "cms")
+ {
+ }
+
+ ~CMSContext()
+ {
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual void setTrustedCertificates(const CertificateCollection &trusted)
+ {
+ trustedCerts = trusted;
+ }
+
+ virtual void setUntrustedCertificates(const CertificateCollection &untrusted)
+ {
+ untrustedCerts = untrusted;
+ }
+
+ virtual void setPrivateKeys(const QList<SecureMessageKey> &keys)
+ {
+ privateKeys = keys;
+ }
+
+ virtual MessageContext *createMessage();
};
STACK_OF(X509) *get_pk7_certs(PKCS7 *p7)
{
- int i = OBJ_obj2nid(p7->type);
- if(i == NID_pkcs7_signed)
- return p7->d.sign->cert;
- else if(i == NID_pkcs7_signedAndEnveloped)
- return p7->d.signed_and_enveloped->cert;
- else
- return 0;
+ int i = OBJ_obj2nid(p7->type);
+ if (i == NID_pkcs7_signed) {
+ return p7->d.sign->cert;
+ } else if (i == NID_pkcs7_signedAndEnveloped) {
+ return p7->d.signed_and_enveloped->cert;
+ } else {
+ return 0;
+ }
}
class MyMessageContextThread : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- SecureMessage::Format format;
- SecureMessage::SignMode signMode;
- Certificate cert;
- PrivateKey key;
- STACK_OF(X509) *other_certs;
- BIO *bi;
- int flags;
- PKCS7 *p7;
- bool ok;
- QByteArray out, sig;
-
- MyMessageContextThread(QObject *parent = 0) : QThread(parent), ok(false)
- {
- }
+ SecureMessage::Format format;
+ SecureMessage::SignMode signMode;
+ Certificate cert;
+ PrivateKey key;
+ STACK_OF(X509) *other_certs;
+ BIO *bi;
+ int flags;
+ PKCS7 *p7;
+ bool ok;
+ QByteArray out, sig;
+
+ MyMessageContextThread(QObject *parent = 0) : QThread(parent), ok(false)
+ {
+ }
protected:
- virtual void run()
- {
- MyCertContext *cc = static_cast<MyCertContext *>(cert.context());
- MyPKeyContext *kc = static_cast<MyPKeyContext *>(key.context());
- X509 *cx = cc->item.cert;
- EVP_PKEY *kx = kc->get_pkey();
-
- p7 = PKCS7_sign(cx, kx, other_certs, bi, flags);
-
- BIO_free(bi);
- sk_X509_pop_free(other_certs, X509_free);
-
- if(p7)
- {
- //printf("good\n");
- BIO *bo;
-
- //BIO *bo = BIO_new(BIO_s_mem());
- //i2d_PKCS7_bio(bo, p7);
- //PEM_write_bio_PKCS7(bo, p7);
- //SecureArray buf = bio2buf(bo);
- //printf("[%s]\n", buf.data());
-
- bo = BIO_new(BIO_s_mem());
- if(format == SecureMessage::Binary)
- i2d_PKCS7_bio(bo, p7);
- else // Ascii
- PEM_write_bio_PKCS7(bo, p7);
-
- if (SecureMessage::Detached == signMode)
- sig = bio2ba(bo);
- else
- out = bio2ba(bo);
-
- ok = true;
- }
- else
- {
- printf("bad here\n");
- ERR_print_errors_fp(stdout);
- }
- }
+ virtual void run()
+ {
+ MyCertContext *cc = static_cast<MyCertContext *>(cert.context());
+ MyPKeyContext *kc = static_cast<MyPKeyContext *>(key.context());
+ X509 *cx = cc->item.cert;
+ EVP_PKEY *kx = kc->get_pkey();
+
+ p7 = PKCS7_sign(cx, kx, other_certs, bi, flags);
+
+ BIO_free(bi);
+ sk_X509_pop_free(other_certs, X509_free);
+
+ if (p7) {
+ //printf("good\n");
+ BIO *bo;
+
+ //BIO *bo = BIO_new(BIO_s_mem());
+ //i2d_PKCS7_bio(bo, p7);
+ //PEM_write_bio_PKCS7(bo, p7);
+ //SecureArray buf = bio2buf(bo);
+ //printf("[%s]\n", buf.data());
+
+ bo = BIO_new(BIO_s_mem());
+ if (format == SecureMessage::Binary) {
+ i2d_PKCS7_bio(bo, p7);
+ } else { // Ascii
+ PEM_write_bio_PKCS7(bo, p7);
+ }
+
+ if (SecureMessage::Detached == signMode) {
+ sig = bio2ba(bo);
+ } else {
+ out = bio2ba(bo);
+ }
+
+ ok = true;
+ } else {
+ printf("bad here\n");
+ ERR_print_errors_fp(stdout);
+ }
+ }
};
class MyMessageContext : public MessageContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- CMSContext *cms;
- SecureMessageKey signer;
- SecureMessageKeyList to;
- SecureMessage::SignMode signMode;
- bool bundleSigner;
- bool smime;
- SecureMessage::Format format;
-
- Operation op;
- bool _finished;
-
- QByteArray in, out;
- QByteArray sig;
- int total;
-
- CertificateChain signerChain;
- int ver_ret;
-
- MyMessageContextThread *thread;
-
- MyMessageContext(CMSContext *_cms, Provider *p) : MessageContext(p, "cmsmsg")
- {
- cms = _cms;
-
- total = 0;
-
- ver_ret = 0;
-
- thread = 0;
- }
-
- ~MyMessageContext()
- {
- }
-
- virtual Provider::Context *clone() const
- {
- return 0;
- }
-
- virtual bool canSignMultiple() const
- {
- return false;
- }
-
- virtual SecureMessage::Type type() const
- {
- return SecureMessage::CMS;
- }
-
- virtual void reset()
- {
- }
-
- virtual void setupEncrypt(const SecureMessageKeyList &keys)
- {
- to = keys;
- }
-
- virtual void setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool bundleSigner, bool smime)
- {
- signer = keys.first();
- signMode = m;
- this->bundleSigner = bundleSigner;
- this->smime = smime;
- }
-
- virtual void setupVerify(const QByteArray &detachedSig)
- {
- // TODO
- sig = detachedSig;
- }
-
- virtual void start(SecureMessage::Format f, Operation op)
- {
- format = f;
- _finished = false;
-
- // TODO: other operations
- //if(op == Sign)
- //{
- this->op = op;
- //}
- //else if(op == Encrypt)
- //{
- // this->op = op;
- //}
- }
-
- virtual void update(const QByteArray &in)
- {
- this->in.append(in);
- total += in.size();
- QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
- }
-
- virtual QByteArray read()
- {
- return out;
- }
-
- virtual int written()
- {
- int x = total;
- total = 0;
- return x;
- }
-
- virtual void end()
- {
- _finished = true;
-
- // sign
- if(op == Sign)
- {
- CertificateChain chain = signer.x509CertificateChain();
- Certificate cert = chain.primary();
- QList<Certificate> nonroots;
- if(chain.count() > 1)
- {
- for(int n = 1; n < chain.count(); ++n)
- nonroots.append(chain[n]);
- }
- PrivateKey key = signer.x509PrivateKey();
-
- const PKeyContext *tmp_kc = static_cast<const PKeyContext *>(key.context());
-
- if(!tmp_kc->sameProvider(this))
- {
- //fprintf(stderr, "experimental: private key supplied by a different provider\n");
-
- // make a pkey pointing to the existing private key
- EVP_PKEY *pkey;
- pkey = EVP_PKEY_new();
- EVP_PKEY_assign_RSA(pkey, createFromExisting(key.toRSA()));
-
- // make a new private key object to hold it
- MyPKeyContext *pk = new MyPKeyContext(provider());
- PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free()
- pk->k = k;
- key.change(pk);
- }
-
- // allow different cert provider. this is just a
- // quick hack, enough to please qca-test
- if(!cert.context()->sameProvider(this))
- {
- //fprintf(stderr, "experimental: cert supplied by a different provider\n");
- cert = Certificate::fromDER(cert.toDER());
- if(cert.isNull() || !cert.context()->sameProvider(this))
- {
- //fprintf(stderr, "error converting cert\n");
- }
- }
-
- //MyCertContext *cc = static_cast<MyCertContext *>(cert.context());
- //MyPKeyContext *kc = static_cast<MyPKeyContext *>(key.context());
-
- //X509 *cx = cc->item.cert;
- //EVP_PKEY *kx = kc->get_pkey();
-
- STACK_OF(X509) *other_certs;
- BIO *bi;
- int flags;
- //PKCS7 *p7;
-
- // nonroots
- other_certs = sk_X509_new_null();
- for(int n = 0; n < nonroots.count(); ++n)
- {
- X509 *x = static_cast<MyCertContext *>(nonroots[n].context())->item.cert;
- X509_up_ref(x);
- sk_X509_push(other_certs, x);
- }
-
- //printf("bundling %d other_certs\n", sk_X509_num(other_certs));
-
- bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
-
- flags = 0;
- flags |= PKCS7_BINARY;
- if (SecureMessage::Detached == signMode) {
- flags |= PKCS7_DETACHED;
- }
- if (false == bundleSigner)
- flags |= PKCS7_NOCERTS;
-
- if(thread)
- delete thread;
- thread = new MyMessageContextThread(this);
- thread->format = format;
- thread->signMode = signMode;
- thread->cert = cert;
- thread->key = key;
- thread->other_certs = other_certs;
- thread->bi = bi;
- thread->flags = flags;
- connect(thread, SIGNAL(finished()), SLOT(thread_finished()));
- thread->start();
- }
- else if(op == Encrypt)
- {
- // TODO: support multiple recipients
- Certificate target = to.first().x509CertificateChain().primary();
-
- STACK_OF(X509) *other_certs;
- BIO *bi;
- int flags;
- PKCS7 *p7;
-
- other_certs = sk_X509_new_null();
- X509 *x = static_cast<MyCertContext *>(target.context())->item.cert;
- X509_up_ref(x);
- sk_X509_push(other_certs, x);
-
- bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
-
- flags = 0;
- flags |= PKCS7_BINARY;
- p7 = PKCS7_encrypt(other_certs, bi, EVP_des_ede3_cbc(), flags); // TODO: cipher?
-
- BIO_free(bi);
- sk_X509_pop_free(other_certs, X509_free);
-
- QString env;
- if(p7)
- {
- // FIXME: format
- BIO *bo = BIO_new(BIO_s_mem());
- i2d_PKCS7_bio(bo, p7);
- //PEM_write_bio_PKCS7(bo, p7);
- out = bio2ba(bo);
- PKCS7_free(p7);
- }
- else
- {
- printf("bad\n");
- return;
- }
- }
- else if(op == Verify)
- {
- // TODO: support non-detached sigs
-
- BIO *out = BIO_new(BIO_s_mem());
- BIO *bi = BIO_new(BIO_s_mem());
- if (false == sig.isEmpty()) {
- // We have detached signature
- BIO_write(bi, sig.data(), sig.size());
- } else {
- BIO_write(bi, in.data(), in.size());
- }
- PKCS7 *p7;
- if(format == SecureMessage::Binary)
- p7 = d2i_PKCS7_bio(bi, NULL);
- else // Ascii
- p7 = PEM_read_bio_PKCS7(bi, NULL, passphrase_cb, NULL);
- BIO_free(bi);
-
- if(!p7)
- {
- // TODO
- printf("bad1\n");
- QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
- return;
- }
-
- // intermediates/signers that may not be in the blob
- STACK_OF(X509) *other_certs = sk_X509_new_null();
- QList<Certificate> untrusted_list = cms->untrustedCerts.certificates();
- QList<CRL> untrusted_crls = cms->untrustedCerts.crls(); // we'll use the crls later
- for(int n = 0; n < untrusted_list.count(); ++n)
- {
- X509 *x = static_cast<MyCertContext *>(untrusted_list[n].context())->item.cert;
- X509_up_ref(x);
- sk_X509_push(other_certs, x);
- }
-
- // get the possible message signers
- QList<Certificate> signers;
- STACK_OF(X509) *xs = PKCS7_get0_signers(p7, other_certs, 0);
- if(xs)
- {
- for(int n = 0; n < sk_X509_num(xs); ++n)
- {
- MyCertContext *cc = new MyCertContext(provider());
- cc->fromX509(sk_X509_value(xs, n));
- Certificate cert;
- cert.change(cc);
- //printf("signer: [%s]\n", qPrintable(cert.commonName()));
- signers.append(cert);
- }
- sk_X509_free(xs);
- }
-
- // get the rest of the certificates lying around
- QList<Certificate> others;
- xs = get_pk7_certs(p7); // don't free
- if(xs)
- {
- for(int n = 0; n < sk_X509_num(xs); ++n)
- {
- MyCertContext *cc = new MyCertContext(provider());
- cc->fromX509(sk_X509_value(xs, n));
- Certificate cert;
- cert.change(cc);
- others.append(cert);
- //printf("other: [%s]\n", qPrintable(cert.commonName()));
- }
- }
-
- // signer needs to be supplied in the message itself
- // or via cms->untrustedCerts
- if(signers.isEmpty())
- {
- QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
- return;
- }
-
- // FIXME: handle more than one signer
- CertificateChain chain;
- chain += signers[0];
-
- // build chain
- chain = chain.complete(others);
-
- signerChain = chain;
-
- X509_STORE *store = X509_STORE_new();
- QList<Certificate> cert_list = cms->trustedCerts.certificates();
- QList<CRL> crl_list = cms->trustedCerts.crls();
- for(int n = 0; n < cert_list.count(); ++n)
- {
- //printf("trusted: [%s]\n", qPrintable(cert_list[n].commonName()));
- const MyCertContext *cc = static_cast<const MyCertContext *>(cert_list[n].context());
- X509 *x = cc->item.cert;
- //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
- X509_STORE_add_cert(store, x);
- }
- for(int n = 0; n < crl_list.count(); ++n)
- {
- const MyCRLContext *cc = static_cast<const MyCRLContext *>(crl_list[n].context());
- X509_CRL *x = cc->item.crl;
- //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL);
- X509_STORE_add_crl(store, x);
- }
- // add these crls also
- crl_list = untrusted_crls;
- for(int n = 0; n < crl_list.count(); ++n)
- {
- const MyCRLContext *cc = static_cast<const MyCRLContext *>(crl_list[n].context());
- X509_CRL *x = cc->item.crl;
- //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL);
- X509_STORE_add_crl(store, x);
- }
-
- int ret;
- if(!sig.isEmpty()) {
- // Detached signMode
- bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- ret = PKCS7_verify(p7, other_certs, store, bi, NULL, 0);
- BIO_free(bi);
- } else {
- ret = PKCS7_verify(p7, other_certs, store, NULL, out, 0);
- // qDebug() << "Verify: " << ret;
- }
- //if(!ret)
- // ERR_print_errors_fp(stdout);
- sk_X509_pop_free(other_certs, X509_free);
- X509_STORE_free(store);
- PKCS7_free(p7);
-
- ver_ret = ret;
- // TODO
-
- QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
- }
- else if(op == Decrypt)
- {
- bool ok = false;
- for(int n = 0; n < cms->privateKeys.count(); ++n)
- {
- CertificateChain chain = cms->privateKeys[n].x509CertificateChain();
- Certificate cert = chain.primary();
- PrivateKey key = cms->privateKeys[n].x509PrivateKey();
-
- MyCertContext *cc = static_cast<MyCertContext *>(cert.context());
- MyPKeyContext *kc = static_cast<MyPKeyContext *>(key.context());
-
- X509 *cx = cc->item.cert;
- EVP_PKEY *kx = kc->get_pkey();
-
- BIO *bi = BIO_new(BIO_s_mem());
- BIO_write(bi, in.data(), in.size());
- PKCS7 *p7 = d2i_PKCS7_bio(bi, NULL);
- BIO_free(bi);
-
- if(!p7)
- {
- // TODO
- printf("bad1\n");
- return;
- }
-
- BIO *bo = BIO_new(BIO_s_mem());
- int ret = PKCS7_decrypt(p7, kx, cx, bo, 0);
- PKCS7_free(p7);
- if(!ret)
- continue;
-
- ok = true;
- out = bio2ba(bo);
- break;
- }
-
- if(!ok)
- {
- // TODO
- printf("bad2\n");
- return;
- }
- }
- }
-
- virtual bool finished() const
- {
- return _finished;
- }
-
- virtual bool waitForFinished(int msecs)
- {
- // TODO
- Q_UNUSED(msecs);
-
- if(thread)
- {
- thread->wait();
- getresults();
- }
- return true;
- }
-
- virtual bool success() const
- {
- // TODO
- return true;
- }
-
- virtual SecureMessage::Error errorCode() const
- {
- // TODO
- return SecureMessage::ErrorUnknown;
- }
-
- virtual QByteArray signature() const
- {
- return sig;
- }
-
- virtual QString hashName() const
- {
- // TODO
- return "sha1";
- }
-
- virtual SecureMessageSignatureList signers() const
- {
- // only report signers for verify
- if(op != Verify)
- return SecureMessageSignatureList();
-
- SecureMessageKey key;
- if(!signerChain.isEmpty())
- key.setX509CertificateChain(signerChain);
-
- // TODO/FIXME !!! InvalidSignature might be used here even
- // if the signature is just fine, and the key is invalid
- // (we need to use InvalidKey instead).
-
- Validity vr = ErrorValidityUnknown;
- if(!signerChain.isEmpty())
- vr = signerChain.validate(cms->trustedCerts, cms->untrustedCerts.crls());
-
- SecureMessageSignature::IdentityResult ir;
- if(vr == ValidityGood)
- ir = SecureMessageSignature::Valid;
- else
- ir = SecureMessageSignature::InvalidKey;
-
- if(!ver_ret)
- ir = SecureMessageSignature::InvalidSignature;
-
- SecureMessageSignature s(ir, vr, key, QDateTime::currentDateTime());
-
- // TODO
- return SecureMessageSignatureList() << s;
- }
-
- void getresults()
- {
- sig = thread->sig;
- out = thread->out;
- }
+ CMSContext *cms;
+ SecureMessageKey signer;
+ SecureMessageKeyList to;
+ SecureMessage::SignMode signMode;
+ bool bundleSigner;
+ bool smime;
+ SecureMessage::Format format;
+
+ Operation op;
+ bool _finished;
+
+ QByteArray in, out;
+ QByteArray sig;
+ int total;
+
+ CertificateChain signerChain;
+ int ver_ret;
+
+ MyMessageContextThread *thread;
+
+ MyMessageContext(CMSContext *_cms, Provider *p) : MessageContext(p, "cmsmsg")
+ {
+ cms = _cms;
+
+ total = 0;
+
+ ver_ret = 0;
+
+ thread = 0;
+ }
+
+ ~MyMessageContext()
+ {
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual bool canSignMultiple() const
+ {
+ return false;
+ }
+
+ virtual SecureMessage::Type type() const
+ {
+ return SecureMessage::CMS;
+ }
+
+ virtual void reset()
+ {
+ }
+
+ virtual void setupEncrypt(const SecureMessageKeyList &keys)
+ {
+ to = keys;
+ }
+
+ virtual void setupSign(const SecureMessageKeyList &keys, SecureMessage::SignMode m, bool bundleSigner, bool smime)
+ {
+ signer = keys.first();
+ signMode = m;
+ this->bundleSigner = bundleSigner;
+ this->smime = smime;
+ }
+
+ virtual void setupVerify(const QByteArray &detachedSig)
+ {
+ // TODO
+ sig = detachedSig;
+ }
+
+ virtual void start(SecureMessage::Format f, Operation op)
+ {
+ format = f;
+ _finished = false;
+
+ // TODO: other operations
+ //if(op == Sign)
+ //{
+ this->op = op;
+ //}
+ //else if(op == Encrypt)
+ //{
+ // this->op = op;
+ //}
+ }
+
+ virtual void update(const QByteArray &in)
+ {
+ this->in.append(in);
+ total += in.size();
+ QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
+ }
+
+ virtual QByteArray read()
+ {
+ return out;
+ }
+
+ virtual int written()
+ {
+ int x = total;
+ total = 0;
+ return x;
+ }
+
+ virtual void end()
+ {
+ _finished = true;
+
+ // sign
+ if (op == Sign) {
+ CertificateChain chain = signer.x509CertificateChain();
+ Certificate cert = chain.primary();
+ QList<Certificate> nonroots;
+ if (chain.count() > 1) {
+ for (int n = 1; n < chain.count(); ++n) {
+ nonroots.append(chain[n]);
+ }
+ }
+ PrivateKey key = signer.x509PrivateKey();
+
+ const PKeyContext *tmp_kc = static_cast<const PKeyContext *>(key.context());
+
+ if (!tmp_kc->sameProvider(this)) {
+ //fprintf(stderr, "experimental: private key supplied by a different provider\n");
+
+ // make a pkey pointing to the existing private key
+ EVP_PKEY *pkey;
+ pkey = EVP_PKEY_new();
+ EVP_PKEY_assign_RSA(pkey, createFromExisting(key.toRSA()));
+
+ // make a new private key object to hold it
+ MyPKeyContext *pk = new MyPKeyContext(provider());
+ PKeyBase *k = pk->pkeyToBase(pkey, true); // does an EVP_PKEY_free()
+ pk->k = k;
+ key.change(pk);
+ }
+
+ // allow different cert provider. this is just a
+ // quick hack, enough to please qca-test
+ if (!cert.context()->sameProvider(this)) {
+ //fprintf(stderr, "experimental: cert supplied by a different provider\n");
+ cert = Certificate::fromDER(cert.toDER());
+ if (cert.isNull() || !cert.context()->sameProvider(this)) {
+ //fprintf(stderr, "error converting cert\n");
+ }
+ }
+
+ //MyCertContext *cc = static_cast<MyCertContext *>(cert.context());
+ //MyPKeyContext *kc = static_cast<MyPKeyContext *>(key.context());
+
+ //X509 *cx = cc->item.cert;
+ //EVP_PKEY *kx = kc->get_pkey();
+
+ STACK_OF(X509) *other_certs;
+ BIO *bi;
+ int flags;
+ //PKCS7 *p7;
+
+ // nonroots
+ other_certs = sk_X509_new_null();
+ for (int n = 0; n < nonroots.count(); ++n) {
+ X509 *x = static_cast<MyCertContext *>(nonroots[n].context())->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(other_certs, x);
+ }
+
+ //printf("bundling %d other_certs\n", sk_X509_num(other_certs));
+
+ bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+
+ flags = 0;
+ flags |= PKCS7_BINARY;
+ if (SecureMessage::Detached == signMode) {
+ flags |= PKCS7_DETACHED;
+ }
+ if (false == bundleSigner) {
+ flags |= PKCS7_NOCERTS;
+ }
+
+ if (thread) {
+ delete thread;
+ }
+ thread = new MyMessageContextThread(this);
+ thread->format = format;
+ thread->signMode = signMode;
+ thread->cert = cert;
+ thread->key = key;
+ thread->other_certs = other_certs;
+ thread->bi = bi;
+ thread->flags = flags;
+ connect(thread, SIGNAL(finished()), SLOT(thread_finished()));
+ thread->start();
+ } else if (op == Encrypt) {
+ // TODO: support multiple recipients
+ Certificate target = to.first().x509CertificateChain().primary();
+
+ STACK_OF(X509) *other_certs;
+ BIO *bi;
+ int flags;
+ PKCS7 *p7;
+
+ other_certs = sk_X509_new_null();
+ X509 *x = static_cast<MyCertContext *>(target.context())->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(other_certs, x);
+
+ bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+
+ flags = 0;
+ flags |= PKCS7_BINARY;
+ p7 = PKCS7_encrypt(other_certs, bi, EVP_des_ede3_cbc(), flags); // TODO: cipher?
+
+ BIO_free(bi);
+ sk_X509_pop_free(other_certs, X509_free);
+
+ QString env;
+ if (p7) {
+ // FIXME: format
+ BIO *bo = BIO_new(BIO_s_mem());
+ i2d_PKCS7_bio(bo, p7);
+ //PEM_write_bio_PKCS7(bo, p7);
+ out = bio2ba(bo);
+ PKCS7_free(p7);
+ } else {
+ printf("bad\n");
+ return;
+ }
+ } else if (op == Verify) {
+ // TODO: support non-detached sigs
+
+ BIO *out = BIO_new(BIO_s_mem());
+ BIO *bi = BIO_new(BIO_s_mem());
+ if (false == sig.isEmpty()) {
+ // We have detached signature
+ BIO_write(bi, sig.data(), sig.size());
+ } else {
+ BIO_write(bi, in.data(), in.size());
+ }
+ PKCS7 *p7;
+ if (format == SecureMessage::Binary) {
+ p7 = d2i_PKCS7_bio(bi, NULL);
+ } else { // Ascii
+ p7 = PEM_read_bio_PKCS7(bi, NULL, passphrase_cb, NULL);
+ }
+ BIO_free(bi);
+
+ if (!p7) {
+ // TODO
+ printf("bad1\n");
+ QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
+ return;
+ }
+
+ // intermediates/signers that may not be in the blob
+ STACK_OF(X509) *other_certs = sk_X509_new_null();
+ QList<Certificate> untrusted_list = cms->untrustedCerts.certificates();
+ QList<CRL> untrusted_crls = cms->untrustedCerts.crls(); // we'll use the crls later
+ for (int n = 0; n < untrusted_list.count(); ++n) {
+ X509 *x = static_cast<MyCertContext *>(untrusted_list[n].context())->item.cert;
+ X509_up_ref(x);
+ sk_X509_push(other_certs, x);
+ }
+
+ // get the possible message signers
+ QList<Certificate> signers;
+ STACK_OF(X509) *xs = PKCS7_get0_signers(p7, other_certs, 0);
+ if (xs) {
+ for (int n = 0; n < sk_X509_num(xs); ++n) {
+ MyCertContext *cc = new MyCertContext(provider());
+ cc->fromX509(sk_X509_value(xs, n));
+ Certificate cert;
+ cert.change(cc);
+ //printf("signer: [%s]\n", qPrintable(cert.commonName()));
+ signers.append(cert);
+ }
+ sk_X509_free(xs);
+ }
+
+ // get the rest of the certificates lying around
+ QList<Certificate> others;
+ xs = get_pk7_certs(p7); // don't free
+ if (xs) {
+ for (int n = 0; n < sk_X509_num(xs); ++n) {
+ MyCertContext *cc = new MyCertContext(provider());
+ cc->fromX509(sk_X509_value(xs, n));
+ Certificate cert;
+ cert.change(cc);
+ others.append(cert);
+ //printf("other: [%s]\n", qPrintable(cert.commonName()));
+ }
+ }
+
+ // signer needs to be supplied in the message itself
+ // or via cms->untrustedCerts
+ if (signers.isEmpty()) {
+ QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
+ return;
+ }
+
+ // FIXME: handle more than one signer
+ CertificateChain chain;
+ chain += signers[0];
+
+ // build chain
+ chain = chain.complete(others);
+
+ signerChain = chain;
+
+ X509_STORE *store = X509_STORE_new();
+ QList<Certificate> cert_list = cms->trustedCerts.certificates();
+ QList<CRL> crl_list = cms->trustedCerts.crls();
+ for (int n = 0; n < cert_list.count(); ++n) {
+ //printf("trusted: [%s]\n", qPrintable(cert_list[n].commonName()));
+ const MyCertContext *cc = static_cast<const MyCertContext *>(cert_list[n].context());
+ X509 *x = cc->item.cert;
+ //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509);
+ X509_STORE_add_cert(store, x);
+ }
+ for (int n = 0; n < crl_list.count(); ++n) {
+ const MyCRLContext *cc = static_cast<const MyCRLContext *>(crl_list[n].context());
+ X509_CRL *x = cc->item.crl;
+ //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL);
+ X509_STORE_add_crl(store, x);
+ }
+ // add these crls also
+ crl_list = untrusted_crls;
+ for (int n = 0; n < crl_list.count(); ++n) {
+ const MyCRLContext *cc = static_cast<const MyCRLContext *>(crl_list[n].context());
+ X509_CRL *x = cc->item.crl;
+ //CRYPTO_add(&x->references, 1, CRYPTO_LOCK_X509_CRL);
+ X509_STORE_add_crl(store, x);
+ }
+
+ int ret;
+ if (!sig.isEmpty()) {
+ // Detached signMode
+ bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ ret = PKCS7_verify(p7, other_certs, store, bi, NULL, 0);
+ BIO_free(bi);
+ } else {
+ ret = PKCS7_verify(p7, other_certs, store, NULL, out, 0);
+ // qDebug() << "Verify: " << ret;
+ }
+ //if(!ret)
+ // ERR_print_errors_fp(stdout);
+ sk_X509_pop_free(other_certs, X509_free);
+ X509_STORE_free(store);
+ PKCS7_free(p7);
+
+ ver_ret = ret;
+ // TODO
+
+ QMetaObject::invokeMethod(this, "updated", Qt::QueuedConnection);
+ } else if (op == Decrypt) {
+ bool ok = false;
+ for (int n = 0; n < cms->privateKeys.count(); ++n) {
+ CertificateChain chain = cms->privateKeys[n].x509CertificateChain();
+ Certificate cert = chain.primary();
+ PrivateKey key = cms->privateKeys[n].x509PrivateKey();
+
+ MyCertContext *cc = static_cast<MyCertContext *>(cert.context());
+ MyPKeyContext *kc = static_cast<MyPKeyContext *>(key.context());
+
+ X509 *cx = cc->item.cert;
+ EVP_PKEY *kx = kc->get_pkey();
+
+ BIO *bi = BIO_new(BIO_s_mem());
+ BIO_write(bi, in.data(), in.size());
+ PKCS7 *p7 = d2i_PKCS7_bio(bi, NULL);
+ BIO_free(bi);
+
+ if (!p7) {
+ // TODO
+ printf("bad1\n");
+ return;
+ }
+
+ BIO *bo = BIO_new(BIO_s_mem());
+ int ret = PKCS7_decrypt(p7, kx, cx, bo, 0);
+ PKCS7_free(p7);
+ if (!ret) {
+ continue;
+ }
+
+ ok = true;
+ out = bio2ba(bo);
+ break;
+ }
+
+ if (!ok) {
+ // TODO
+ printf("bad2\n");
+ return;
+ }
+ }
+ }
+
+ virtual bool finished() const
+ {
+ return _finished;
+ }
+
+ virtual bool waitForFinished(int msecs)
+ {
+ // TODO
+ Q_UNUSED(msecs);
+
+ if (thread) {
+ thread->wait();
+ getresults();
+ }
+ return true;
+ }
+
+ virtual bool success() const
+ {
+ // TODO
+ return true;
+ }
+
+ virtual SecureMessage::Error errorCode() const
+ {
+ // TODO
+ return SecureMessage::ErrorUnknown;
+ }
+
+ virtual QByteArray signature() const
+ {
+ return sig;
+ }
+
+ virtual QString hashName() const
+ {
+ // TODO
+ return "sha1";
+ }
+
+ virtual SecureMessageSignatureList signers() const
+ {
+ // only report signers for verify
+ if (op != Verify) {
+ return SecureMessageSignatureList();
+ }
+
+ SecureMessageKey key;
+ if (!signerChain.isEmpty()) {
+ key.setX509CertificateChain(signerChain);
+ }
+
+ // TODO/FIXME !!! InvalidSignature might be used here even
+ // if the signature is just fine, and the key is invalid
+ // (we need to use InvalidKey instead).
+
+ Validity vr = ErrorValidityUnknown;
+ if (!signerChain.isEmpty()) {
+ vr = signerChain.validate(cms->trustedCerts, cms->untrustedCerts.crls());
+ }
+
+ SecureMessageSignature::IdentityResult ir;
+ if (vr == ValidityGood) {
+ ir = SecureMessageSignature::Valid;
+ } else {
+ ir = SecureMessageSignature::InvalidKey;
+ }
+
+ if (!ver_ret) {
+ ir = SecureMessageSignature::InvalidSignature;
+ }
+
+ SecureMessageSignature s(ir, vr, key, QDateTime::currentDateTime());
+
+ // TODO
+ return SecureMessageSignatureList() << s;
+ }
+
+ void getresults()
+ {
+ sig = thread->sig;
+ out = thread->out;
+ }
private slots:
- void thread_finished()
- {
- getresults();
- emit updated();
- }
+ void thread_finished()
+ {
+ getresults();
+ emit updated();
+ }
};
MessageContext *CMSContext::createMessage()
{
- return new MyMessageContext(this, provider());
+ return new MyMessageContext(this, provider());
}
-
class opensslCipherContext : public CipherContext
{
public:
- opensslCipherContext(const EVP_CIPHER *algorithm, const int pad, Provider *p, const QString &type) : CipherContext(p, type)
- {
- m_cryptoAlgorithm = algorithm;
- m_context = EVP_CIPHER_CTX_new();
- EVP_CIPHER_CTX_init(m_context);
- m_pad = pad;
- m_type = type;
- }
-
- opensslCipherContext(const opensslCipherContext &other)
- : CipherContext(other)
- {
- m_cryptoAlgorithm = other.m_cryptoAlgorithm;
- m_context = EVP_CIPHER_CTX_new();
- EVP_CIPHER_CTX_copy(m_context, other.m_context);
- m_direction = other.m_direction;
- m_pad = other.m_pad;
- m_type = other.m_type;
- m_tag = other.m_tag;
- }
-
- ~opensslCipherContext()
- {
- EVP_CIPHER_CTX_cleanup(m_context);
- EVP_CIPHER_CTX_free(m_context);
- }
-
- void setup(Direction dir,
- const SymmetricKey &key,
- const InitializationVector &iv,
- const AuthTag &tag)
- {
- m_tag = tag;
- m_direction = dir;
- if ( ( m_cryptoAlgorithm == EVP_des_ede3() ) && (key.size() == 16) ) {
- // this is really a two key version of triple DES.
- m_cryptoAlgorithm = EVP_des_ede();
- }
- if (Encode == m_direction) {
- EVP_EncryptInit_ex(m_context, m_cryptoAlgorithm, 0, 0, 0);
- EVP_CIPHER_CTX_set_key_length(m_context, key.size());
- if (m_type.endsWith("gcm") || m_type.endsWith("ccm")) {
- int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_IVLEN : EVP_CTRL_CCM_SET_IVLEN;
- EVP_CIPHER_CTX_ctrl(m_context, parameter, iv.size(), NULL);
- }
- EVP_EncryptInit_ex(m_context, 0, 0,
- (const unsigned char*)(key.data()),
- (const unsigned char*)(iv.data()));
- } else {
- EVP_DecryptInit_ex(m_context, m_cryptoAlgorithm, 0, 0, 0);
- EVP_CIPHER_CTX_set_key_length(m_context, key.size());
- if (m_type.endsWith("gcm") || m_type.endsWith("ccm")) {
- int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_IVLEN : EVP_CTRL_CCM_SET_IVLEN;
- EVP_CIPHER_CTX_ctrl(m_context, parameter, iv.size(), NULL);
- }
- EVP_DecryptInit_ex(m_context, 0, 0,
- (const unsigned char*)(key.data()),
- (const unsigned char*)(iv.data()));
- }
-
- EVP_CIPHER_CTX_set_padding(m_context, m_pad);
- }
-
- Provider::Context *clone() const
- {
- return new opensslCipherContext( *this );
- }
-
- int blockSize() const
- {
- return EVP_CIPHER_CTX_block_size(m_context);
- }
+ opensslCipherContext(const EVP_CIPHER *algorithm, const int pad, Provider *p, const QString &type) : CipherContext(p, type)
+ {
+ m_cryptoAlgorithm = algorithm;
+ m_context = EVP_CIPHER_CTX_new();
+ EVP_CIPHER_CTX_init(m_context);
+ m_pad = pad;
+ m_type = type;
+ }
+
+ opensslCipherContext(const opensslCipherContext &other)
+ : CipherContext(other)
+ {
+ m_cryptoAlgorithm = other.m_cryptoAlgorithm;
+ m_context = EVP_CIPHER_CTX_new();
+ EVP_CIPHER_CTX_copy(m_context, other.m_context);
+ m_direction = other.m_direction;
+ m_pad = other.m_pad;
+ m_type = other.m_type;
+ m_tag = other.m_tag;
+ }
+
+ ~opensslCipherContext()
+ {
+ EVP_CIPHER_CTX_cleanup(m_context);
+ EVP_CIPHER_CTX_free(m_context);
+ }
+
+ void setup(Direction dir,
+ const SymmetricKey &key,
+ const InitializationVector &iv,
+ const AuthTag &tag)
+ {
+ m_tag = tag;
+ m_direction = dir;
+ if ((m_cryptoAlgorithm == EVP_des_ede3()) && (key.size() == 16)) {
+ // this is really a two key version of triple DES.
+ m_cryptoAlgorithm = EVP_des_ede();
+ }
+ if (Encode == m_direction) {
+ EVP_EncryptInit_ex(m_context, m_cryptoAlgorithm, 0, 0, 0);
+ EVP_CIPHER_CTX_set_key_length(m_context, key.size());
+ if (m_type.endsWith("gcm") || m_type.endsWith("ccm")) {
+ int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_IVLEN : EVP_CTRL_CCM_SET_IVLEN;
+ EVP_CIPHER_CTX_ctrl(m_context, parameter, iv.size(), NULL);
+ }
+ EVP_EncryptInit_ex(m_context, 0, 0,
+ (const unsigned char *)(key.data()),
+ (const unsigned char *)(iv.data()));
+ } else {
+ EVP_DecryptInit_ex(m_context, m_cryptoAlgorithm, 0, 0, 0);
+ EVP_CIPHER_CTX_set_key_length(m_context, key.size());
+ if (m_type.endsWith("gcm") || m_type.endsWith("ccm")) {
+ int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_IVLEN : EVP_CTRL_CCM_SET_IVLEN;
+ EVP_CIPHER_CTX_ctrl(m_context, parameter, iv.size(), NULL);
+ }
+ EVP_DecryptInit_ex(m_context, 0, 0,
+ (const unsigned char *)(key.data()),
+ (const unsigned char *)(iv.data()));
+ }
+
+ EVP_CIPHER_CTX_set_padding(m_context, m_pad);
+ }
+
+ Provider::Context *clone() const
+ {
+ return new opensslCipherContext(*this);
+ }
+
+ int blockSize() const
+ {
+ return EVP_CIPHER_CTX_block_size(m_context);
+ }
AuthTag tag() const
{
- return m_tag;
- }
-
- bool update(const SecureArray &in, SecureArray *out)
- {
- // This works around a problem in OpenSSL, where it asserts if
- // there is nothing to encrypt.
- if ( 0 == in.size() )
- return true;
-
- out->resize(in.size()+blockSize());
- int resultLength;
- if (Encode == m_direction) {
- if (0 == EVP_EncryptUpdate(m_context,
- (unsigned char*)out->data(),
- &resultLength,
- (unsigned char*)in.data(),
- in.size())) {
- return false;
- }
- } else {
- if (0 == EVP_DecryptUpdate(m_context,
- (unsigned char*)out->data(),
- &resultLength,
- (unsigned char*)in.data(),
- in.size())) {
- return false;
- }
- }
- out->resize(resultLength);
- return true;
- }
-
- bool final(SecureArray *out)
- {
- out->resize(blockSize());
- int resultLength;
- if (Encode == m_direction) {
- if (0 == EVP_EncryptFinal_ex(m_context,
- (unsigned char*)out->data(),
- &resultLength)) {
- return false;
- }
- if (m_tag.size() && (m_type.endsWith("gcm") || m_type.endsWith("ccm"))) {
- int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_GET_TAG : EVP_CTRL_CCM_GET_TAG;
- if (0 == EVP_CIPHER_CTX_ctrl(m_context, parameter, m_tag.size(), (unsigned char*)m_tag.data())) {
- return false;
- }
- }
- } else {
- if (m_tag.size() && (m_type.endsWith("gcm") || m_type.endsWith("ccm"))) {
- int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_TAG : EVP_CTRL_CCM_SET_TAG;
- if (0 == EVP_CIPHER_CTX_ctrl(m_context, parameter, m_tag.size(), m_tag.data())) {
- return false;
- }
- }
- if (0 == EVP_DecryptFinal_ex(m_context,
- (unsigned char*)out->data(),
- &resultLength)) {
- return false;
- }
- }
- out->resize(resultLength);
- return true;
- }
-
- // Change cipher names
- KeyLength keyLength() const
- {
- if (m_type.left(4) == "des-") {
- return KeyLength( 8, 8, 1);
- } else if (m_type.left(6) == "aes128") {
- return KeyLength( 16, 16, 1);
- } else if (m_type.left(6) == "aes192") {
- return KeyLength( 24, 24, 1);
- } else if (m_type.left(6) == "aes256") {
- return KeyLength( 32, 32, 1);
- } else if (m_type.left(5) == "cast5") {
- return KeyLength( 5, 16, 1);
- } else if (m_type.left(8) == "blowfish") {
- // Don't know - TODO
- return KeyLength( 1, 32, 1);
- } else if (m_type.left(9) == "tripledes") {
- return KeyLength( 16, 24, 1);
- } else {
- return KeyLength( 0, 1, 1);
- }
- }
+ return m_tag;
+ }
+
+ bool update(const SecureArray &in, SecureArray *out)
+ {
+ // This works around a problem in OpenSSL, where it asserts if
+ // there is nothing to encrypt.
+ if (0 == in.size()) {
+ return true;
+ }
+
+ out->resize(in.size() + blockSize());
+ int resultLength;
+ if (Encode == m_direction) {
+ if (0 == EVP_EncryptUpdate(m_context,
+ (unsigned char *)out->data(),
+ &resultLength,
+ (unsigned char *)in.data(),
+ in.size())) {
+ return false;
+ }
+ } else {
+ if (0 == EVP_DecryptUpdate(m_context,
+ (unsigned char *)out->data(),
+ &resultLength,
+ (unsigned char *)in.data(),
+ in.size())) {
+ return false;
+ }
+ }
+ out->resize(resultLength);
+ return true;
+ }
+
+ bool final(SecureArray *out)
+ {
+ out->resize(blockSize());
+ int resultLength;
+ if (Encode == m_direction) {
+ if (0 == EVP_EncryptFinal_ex(m_context,
+ (unsigned char *)out->data(),
+ &resultLength)) {
+ return false;
+ }
+ if (m_tag.size() && (m_type.endsWith("gcm") || m_type.endsWith("ccm"))) {
+ int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_GET_TAG : EVP_CTRL_CCM_GET_TAG;
+ if (0 == EVP_CIPHER_CTX_ctrl(m_context, parameter, m_tag.size(), (unsigned char *)m_tag.data())) {
+ return false;
+ }
+ }
+ } else {
+ if (m_tag.size() && (m_type.endsWith("gcm") || m_type.endsWith("ccm"))) {
+ int parameter = m_type.endsWith("gcm") ? EVP_CTRL_GCM_SET_TAG : EVP_CTRL_CCM_SET_TAG;
+ if (0 == EVP_CIPHER_CTX_ctrl(m_context, parameter, m_tag.size(), m_tag.data())) {
+ return false;
+ }
+ }
+ if (0 == EVP_DecryptFinal_ex(m_context,
+ (unsigned char *)out->data(),
+ &resultLength)) {
+ return false;
+ }
+ }
+ out->resize(resultLength);
+ return true;
+ }
+ // Change cipher names
+ KeyLength keyLength() const
+ {
+ if (m_type.left(4) == "des-") {
+ return KeyLength(8, 8, 1);
+ } else if (m_type.left(6) == "aes128") {
+ return KeyLength(16, 16, 1);
+ } else if (m_type.left(6) == "aes192") {
+ return KeyLength(24, 24, 1);
+ } else if (m_type.left(6) == "aes256") {
+ return KeyLength(32, 32, 1);
+ } else if (m_type.left(5) == "cast5") {
+ return KeyLength(5, 16, 1);
+ } else if (m_type.left(8) == "blowfish") {
+ // Don't know - TODO
+ return KeyLength(1, 32, 1);
+ } else if (m_type.left(9) == "tripledes") {
+ return KeyLength(16, 24, 1);
+ } else {
+ return KeyLength(0, 1, 1);
+ }
+ }
protected:
- EVP_CIPHER_CTX *m_context;
- const EVP_CIPHER *m_cryptoAlgorithm;
- Direction m_direction;
- int m_pad;
- QString m_type;
- AuthTag m_tag;
+ EVP_CIPHER_CTX *m_context;
+ const EVP_CIPHER *m_cryptoAlgorithm;
+ Direction m_direction;
+ int m_pad;
+ QString m_type;
+ AuthTag m_tag;
};
static QStringList all_hash_types()
{
- QStringList list;
- list += "sha1";
+ QStringList list;
+ list += "sha1";
#ifdef HAVE_OPENSSL_SHA0
- list += "sha0";
+ list += "sha0";
#endif
- list += "ripemd160";
+ list += "ripemd160";
#ifdef HAVE_OPENSSL_MD2
- list += "md2";
+ list += "md2";
#endif
- list += "md4";
- list += "md5";
+ list += "md4";
+ list += "md5";
#ifdef SHA224_DIGEST_LENGTH
- list += "sha224";
+ list += "sha224";
#endif
#ifdef SHA256_DIGEST_LENGTH
- list += "sha256";
+ list += "sha256";
#endif
#ifdef SHA384_DIGEST_LENGTH
- list += "sha384";
+ list += "sha384";
#endif
#ifdef SHA512_DIGEST_LENGTH
- list += "sha512";
+ list += "sha512";
#endif
-/*
-#ifdef OBJ_whirlpool
- list += "whirlpool";
-#endif
-*/
- return list;
+ /*
+ #ifdef OBJ_whirlpool
+ list += "whirlpool";
+ #endif
+ */
+ return list;
}
static QStringList all_cipher_types()
{
- QStringList list;
- list += "aes128-ecb";
- list += "aes128-cfb";
- list += "aes128-cbc";
- list += "aes128-cbc-pkcs7";
- list += "aes128-ofb";
+ QStringList list;
+ list += "aes128-ecb";
+ list += "aes128-cfb";
+ list += "aes128-cbc";
+ list += "aes128-cbc-pkcs7";
+ list += "aes128-ofb";
#ifdef HAVE_OPENSSL_AES_CTR
- list += "aes128-ctr";
+ list += "aes128-ctr";
#endif
#ifdef HAVE_OPENSSL_AES_GCM
- list += "aes128-gcm";
+ list += "aes128-gcm";
#endif
#ifdef HAVE_OPENSSL_AES_CCM
- list += "aes128-ccm";
+ list += "aes128-ccm";
#endif
- list += "aes192-ecb";
- list += "aes192-cfb";
- list += "aes192-cbc";
- list += "aes192-cbc-pkcs7";
- list += "aes192-ofb";
+ list += "aes192-ecb";
+ list += "aes192-cfb";
+ list += "aes192-cbc";
+ list += "aes192-cbc-pkcs7";
+ list += "aes192-ofb";
#ifdef HAVE_OPENSSL_AES_CTR
- list += "aes192-ctr";
+ list += "aes192-ctr";
#endif
#ifdef HAVE_OPENSSL_AES_GCM
- list += "aes192-gcm";
+ list += "aes192-gcm";
#endif
#ifdef HAVE_OPENSSL_AES_CCM
- list += "aes192-ccm";
+ list += "aes192-ccm";
#endif
- list += "aes256-ecb";
- list += "aes256-cbc";
- list += "aes256-cbc-pkcs7";
- list += "aes256-cfb";
- list += "aes256-ofb";
+ list += "aes256-ecb";
+ list += "aes256-cbc";
+ list += "aes256-cbc-pkcs7";
+ list += "aes256-cfb";
+ list += "aes256-ofb";
#ifdef HAVE_OPENSSL_AES_CTR
- list += "aes256-ctr";
+ list += "aes256-ctr";
#endif
#ifdef HAVE_OPENSSL_AES_GCM
- list += "aes256-gcm";
+ list += "aes256-gcm";
#endif
#ifdef HAVE_OPENSSL_AES_CCM
- list += "aes256-ccm";
+ list += "aes256-ccm";
#endif
- list += "blowfish-ecb";
- list += "blowfish-cbc-pkcs7";
- list += "blowfish-cbc";
- list += "blowfish-cfb";
- list += "blowfish-ofb";
- list += "tripledes-ecb";
- list += "tripledes-cbc";
- list += "des-ecb";
- list += "des-ecb-pkcs7";
- list += "des-cbc";
- list += "des-cbc-pkcs7";
- list += "des-cfb";
- list += "des-ofb";
- list += "cast5-ecb";
- list += "cast5-cbc";
- list += "cast5-cbc-pkcs7";
- list += "cast5-cfb";
- list += "cast5-ofb";
- return list;
+ list += "blowfish-ecb";
+ list += "blowfish-cbc-pkcs7";
+ list += "blowfish-cbc";
+ list += "blowfish-cfb";
+ list += "blowfish-ofb";
+ list += "tripledes-ecb";
+ list += "tripledes-cbc";
+ list += "des-ecb";
+ list += "des-ecb-pkcs7";
+ list += "des-cbc";
+ list += "des-cbc-pkcs7";
+ list += "des-cfb";
+ list += "des-ofb";
+ list += "cast5-ecb";
+ list += "cast5-cbc";
+ list += "cast5-cbc-pkcs7";
+ list += "cast5-cfb";
+ list += "cast5-ofb";
+ return list;
}
static QStringList all_mac_types()
{
- QStringList list;
- list += "hmac(md5)";
- list += "hmac(sha1)";
+ QStringList list;
+ list += "hmac(md5)";
+ list += "hmac(sha1)";
#ifdef SHA224_DIGEST_LENGTH
- list += "hmac(sha224)";
+ list += "hmac(sha224)";
#endif
#ifdef SHA256_DIGEST_LENGTH
- list += "hmac(sha256)";
+ list += "hmac(sha256)";
#endif
#ifdef SHA384_DIGEST_LENGTH
- list += "hmac(sha384)";
+ list += "hmac(sha384)";
#endif
#ifdef SHA512_DIGEST_LENGTH
- list += "hmac(sha512)";
+ list += "hmac(sha512)";
#endif
- list += "hmac(ripemd160)";
- return list;
+ list += "hmac(ripemd160)";
+ return list;
}
class opensslInfoContext : public InfoContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- opensslInfoContext(Provider *p) : InfoContext(p)
- {
- }
-
- Provider::Context *clone() const
- {
- return new opensslInfoContext(*this);
- }
-
- QStringList supportedHashTypes() const
- {
- return all_hash_types();
- }
-
- QStringList supportedCipherTypes() const
- {
- return all_cipher_types();
- }
-
- QStringList supportedMACTypes() const
- {
- return all_mac_types();
- }
+ opensslInfoContext(Provider *p) : InfoContext(p)
+ {
+ }
+
+ Provider::Context *clone() const
+ {
+ return new opensslInfoContext(*this);
+ }
+
+ QStringList supportedHashTypes() const
+ {
+ return all_hash_types();
+ }
+
+ QStringList supportedCipherTypes() const
+ {
+ return all_cipher_types();
+ }
+
+ QStringList supportedMACTypes() const
+ {
+ return all_mac_types();
+ }
};
class opensslRandomContext : public RandomContext
{
public:
- opensslRandomContext(QCA::Provider *p) : RandomContext(p)
- {
- }
-
- Context *clone() const
- {
- return new opensslRandomContext(*this);
- }
-
- QCA::SecureArray nextBytes(int size)
- {
- QCA::SecureArray buf(size);
- int r;
- // FIXME: loop while we don't have enough random bytes.
- while (true) {
- r = RAND_bytes((unsigned char*)(buf.data()), size);
- if (r == 1) break; // success
- }
- return buf;
- }
+ opensslRandomContext(QCA::Provider *p) : RandomContext(p)
+ {
+ }
+
+ Context *clone() const
+ {
+ return new opensslRandomContext(*this);
+ }
+
+ QCA::SecureArray nextBytes(int size)
+ {
+ QCA::SecureArray buf(size);
+ int r;
+ // FIXME: loop while we don't have enough random bytes.
+ while (true) {
+ r = RAND_bytes((unsigned char *)(buf.data()), size);
+ if (r == 1) {
+ break; // success
+ }
+ }
+ return buf;
+ }
};
}
using namespace opensslQCAPlugin;
class opensslProvider : public Provider
{
public:
- bool openssl_initted;
-
- opensslProvider()
- {
- openssl_initted = false;
- }
-
- void init()
- {
- OpenSSL_add_all_algorithms();
- ERR_load_crypto_strings();
-
- // seed the RNG if it's not seeded yet
- if (RAND_status() == 0) {
- qsrand(time(NULL));
- char buf[128];
- for(int n = 0; n < 128; ++n)
- buf[n] = qrand();
- RAND_seed(buf, 128);
- }
-
- openssl_initted = true;
- }
-
- ~opensslProvider()
- {
- // FIXME: ? for now we never deinit, in case other libs/code
- // are using openssl
- /*if(!openssl_initted)
- return;
- // todo: any other shutdown?
- EVP_cleanup();
- //ENGINE_cleanup();
- CRYPTO_cleanup_all_ex_data();
- ERR_remove_state(0);
- ERR_free_strings();*/
- }
-
- int qcaVersion() const
- {
- return QCA_VERSION;
- }
-
- QString name() const
- {
- return "qca-ossl";
- }
-
- QString credit() const
- {
- return QString(
- "This product includes cryptographic software "
- "written by Eric Young (eay@cryptsoft.com)");
- }
-
- QStringList features() const
- {
- QStringList list;
- list += "random";
- list += all_hash_types();
- list += all_mac_types();
- list += all_cipher_types();
+ bool openssl_initted;
+
+ opensslProvider()
+ {
+ openssl_initted = false;
+ }
+
+ void init()
+ {
+ OpenSSL_add_all_algorithms();
+ ERR_load_crypto_strings();
+
+ // seed the RNG if it's not seeded yet
+ if (RAND_status() == 0) {
+ qsrand(time(NULL));
+ char buf[128];
+ for (int n = 0; n < 128; ++n) {
+ buf[n] = qrand();
+ }
+ RAND_seed(buf, 128);
+ }
+
+ openssl_initted = true;
+ }
+
+ ~opensslProvider()
+ {
+ // FIXME: ? for now we never deinit, in case other libs/code
+ // are using openssl
+ /*if(!openssl_initted)
+ return;
+ // todo: any other shutdown?
+ EVP_cleanup();
+ //ENGINE_cleanup();
+ CRYPTO_cleanup_all_ex_data();
+ ERR_remove_state(0);
+ ERR_free_strings();*/
+ }
+
+ int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ QString name() const
+ {
+ return "qca-ossl";
+ }
+
+ QString credit() const
+ {
+ return QString(
+ "This product includes cryptographic software "
+ "written by Eric Young (eay@cryptsoft.com)");
+ }
+
+ QStringList features() const
+ {
+ QStringList list;
+ list += "random";
+ list += all_hash_types();
+ list += all_mac_types();
+ list += all_cipher_types();
#ifdef HAVE_OPENSSL_MD2
- list += "pbkdf1(md2)";
+ list += "pbkdf1(md2)";
#endif
- list += "pbkdf1(sha1)";
- list += "pbkdf2(sha1)";
- list += "hkdf(sha256)";
- list += "pkey";
- list += "dlgroup";
- list += "rsa";
- list += "dsa";
- list += "dh";
- list += "cert";
- list += "csr";
- list += "crl";
- list += "certcollection";
- list += "pkcs12";
- list += "tls";
- list += "cms";
- list += "ca";
-
- return list;
- }
-
- Context *createContext(const QString &type)
- {
- //OpenSSL_add_all_digests();
- if ( type == "random" )
- return new opensslRandomContext(this);
- else if ( type == "info" )
- return new opensslInfoContext(this);
- else if ( type == "sha1" )
- return new opensslHashContext( EVP_sha1(), this, type);
+ list += "pbkdf1(sha1)";
+ list += "pbkdf2(sha1)";
+ list += "hkdf(sha256)";
+ list += "pkey";
+ list += "dlgroup";
+ list += "rsa";
+ list += "dsa";
+ list += "dh";
+ list += "cert";
+ list += "csr";
+ list += "crl";
+ list += "certcollection";
+ list += "pkcs12";
+ list += "tls";
+ list += "cms";
+ list += "ca";
+
+ return list;
+ }
+
+ Context *createContext(const QString &type)
+ {
+ //OpenSSL_add_all_digests();
+ if (type == "random") {
+ return new opensslRandomContext(this);
+ } else if (type == "info") {
+ return new opensslInfoContext(this);
+ } else if (type == "sha1") {
+ return new opensslHashContext(EVP_sha1(), this, type);
+ }
#ifdef HAVE_OPENSSL_SHA0
- else if ( type == "sha0" )
- return new opensslHashContext( EVP_sha(), this, type);
+ else if (type == "sha0") {
+ return new opensslHashContext(EVP_sha(), this, type);
+ }
#endif
- else if ( type == "ripemd160" )
- return new opensslHashContext( EVP_ripemd160(), this, type);
+ else if (type == "ripemd160") {
+ return new opensslHashContext(EVP_ripemd160(), this, type);
+ }
#ifdef HAVE_OPENSSL_MD2
- else if ( type == "md2" )
- return new opensslHashContext( EVP_md2(), this, type);
+ else if (type == "md2") {
+ return new opensslHashContext(EVP_md2(), this, type);
+ }
#endif
- else if ( type == "md4" )
- return new opensslHashContext( EVP_md4(), this, type);
- else if ( type == "md5" )
- return new opensslHashContext( EVP_md5(), this, type);
+ else if (type == "md4") {
+ return new opensslHashContext(EVP_md4(), this, type);
+ } else if (type == "md5") {
+ return new opensslHashContext(EVP_md5(), this, type);
+ }
#ifdef SHA224_DIGEST_LENGTH
- else if ( type == "sha224" )
- return new opensslHashContext( EVP_sha224(), this, type);
+ else if (type == "sha224") {
+ return new opensslHashContext(EVP_sha224(), this, type);
+ }
#endif
#ifdef SHA256_DIGEST_LENGTH
- else if ( type == "sha256" )
- return new opensslHashContext( EVP_sha256(), this, type);
+ else if (type == "sha256") {
+ return new opensslHashContext(EVP_sha256(), this, type);
+ }
#endif
#ifdef SHA384_DIGEST_LENGTH
- else if ( type == "sha384" )
- return new opensslHashContext( EVP_sha384(), this, type);
+ else if (type == "sha384") {
+ return new opensslHashContext(EVP_sha384(), this, type);
+ }
#endif
#ifdef SHA512_DIGEST_LENGTH
- else if ( type == "sha512" )
- return new opensslHashContext( EVP_sha512(), this, type);
-#endif
-/*
-#ifdef OBJ_whirlpool
- else if ( type == "whirlpool" )
- return new opensslHashContext( EVP_whirlpool(), this, type);
+ else if (type == "sha512") {
+ return new opensslHashContext(EVP_sha512(), this, type);
+ }
#endif
-*/
- else if ( type == "pbkdf1(sha1)" )
- return new opensslPbkdf1Context( EVP_sha1(), this, type );
+ /*
+ #ifdef OBJ_whirlpool
+ else if ( type == "whirlpool" )
+ return new opensslHashContext( EVP_whirlpool(), this, type);
+ #endif
+ */
+ else if (type == "pbkdf1(sha1)") {
+ return new opensslPbkdf1Context(EVP_sha1(), this, type);
+ }
#ifdef HAVE_OPENSSL_MD2
- else if ( type == "pbkdf1(md2)" )
- return new opensslPbkdf1Context( EVP_md2(), this, type );
+ else if (type == "pbkdf1(md2)") {
+ return new opensslPbkdf1Context(EVP_md2(), this, type);
+ }
#endif
- else if ( type == "pbkdf2(sha1)" )
- return new opensslPbkdf2Context( this, type );
- else if ( type == "hkdf(sha256)" )
- return new opensslHkdfContext( this, type );
- else if ( type == "hmac(md5)" )
- return new opensslHMACContext( EVP_md5(), this, type );
- else if ( type == "hmac(sha1)" )
- return new opensslHMACContext( EVP_sha1(),this, type );
+ else if (type == "pbkdf2(sha1)") {
+ return new opensslPbkdf2Context(this, type);
+ } else if (type == "hkdf(sha256)") {
+ return new opensslHkdfContext(this, type);
+ } else if (type == "hmac(md5)") {
+ return new opensslHMACContext(EVP_md5(), this, type);
+ } else if (type == "hmac(sha1)") {
+ return new opensslHMACContext(EVP_sha1(), this, type);
+ }
#ifdef SHA224_DIGEST_LENGTH
- else if ( type == "hmac(sha224)" )
- return new opensslHMACContext( EVP_sha224(), this, type);
+ else if (type == "hmac(sha224)") {
+ return new opensslHMACContext(EVP_sha224(), this, type);
+ }
#endif
#ifdef SHA256_DIGEST_LENGTH
- else if ( type == "hmac(sha256)" )
- return new opensslHMACContext( EVP_sha256(), this, type);
+ else if (type == "hmac(sha256)") {
+ return new opensslHMACContext(EVP_sha256(), this, type);
+ }
#endif
#ifdef SHA384_DIGEST_LENGTH
- else if ( type == "hmac(sha384)" )
- return new opensslHMACContext( EVP_sha384(), this, type);
+ else if (type == "hmac(sha384)") {
+ return new opensslHMACContext(EVP_sha384(), this, type);
+ }
#endif
#ifdef SHA512_DIGEST_LENGTH
- else if ( type == "hmac(sha512)" )
- return new opensslHMACContext( EVP_sha512(), this, type);
+ else if (type == "hmac(sha512)") {
+ return new opensslHMACContext(EVP_sha512(), this, type);
+ }
#endif
- else if ( type == "hmac(ripemd160)" )
- return new opensslHMACContext( EVP_ripemd160(), this, type );
- else if ( type == "aes128-ecb" )
- return new opensslCipherContext( EVP_aes_128_ecb(), 0, this, type);
- else if ( type == "aes128-cfb" )
- return new opensslCipherContext( EVP_aes_128_cfb(), 0, this, type);
- else if ( type == "aes128-cbc" )
- return new opensslCipherContext( EVP_aes_128_cbc(), 0, this, type);
- else if ( type == "aes128-cbc-pkcs7" )
- return new opensslCipherContext( EVP_aes_128_cbc(), 1, this, type);
- else if ( type == "aes128-ofb" )
- return new opensslCipherContext( EVP_aes_128_ofb(), 0, this, type);
+ else if (type == "hmac(ripemd160)") {
+ return new opensslHMACContext(EVP_ripemd160(), this, type);
+ } else if (type == "aes128-ecb") {
+ return new opensslCipherContext(EVP_aes_128_ecb(), 0, this, type);
+ } else if (type == "aes128-cfb") {
+ return new opensslCipherContext(EVP_aes_128_cfb(), 0, this, type);
+ } else if (type == "aes128-cbc") {
+ return new opensslCipherContext(EVP_aes_128_cbc(), 0, this, type);
+ } else if (type == "aes128-cbc-pkcs7") {
+ return new opensslCipherContext(EVP_aes_128_cbc(), 1, this, type);
+ } else if (type == "aes128-ofb") {
+ return new opensslCipherContext(EVP_aes_128_ofb(), 0, this, type);
+ }
#ifdef HAVE_OPENSSL_AES_CTR
- else if ( type == "aes128-ctr" )
- return new opensslCipherContext( EVP_aes_128_ctr(), 0, this, type);
+ else if (type == "aes128-ctr") {
+ return new opensslCipherContext(EVP_aes_128_ctr(), 0, this, type);
+ }
#endif
#ifdef HAVE_OPENSSL_AES_GCM
- else if ( type == "aes128-gcm" )
- return new opensslCipherContext( EVP_aes_128_gcm(), 0, this, type);
+ else if (type == "aes128-gcm") {
+ return new opensslCipherContext(EVP_aes_128_gcm(), 0, this, type);
+ }
#endif
#ifdef HAVE_OPENSSL_AES_CCM
- else if ( type == "aes128-ccm" )
- return new opensslCipherContext( EVP_aes_128_ccm(), 0, this, type);
+ else if (type == "aes128-ccm") {
+ return new opensslCipherContext(EVP_aes_128_ccm(), 0, this, type);
+ }
#endif
- else if ( type == "aes192-ecb" )
- return new opensslCipherContext( EVP_aes_192_ecb(), 0, this, type);
- else if ( type == "aes192-cfb" )
- return new opensslCipherContext( EVP_aes_192_cfb(), 0, this, type);
- else if ( type == "aes192-cbc" )
- return new opensslCipherContext( EVP_aes_192_cbc(), 0, this, type);
- else if ( type == "aes192-cbc-pkcs7" )
- return new opensslCipherContext( EVP_aes_192_cbc(), 1, this, type);
- else if ( type == "aes192-ofb" )
- return new opensslCipherContext( EVP_aes_192_ofb(), 0, this, type);
+ else if (type == "aes192-ecb") {
+ return new opensslCipherContext(EVP_aes_192_ecb(), 0, this, type);
+ } else if (type == "aes192-cfb") {
+ return new opensslCipherContext(EVP_aes_192_cfb(), 0, this, type);
+ } else if (type == "aes192-cbc") {
+ return new opensslCipherContext(EVP_aes_192_cbc(), 0, this, type);
+ } else if (type == "aes192-cbc-pkcs7") {
+ return new opensslCipherContext(EVP_aes_192_cbc(), 1, this, type);
+ } else if (type == "aes192-ofb") {
+ return new opensslCipherContext(EVP_aes_192_ofb(), 0, this, type);
+ }
#ifdef HAVE_OPENSSL_AES_CTR
- else if ( type == "aes192-ctr" )
- return new opensslCipherContext( EVP_aes_192_ctr(), 0, this, type);
+ else if (type == "aes192-ctr") {
+ return new opensslCipherContext(EVP_aes_192_ctr(), 0, this, type);
+ }
#endif
#ifdef HAVE_OPENSSL_AES_GCM
- else if ( type == "aes192-gcm" )
- return new opensslCipherContext( EVP_aes_192_gcm(), 0, this, type);
+ else if (type == "aes192-gcm") {
+ return new opensslCipherContext(EVP_aes_192_gcm(), 0, this, type);
+ }
#endif
#ifdef HAVE_OPENSSL_AES_CCM
- else if ( type == "aes192-ccm" )
- return new opensslCipherContext( EVP_aes_192_ccm(), 0, this, type);
+ else if (type == "aes192-ccm") {
+ return new opensslCipherContext(EVP_aes_192_ccm(), 0, this, type);
+ }
#endif
- else if ( type == "aes256-ecb" )
- return new opensslCipherContext( EVP_aes_256_ecb(), 0, this, type);
- else if ( type == "aes256-cfb" )
- return new opensslCipherContext( EVP_aes_256_cfb(), 0, this, type);
- else if ( type == "aes256-cbc" )
- return new opensslCipherContext( EVP_aes_256_cbc(), 0, this, type);
- else if ( type == "aes256-cbc-pkcs7" )
- return new opensslCipherContext( EVP_aes_256_cbc(), 1, this, type);
- else if ( type == "aes256-ofb" )
- return new opensslCipherContext( EVP_aes_256_ofb(), 0, this, type);
+ else if (type == "aes256-ecb") {
+ return new opensslCipherContext(EVP_aes_256_ecb(), 0, this, type);
+ } else if (type == "aes256-cfb") {
+ return new opensslCipherContext(EVP_aes_256_cfb(), 0, this, type);
+ } else if (type == "aes256-cbc") {
+ return new opensslCipherContext(EVP_aes_256_cbc(), 0, this, type);
+ } else if (type == "aes256-cbc-pkcs7") {
+ return new opensslCipherContext(EVP_aes_256_cbc(), 1, this, type);
+ } else if (type == "aes256-ofb") {
+ return new opensslCipherContext(EVP_aes_256_ofb(), 0, this, type);
+ }
#ifdef HAVE_OPENSSL_AES_CTR
- else if ( type == "aes256-ctr" )
- return new opensslCipherContext( EVP_aes_256_ctr(), 0, this, type);
+ else if (type == "aes256-ctr") {
+ return new opensslCipherContext(EVP_aes_256_ctr(), 0, this, type);
+ }
#endif
#ifdef HAVE_OPENSSL_AES_GCM
- else if ( type == "aes256-gcm" )
- return new opensslCipherContext( EVP_aes_256_gcm(), 0, this, type);
+ else if (type == "aes256-gcm") {
+ return new opensslCipherContext(EVP_aes_256_gcm(), 0, this, type);
+ }
#endif
#ifdef HAVE_OPENSSL_AES_CCM
- else if ( type == "aes256-ccm" )
- return new opensslCipherContext( EVP_aes_256_ccm(), 0, this, type);
+ else if (type == "aes256-ccm") {
+ return new opensslCipherContext(EVP_aes_256_ccm(), 0, this, type);
+ }
#endif
- else if ( type == "blowfish-ecb" )
- return new opensslCipherContext( EVP_bf_ecb(), 0, this, type);
- else if ( type == "blowfish-cfb" )
- return new opensslCipherContext( EVP_bf_cfb(), 0, this, type);
- else if ( type == "blowfish-ofb" )
- return new opensslCipherContext( EVP_bf_ofb(), 0, this, type);
- else if ( type == "blowfish-cbc" )
- return new opensslCipherContext( EVP_bf_cbc(), 0, this, type);
- else if ( type == "blowfish-cbc-pkcs7" )
- return new opensslCipherContext( EVP_bf_cbc(), 1, this, type);
- else if ( type == "tripledes-ecb" )
- return new opensslCipherContext( EVP_des_ede3(), 0, this, type);
- else if ( type == "tripledes-cbc" )
- return new opensslCipherContext( EVP_des_ede3_cbc(), 0, this, type);
- else if ( type == "des-ecb" )
- return new opensslCipherContext( EVP_des_ecb(), 0, this, type);
- else if ( type == "des-ecb-pkcs7" )
- return new opensslCipherContext( EVP_des_ecb(), 1, this, type);
- else if ( type == "des-cbc" )
- return new opensslCipherContext( EVP_des_cbc(), 0, this, type);
- else if ( type == "des-cbc-pkcs7" )
- return new opensslCipherContext( EVP_des_cbc(), 1, this, type);
- else if ( type == "des-cfb" )
- return new opensslCipherContext( EVP_des_cfb(), 0, this, type);
- else if ( type == "des-ofb" )
- return new opensslCipherContext( EVP_des_ofb(), 0, this, type);
- else if ( type == "cast5-ecb" )
- return new opensslCipherContext( EVP_cast5_ecb(), 0, this, type);
- else if ( type == "cast5-cbc" )
- return new opensslCipherContext( EVP_cast5_cbc(), 0, this, type);
- else if ( type == "cast5-cbc-pkcs7" )
- return new opensslCipherContext( EVP_cast5_cbc(), 1, this, type);
- else if ( type == "cast5-cfb" )
- return new opensslCipherContext( EVP_cast5_cfb(), 0, this, type);
- else if ( type == "cast5-ofb" )
- return new opensslCipherContext( EVP_cast5_ofb(), 0, this, type);
- else if ( type == "pkey" )
- return new MyPKeyContext( this );
- else if ( type == "dlgroup" )
- return new MyDLGroup( this );
- else if ( type == "rsa" )
- return new RSAKey( this );
- else if ( type == "dsa" )
- return new DSAKey( this );
- else if ( type == "dh" )
- return new DHKey( this );
- else if ( type == "cert" )
- return new MyCertContext( this );
- else if ( type == "csr" )
- return new MyCSRContext( this );
- else if ( type == "crl" )
- return new MyCRLContext( this );
- else if ( type == "certcollection" )
- return new MyCertCollectionContext( this );
- else if ( type == "pkcs12" )
- return new MyPKCS12Context( this );
- else if ( type == "tls" )
- return new MyTLSContext( this );
- else if ( type == "cms" )
- return new CMSContext( this );
- else if ( type == "ca" )
- return new MyCAContext( this );
- return 0;
- }
+ else if (type == "blowfish-ecb") {
+ return new opensslCipherContext(EVP_bf_ecb(), 0, this, type);
+ } else if (type == "blowfish-cfb") {
+ return new opensslCipherContext(EVP_bf_cfb(), 0, this, type);
+ } else if (type == "blowfish-ofb") {
+ return new opensslCipherContext(EVP_bf_ofb(), 0, this, type);
+ } else if (type == "blowfish-cbc") {
+ return new opensslCipherContext(EVP_bf_cbc(), 0, this, type);
+ } else if (type == "blowfish-cbc-pkcs7") {
+ return new opensslCipherContext(EVP_bf_cbc(), 1, this, type);
+ } else if (type == "tripledes-ecb") {
+ return new opensslCipherContext(EVP_des_ede3(), 0, this, type);
+ } else if (type == "tripledes-cbc") {
+ return new opensslCipherContext(EVP_des_ede3_cbc(), 0, this, type);
+ } else if (type == "des-ecb") {
+ return new opensslCipherContext(EVP_des_ecb(), 0, this, type);
+ } else if (type == "des-ecb-pkcs7") {
+ return new opensslCipherContext(EVP_des_ecb(), 1, this, type);
+ } else if (type == "des-cbc") {
+ return new opensslCipherContext(EVP_des_cbc(), 0, this, type);
+ } else if (type == "des-cbc-pkcs7") {
+ return new opensslCipherContext(EVP_des_cbc(), 1, this, type);
+ } else if (type == "des-cfb") {
+ return new opensslCipherContext(EVP_des_cfb(), 0, this, type);
+ } else if (type == "des-ofb") {
+ return new opensslCipherContext(EVP_des_ofb(), 0, this, type);
+ } else if (type == "cast5-ecb") {
+ return new opensslCipherContext(EVP_cast5_ecb(), 0, this, type);
+ } else if (type == "cast5-cbc") {
+ return new opensslCipherContext(EVP_cast5_cbc(), 0, this, type);
+ } else if (type == "cast5-cbc-pkcs7") {
+ return new opensslCipherContext(EVP_cast5_cbc(), 1, this, type);
+ } else if (type == "cast5-cfb") {
+ return new opensslCipherContext(EVP_cast5_cfb(), 0, this, type);
+ } else if (type == "cast5-ofb") {
+ return new opensslCipherContext(EVP_cast5_ofb(), 0, this, type);
+ } else if (type == "pkey") {
+ return new MyPKeyContext(this);
+ } else if (type == "dlgroup") {
+ return new MyDLGroup(this);
+ } else if (type == "rsa") {
+ return new RSAKey(this);
+ } else if (type == "dsa") {
+ return new DSAKey(this);
+ } else if (type == "dh") {
+ return new DHKey(this);
+ } else if (type == "cert") {
+ return new MyCertContext(this);
+ } else if (type == "csr") {
+ return new MyCSRContext(this);
+ } else if (type == "crl") {
+ return new MyCRLContext(this);
+ } else if (type == "certcollection") {
+ return new MyCertCollectionContext(this);
+ } else if (type == "pkcs12") {
+ return new MyPKCS12Context(this);
+ } else if (type == "tls") {
+ return new MyTLSContext(this);
+ } else if (type == "cms") {
+ return new CMSContext(this);
+ } else if (type == "ca") {
+ return new MyCAContext(this);
+ }
+ return 0;
+ }
};
class opensslPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { return new opensslProvider; }
+ virtual Provider *createProvider()
+ {
+ return new opensslProvider;
+ }
};
#include "qca-ossl.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_ossl, opensslPlugin)
#endif
diff --git a/plugins/qca-pkcs11/qca-pkcs11.cpp b/plugins/qca-pkcs11/qca-pkcs11.cpp
index d22cde2f..16532554 100644
--- a/plugins/qca-pkcs11/qca-pkcs11.cpp
+++ b/plugins/qca-pkcs11/qca-pkcs11.cpp
@@ -1,3113 +1,3219 @@
/*
* Copyright (C) 2004 Justin Karneges <justin@affinix.com>
* Copyright (C) 2006-2007 Alon Bar-Lev <alon.barlev@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <qcaprovider.h>
#include <qplatformdefs.h>
#include <QHash>
#include <QMutexLocker>
#include <QtPlugin>
#include <pkcs11-helper-1.0/pkcs11h-token.h>
#include <pkcs11-helper-1.0/pkcs11h-certificate.h>
using namespace QCA;
// qPrintable is ASCII only!!!
#define myPrintable(s) (s).toUtf8 ().constData ()
static
inline
QString
-certificateHash (
- const Certificate &cert
-) {
- if (cert.isNull ()) {
- return QString();
- }
- else {
- return Hash ("sha1").hashToString (cert.toDER ());
- }
+certificateHash(
+ const Certificate &cert
+)
+{
+ if (cert.isNull()) {
+ return QString();
+ } else {
+ return Hash("sha1").hashToString(cert.toDER());
+ }
}
//----------------------------------------------------------------------------
// pkcs11Provider
//----------------------------------------------------------------------------
class pkcs11Provider : public Provider
{
private:
- static const int _CONFIG_MAX_PROVIDERS;
+ static const int _CONFIG_MAX_PROVIDERS;
- bool _lowLevelInitialized;
- bool _slotEventsActive;
- bool _slotEventsLowLevelActive;
- QStringList _providers;
+ bool _lowLevelInitialized;
+ bool _slotEventsActive;
+ bool _slotEventsLowLevelActive;
+ QStringList _providers;
public:
- bool _allowLoadRootCA;
+ bool _allowLoadRootCA;
public:
- pkcs11Provider ();
- ~pkcs11Provider ();
+ pkcs11Provider();
+ ~pkcs11Provider();
public:
- virtual
- int
- qcaVersion() const;
+ virtual
+ int
+ qcaVersion() const;
- virtual
- void
- init ();
+ virtual
+ void
+ init();
- virtual
- void
- deinit ();
+ virtual
+ void
+ deinit();
- virtual
- QString
- name () const;
+ virtual
+ QString
+ name() const;
- virtual
- QStringList
- features () const;
+ virtual
+ QStringList
+ features() const;
- virtual
- Context *
- createContext (
- const QString &type
- );
+ virtual
+ Context *
+ createContext(
+ const QString &type
+ );
- void
- startSlotEvents ();
+ void
+ startSlotEvents();
- void
- stopSlotEvents ();
+ void
+ stopSlotEvents();
- virtual
- QVariantMap
- defaultConfig () const;
+ virtual
+ QVariantMap
+ defaultConfig() const;
- virtual
- void
- configChanged (const QVariantMap &config);
+ virtual
+ void
+ configChanged(const QVariantMap &config);
protected:
- static
- void
- __logHook (
- void * const global_data,
- const unsigned flags,
- const char * const format,
- va_list args
- );
-
- static
- void
- __slotEventHook (
- void * const global_data
- );
-
- static
- PKCS11H_BOOL
- __tokenPromptHook (
- void * const global_data,
- void * const user_data,
- const pkcs11h_token_id_t token,
- const unsigned retry
- );
-
- static
- PKCS11H_BOOL
- __pinPromptHook (
- void * const global_data,
- void * const user_data,
- const pkcs11h_token_id_t token,
- const unsigned retry,
- char * const pin,
- const size_t pin_max
- );
-
- void
- _logHook (
- const unsigned flags,
- const char * const format,
- va_list args
- );
-
- void
- _slotEventHook ();
-
- PKCS11H_BOOL
- _tokenPromptHook (
- void * const user_data,
- const pkcs11h_token_id_t token
- );
-
- PKCS11H_BOOL
- _pinPromptHook (
- void * const user_data,
- const pkcs11h_token_id_t token,
- char * const pin,
- const size_t pin_max
- );
+ static
+ void
+ __logHook(
+ void *const global_data,
+ const unsigned flags,
+ const char *const format,
+ va_list args
+ );
+
+ static
+ void
+ __slotEventHook(
+ void *const global_data
+ );
+
+ static
+ PKCS11H_BOOL
+ __tokenPromptHook(
+ void *const global_data,
+ void *const user_data,
+ const pkcs11h_token_id_t token,
+ const unsigned retry
+ );
+
+ static
+ PKCS11H_BOOL
+ __pinPromptHook(
+ void *const global_data,
+ void *const user_data,
+ const pkcs11h_token_id_t token,
+ const unsigned retry,
+ char *const pin,
+ const size_t pin_max
+ );
+
+ void
+ _logHook(
+ const unsigned flags,
+ const char *const format,
+ va_list args
+ );
+
+ void
+ _slotEventHook();
+
+ PKCS11H_BOOL
+ _tokenPromptHook(
+ void *const user_data,
+ const pkcs11h_token_id_t token
+ );
+
+ PKCS11H_BOOL
+ _pinPromptHook(
+ void *const user_data,
+ const pkcs11h_token_id_t token,
+ char *const pin,
+ const size_t pin_max
+ );
};
-namespace pkcs11QCAPlugin {
+namespace pkcs11QCAPlugin
+{
class pkcs11KeyStoreEntryContext;
//----------------------------------------------------------------------------
// pkcs11KeyStoreListContext
//----------------------------------------------------------------------------
class pkcs11KeyStoreListContext : public KeyStoreListContext
{
- Q_OBJECT
+ Q_OBJECT
private:
- struct pkcs11KeyStoreItem {
-
- protected:
- int _id;
- pkcs11h_token_id_t _token_id;
- QList<Certificate> _certs;
-
- public:
- pkcs11KeyStoreItem (
- const int id,
- const pkcs11h_token_id_t token_id
- ) {
- _id = id;;
- pkcs11h_token_duplicateTokenId (&_token_id, token_id);
- }
-
- ~pkcs11KeyStoreItem () {
- if (_token_id != NULL) {
- pkcs11h_token_freeTokenId (_token_id);
- }
- }
-
- inline int id () const {
- return _id;
- }
-
- inline pkcs11h_token_id_t tokenId () const {
- return _token_id;
- }
-
- void
- registerCertificates (
- const QList<Certificate> &certs
- ) {
- foreach (Certificate i, certs) {
- if (qFind (_certs.begin (), _certs.end (), i) == _certs.end ()) {
- _certs += i;
- }
- }
- }
-
- QMap<QString, QString>
- friendlyNames () {
- QStringList names = makeFriendlyNames (_certs);
- QMap<QString, QString> friendlyNames;
-
- for (int i=0;i<names.size ();i++) {
- friendlyNames.insert (certificateHash (_certs[i]), names[i]);
- }
-
- return friendlyNames;
- }
- };
- int _last_id;
- typedef QList<pkcs11KeyStoreItem *> _stores_t;
- _stores_t _stores;
- QHash<int, pkcs11KeyStoreItem *> _storesById;
- QMutex _mutexStores;
- bool _initialized;
+ struct pkcs11KeyStoreItem {
+
+ protected:
+ int _id;
+ pkcs11h_token_id_t _token_id;
+ QList<Certificate> _certs;
+
+ public:
+ pkcs11KeyStoreItem(
+ const int id,
+ const pkcs11h_token_id_t token_id
+ )
+ {
+ _id = id;;
+ pkcs11h_token_duplicateTokenId(&_token_id, token_id);
+ }
+
+ ~pkcs11KeyStoreItem()
+ {
+ if (_token_id != NULL) {
+ pkcs11h_token_freeTokenId(_token_id);
+ }
+ }
+
+ inline int id() const
+ {
+ return _id;
+ }
+
+ inline pkcs11h_token_id_t tokenId() const
+ {
+ return _token_id;
+ }
+
+ void
+ registerCertificates(
+ const QList<Certificate> &certs
+ )
+ {
+ foreach (Certificate i, certs) {
+ if (qFind(_certs.begin(), _certs.end(), i) == _certs.end()) {
+ _certs += i;
+ }
+ }
+ }
+
+ QMap<QString, QString>
+ friendlyNames()
+ {
+ QStringList names = makeFriendlyNames(_certs);
+ QMap<QString, QString> friendlyNames;
+
+ for (int i = 0; i < names.size(); i++) {
+ friendlyNames.insert(certificateHash(_certs[i]), names[i]);
+ }
+
+ return friendlyNames;
+ }
+ };
+ int _last_id;
+ typedef QList<pkcs11KeyStoreItem *> _stores_t;
+ _stores_t _stores;
+ QHash<int, pkcs11KeyStoreItem *> _storesById;
+ QMutex _mutexStores;
+ bool _initialized;
public:
- pkcs11KeyStoreListContext (Provider *p);
+ pkcs11KeyStoreListContext(Provider *p);
- ~pkcs11KeyStoreListContext ();
+ ~pkcs11KeyStoreListContext();
- virtual
- Provider::Context *
- clone () const;
+ virtual
+ Provider::Context *
+ clone() const;
public:
- virtual
- void
- start ();
-
- virtual
- void
- setUpdatesEnabled (bool enabled);
-
- virtual
- KeyStoreEntryContext *
- entry (
- int id,
- const QString &entryId
- );
-
- virtual
- KeyStoreEntryContext *
- entryPassive (
- const QString &serialized
- );
-
- virtual
- KeyStore::Type
- type (int id) const;
-
- virtual
- QString
- storeId (int id) const;
-
- virtual
- QString
- name (int id) const;
-
- virtual
- QList<KeyStoreEntry::Type>
- entryTypes (int id) const;
-
- virtual
- QList<int>
- keyStores ();
-
- virtual
- QList<KeyStoreEntryContext *>
- entryList (int id);
-
- bool
- _tokenPrompt (
- void * const user_data,
- const pkcs11h_token_id_t token_id
- );
-
- bool
- _pinPrompt (
- void * const user_data,
- const pkcs11h_token_id_t token_id,
- SecureArray &pin
- );
-
- void
- _emit_diagnosticText (
- const QString &t
- );
+ virtual
+ void
+ start();
+
+ virtual
+ void
+ setUpdatesEnabled(bool enabled);
+
+ virtual
+ KeyStoreEntryContext *
+ entry(
+ int id,
+ const QString &entryId
+ );
+
+ virtual
+ KeyStoreEntryContext *
+ entryPassive(
+ const QString &serialized
+ );
+
+ virtual
+ KeyStore::Type
+ type(int id) const;
+
+ virtual
+ QString
+ storeId(int id) const;
+
+ virtual
+ QString
+ name(int id) const;
+
+ virtual
+ QList<KeyStoreEntry::Type>
+ entryTypes(int id) const;
+
+ virtual
+ QList<int>
+ keyStores();
+
+ virtual
+ QList<KeyStoreEntryContext *>
+ entryList(int id);
+
+ bool
+ _tokenPrompt(
+ void *const user_data,
+ const pkcs11h_token_id_t token_id
+ );
+
+ bool
+ _pinPrompt(
+ void *const user_data,
+ const pkcs11h_token_id_t token_id,
+ SecureArray &pin
+ );
+
+ void
+ _emit_diagnosticText(
+ const QString &t
+ );
private slots:
- void
- doReady ();
+ void
+ doReady();
- void
- doUpdated ();
+ void
+ doUpdated();
private:
- pkcs11KeyStoreItem *
- _registerTokenId (
- const pkcs11h_token_id_t token_id
- );
-
- void
- _clearStores ();
-
- pkcs11KeyStoreEntryContext *
- _keyStoreEntryByCertificateId (
- const pkcs11h_certificate_id_t certificate_id,
- const bool has_private,
- const CertificateChain &chain,
- const QString &description
- ) const;
-
- QString
- _tokenId2storeId (
- const pkcs11h_token_id_t token_id
- ) const;
-
- QString
- _serializeCertificate (
- const pkcs11h_certificate_id_t certificate_id,
- const CertificateChain &chain,
- const bool has_private
- ) const;
-
- void
- _deserializeCertificate (
- const QString &from,
- pkcs11h_certificate_id_t * const p_certificate_id,
- bool * const p_has_private,
- CertificateChain &chain
- ) const;
-
- QString
- _escapeString (
- const QString &from
- ) const;
-
- QString
- _unescapeString (
- const QString &from
- ) const;
+ pkcs11KeyStoreItem *
+ _registerTokenId(
+ const pkcs11h_token_id_t token_id
+ );
+
+ void
+ _clearStores();
+
+ pkcs11KeyStoreEntryContext *
+ _keyStoreEntryByCertificateId(
+ const pkcs11h_certificate_id_t certificate_id,
+ const bool has_private,
+ const CertificateChain &chain,
+ const QString &description
+ ) const;
+
+ QString
+ _tokenId2storeId(
+ const pkcs11h_token_id_t token_id
+ ) const;
+
+ QString
+ _serializeCertificate(
+ const pkcs11h_certificate_id_t certificate_id,
+ const CertificateChain &chain,
+ const bool has_private
+ ) const;
+
+ void
+ _deserializeCertificate(
+ const QString &from,
+ pkcs11h_certificate_id_t *const p_certificate_id,
+ bool *const p_has_private,
+ CertificateChain &chain
+ ) const;
+
+ QString
+ _escapeString(
+ const QString &from
+ ) const;
+
+ QString
+ _unescapeString(
+ const QString &from
+ ) const;
};
static pkcs11KeyStoreListContext *s_keyStoreList = NULL;
//----------------------------------------------------------------------------
// pkcs11Exception
//----------------------------------------------------------------------------
-class pkcs11Exception {
+class pkcs11Exception
+{
private:
- CK_RV _rv;
- QString _msg;
+ CK_RV _rv;
+ QString _msg;
private:
- pkcs11Exception () {}
+ pkcs11Exception() {}
public:
- pkcs11Exception (const CK_RV rv, const QString &msg) {
- _rv = rv;
- _msg = msg;
- }
-
- pkcs11Exception (const pkcs11Exception &other) {
- *this = other;
- }
-
- pkcs11Exception &
- operator = (const pkcs11Exception &other) {
- _rv = other._rv;
- _msg = other._msg;
- return *this;
- }
-
- CK_RV
- rv () const {
- return _rv;
- }
-
- QString
- message () const {
- return _msg + QString (" ") + pkcs11h_getMessage (_rv);
- }
+ pkcs11Exception(const CK_RV rv, const QString &msg)
+ {
+ _rv = rv;
+ _msg = msg;
+ }
+
+ pkcs11Exception(const pkcs11Exception &other)
+ {
+ *this = other;
+ }
+
+ pkcs11Exception &
+ operator = (const pkcs11Exception &other)
+ {
+ _rv = other._rv;
+ _msg = other._msg;
+ return *this;
+ }
+
+ CK_RV
+ rv() const
+ {
+ return _rv;
+ }
+
+ QString
+ message() const
+ {
+ return _msg + QString(" ") + pkcs11h_getMessage(_rv);
+ }
};
//----------------------------------------------------------------------------
// pkcs11RSAContext
//----------------------------------------------------------------------------
class pkcs11RSAContext : public RSAContext
{
- Q_OBJECT
+ Q_OBJECT
private:
- bool _has_privateKeyRole;
- pkcs11h_certificate_id_t _pkcs11h_certificate_id;
- pkcs11h_certificate_t _pkcs11h_certificate;
- RSAPublicKey _pubkey;
- QString _serialized;
-
- struct _sign_data_s {
- SignatureAlgorithm alg;
- Hash *hash;
- QByteArray raw;
-
- _sign_data_s() {
- hash = NULL;
- }
- } _sign_data;
+ bool _has_privateKeyRole;
+ pkcs11h_certificate_id_t _pkcs11h_certificate_id;
+ pkcs11h_certificate_t _pkcs11h_certificate;
+ RSAPublicKey _pubkey;
+ QString _serialized;
+
+ struct _sign_data_s {
+ SignatureAlgorithm alg;
+ Hash *hash;
+ QByteArray raw;
+
+ _sign_data_s()
+ {
+ hash = NULL;
+ }
+ } _sign_data;
public:
- pkcs11RSAContext (
- Provider *p,
- const pkcs11h_certificate_id_t pkcs11h_certificate_id,
- const QString &serialized,
- const RSAPublicKey &pubkey
- ) : RSAContext (p) {
- CK_RV rv;
-
- QCA_logTextMessage (
- "pkcs11RSAContext::pkcs11RSAContext1 - entry",
- Logger::Debug
- );
-
- _has_privateKeyRole = true;
- _pkcs11h_certificate_id = NULL;
- _pkcs11h_certificate = NULL;
- _pubkey = pubkey;
- _serialized = serialized;
- _clearSign ();
-
- if (
- (rv = pkcs11h_certificate_duplicateCertificateId (
- &_pkcs11h_certificate_id,
- pkcs11h_certificate_id
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Memory error");
- }
-
- QCA_logTextMessage (
- "pkcs11RSAContext::pkcs11RSAContext1 - return",
- Logger::Debug
- );
- }
-
- pkcs11RSAContext (const pkcs11RSAContext &from) : RSAContext (from.provider ()) {
- CK_RV rv;
-
- QCA_logTextMessage (
- "pkcs11RSAContext::pkcs11RSAContextC - entry",
- Logger::Debug
- );
-
- _has_privateKeyRole = from._has_privateKeyRole;
- _pkcs11h_certificate_id = NULL;
- _pkcs11h_certificate = NULL;
- _pubkey = from._pubkey;
- _serialized = from._serialized;
- _sign_data.hash = NULL;
- _clearSign ();
-
- if (
- (rv = pkcs11h_certificate_duplicateCertificateId (
- &_pkcs11h_certificate_id,
- from._pkcs11h_certificate_id
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Memory error");
- }
-
- QCA_logTextMessage (
- "pkcs11RSAContext::pkcs11RSAContextC - return",
- Logger::Debug
- );
- }
-
- ~pkcs11RSAContext () {
- QCA_logTextMessage (
- "pkcs11RSAContext::~pkcs11RSAContext - entry",
- Logger::Debug
- );
-
- _clearSign ();
-
- if (_pkcs11h_certificate != NULL) {
- pkcs11h_certificate_freeCertificate (_pkcs11h_certificate);
- _pkcs11h_certificate = NULL;
- }
-
- if (_pkcs11h_certificate_id != NULL) {
- pkcs11h_certificate_freeCertificateId (_pkcs11h_certificate_id);
- _pkcs11h_certificate_id = NULL;
- }
-
- QCA_logTextMessage (
- "pkcs11RSAContext::~pkcs11RSAContext - return",
- Logger::Debug
- );
- }
-
- virtual
- Provider::Context *
- clone () const {
- return new pkcs11RSAContext (*this);
- }
+ pkcs11RSAContext(
+ Provider *p,
+ const pkcs11h_certificate_id_t pkcs11h_certificate_id,
+ const QString &serialized,
+ const RSAPublicKey &pubkey
+ ) : RSAContext(p)
+ {
+ CK_RV rv;
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::pkcs11RSAContext1 - entry",
+ Logger::Debug
+ );
+
+ _has_privateKeyRole = true;
+ _pkcs11h_certificate_id = NULL;
+ _pkcs11h_certificate = NULL;
+ _pubkey = pubkey;
+ _serialized = serialized;
+ _clearSign();
+
+ if (
+ (rv = pkcs11h_certificate_duplicateCertificateId(
+ &_pkcs11h_certificate_id,
+ pkcs11h_certificate_id
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Memory error");
+ }
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::pkcs11RSAContext1 - return",
+ Logger::Debug
+ );
+ }
+
+ pkcs11RSAContext(const pkcs11RSAContext &from) : RSAContext(from.provider())
+ {
+ CK_RV rv;
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::pkcs11RSAContextC - entry",
+ Logger::Debug
+ );
+
+ _has_privateKeyRole = from._has_privateKeyRole;
+ _pkcs11h_certificate_id = NULL;
+ _pkcs11h_certificate = NULL;
+ _pubkey = from._pubkey;
+ _serialized = from._serialized;
+ _sign_data.hash = NULL;
+ _clearSign();
+
+ if (
+ (rv = pkcs11h_certificate_duplicateCertificateId(
+ &_pkcs11h_certificate_id,
+ from._pkcs11h_certificate_id
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Memory error");
+ }
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::pkcs11RSAContextC - return",
+ Logger::Debug
+ );
+ }
+
+ ~pkcs11RSAContext()
+ {
+ QCA_logTextMessage(
+ "pkcs11RSAContext::~pkcs11RSAContext - entry",
+ Logger::Debug
+ );
+
+ _clearSign();
+
+ if (_pkcs11h_certificate != NULL) {
+ pkcs11h_certificate_freeCertificate(_pkcs11h_certificate);
+ _pkcs11h_certificate = NULL;
+ }
+
+ if (_pkcs11h_certificate_id != NULL) {
+ pkcs11h_certificate_freeCertificateId(_pkcs11h_certificate_id);
+ _pkcs11h_certificate_id = NULL;
+ }
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::~pkcs11RSAContext - return",
+ Logger::Debug
+ );
+ }
+
+ virtual
+ Provider::Context *
+ clone() const
+ {
+ return new pkcs11RSAContext(*this);
+ }
public:
- virtual
- bool
- isNull () const {
- return _pubkey.isNull ();
- }
-
- virtual
- PKey::Type
- type () const {
- return _pubkey.type ();
- }
-
- virtual
- bool
- isPrivate () const {
- return _has_privateKeyRole;
- }
-
- virtual
- bool
- canExport () const {
- return !_has_privateKeyRole;
- }
-
- virtual
- void
- convertToPublic () {
- QCA_logTextMessage (
- "pkcs11RSAContext::convertToPublic - entry",
- Logger::Debug
- );
-
- if (_has_privateKeyRole) {
- if (_pkcs11h_certificate != NULL) {
- pkcs11h_certificate_freeCertificate (_pkcs11h_certificate);
- _pkcs11h_certificate = NULL;
- }
- _has_privateKeyRole = false;
- }
-
- QCA_logTextMessage (
- "pkcs11RSAContext::convertToPublic - return",
- Logger::Debug
- );
- }
-
- virtual
- int
- bits () const {
- return _pubkey.bitSize ();
- }
-
- virtual
- int
- maximumEncryptSize (
- EncryptionAlgorithm alg
- ) const {
- return _pubkey.maximumEncryptSize (alg);
- }
-
- virtual
- SecureArray
- encrypt (
- const SecureArray &in,
- EncryptionAlgorithm alg
- ) {
- return _pubkey.encrypt (in, alg);
- }
-
- virtual
- bool
- decrypt (
- const SecureArray &in,
- SecureArray *out,
- EncryptionAlgorithm alg
- ) {
- bool session_locked = false;
- bool ret = false;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11RSAContext::decrypt - decrypt in.size()=%d, alg=%d",
- in.size (),
- (int)alg
- ),
- Logger::Debug
- );
-
- try {
- CK_MECHANISM_TYPE mech;
- CK_RV rv;
- size_t my_size;
-
- switch (alg) {
- case EME_PKCS1v15:
- mech = CKM_RSA_PKCS;
- break;
- case EME_PKCS1_OAEP:
- mech = CKM_RSA_PKCS_OAEP;
- break;
- default:
- throw pkcs11Exception (CKR_FUNCTION_NOT_SUPPORTED, "Invalid algorithm");
- break;
- }
-
- _ensureCertificate ();
-
- if (
- (rv = pkcs11h_certificate_lockSession (
- _pkcs11h_certificate
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot lock session");
- }
- session_locked = true;
-
- if (
- (rv = pkcs11h_certificate_decryptAny (
- _pkcs11h_certificate,
- mech,
- (const unsigned char *)in.constData (),
- in.size (),
- NULL,
- &my_size
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Decryption error");
- }
-
- out->resize (my_size);
-
- if (
- (rv = pkcs11h_certificate_decryptAny (
- _pkcs11h_certificate,
- mech,
- (const unsigned char *)in.constData (),
- in.size (),
- (unsigned char *)out->data (),
- &my_size
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Decryption error");
- }
-
- rv = out->resize (my_size);
-
- if (
- (rv = pkcs11h_certificate_releaseSession (
- _pkcs11h_certificate
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot release session");
- }
- session_locked = false;
-
- ret = true;
- }
- catch (const pkcs11Exception &e) {
- if (session_locked) {
- pkcs11h_certificate_releaseSession (
- _pkcs11h_certificate
- );
- session_locked = false;
- }
-
- if (s_keyStoreList != NULL) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Cannot decrypt: %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11RSAContext::decrypt - decrypt out->size()=%d",
- out->size ()
- ),
- Logger::Debug
- );
-
- return ret;
- }
-
- virtual
- void
- startSign (
- SignatureAlgorithm alg,
- SignatureFormat
- ) {
- _clearSign ();
-
- _sign_data.alg = alg;
-
- switch (_sign_data.alg) {
- case EMSA3_SHA1:
- _sign_data.hash = new Hash ("sha1");
- break;
- case EMSA3_MD5:
- _sign_data.hash = new Hash ("md5");
- break;
- case EMSA3_MD2:
- _sign_data.hash = new Hash ("md2");
- break;
- case EMSA3_Raw:
- break;
- case SignatureUnknown:
- case EMSA1_SHA1:
- case EMSA3_RIPEMD160:
- default:
- QCA_logTextMessage (
- QString().sprintf (
- "PKCS#11: Invalid hash algorithm %d",
- _sign_data.alg
- ),
- Logger::Warning
- );
- break;
- }
- }
-
- virtual
- void
- startVerify (
- SignatureAlgorithm alg,
- SignatureFormat sf
- ) {
- _pubkey.startVerify (alg, sf);
- }
-
- virtual
- void
- update (
- const MemoryRegion &in
- ) {
- if (_has_privateKeyRole) {
- if (_sign_data.hash != NULL) {
- _sign_data.hash->update (in);
- }
- else {
- _sign_data.raw.append (in.toByteArray ());
- }
- }
- else {
- _pubkey.update (in);
- }
- }
-
- virtual
- QByteArray
- endSign () {
- QByteArray result;
- bool session_locked = false;
-
- QCA_logTextMessage (
- "pkcs11RSAContext::endSign - entry",
- Logger::Debug
- );
-
- try {
- QByteArray final;
- CK_RV rv;
-
- // from some strange reason I got 2047... (for some) <---- BUG?!?!?!
- int myrsa_size=(_pubkey.bitSize () + 7) / 8;
-
- if (_sign_data.hash != NULL) {
- final = emsa3Encode (
- _sign_data.hash->type (),
- _sign_data.hash->final ().toByteArray (),
- myrsa_size
- );
- }
- else {
- final = _sign_data.raw;
- }
-
- if (final.size () == 0) {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Cannot encode signature");
- }
-
- _ensureCertificate ();
-
- size_t my_size;
-
- if (
- (rv = pkcs11h_certificate_lockSession (
- _pkcs11h_certificate
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot lock session");
- }
- session_locked = true;
-
- if (
- (rv = pkcs11h_certificate_signAny (
- _pkcs11h_certificate,
- CKM_RSA_PKCS,
- (const unsigned char *)final.constData (),
- (size_t)final.size (),
- NULL,
- &my_size
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Signature failed");
- }
-
- result.resize (my_size);
-
- if (
- (rv = pkcs11h_certificate_signAny (
- _pkcs11h_certificate,
- CKM_RSA_PKCS,
- (const unsigned char *)final.constData (),
- (size_t)final.size (),
- (unsigned char *)result.data (),
- &my_size
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Signature failed");
- }
-
- result.resize (my_size);
-
- if (
- (rv = pkcs11h_certificate_releaseSession (
- _pkcs11h_certificate
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot release session");
- }
- session_locked = false;
-
- }
- catch (const pkcs11Exception &e) {
- result.clear ();
-
- if (session_locked) {
- pkcs11h_certificate_releaseSession (
- _pkcs11h_certificate
- );
- session_locked = false;
- }
-
- if (s_keyStoreList != NULL) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Cannot sign: %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
- }
-
- _clearSign ();
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11RSAContext::endSign - return result.size ()=%d",
- result.size ()
- ),
- Logger::Debug
- );
-
- return result;
- }
-
- virtual
- bool
- validSignature (
- const QByteArray &sig
- ) {
- return _pubkey.validSignature (sig);
- }
-
- virtual
- void
- createPrivate (
- int bits,
- int exp,
- bool block
- ) {
- Q_UNUSED(bits);
- Q_UNUSED(exp);
- Q_UNUSED(block);
- }
-
- virtual
- void
- createPrivate (
- const BigInteger &n,
- const BigInteger &e,
- const BigInteger &p,
- const BigInteger &q,
- const BigInteger &d
- ) {
- Q_UNUSED(n);
- Q_UNUSED(e);
- Q_UNUSED(p);
- Q_UNUSED(q);
- Q_UNUSED(d);
- }
-
- virtual
- void
- createPublic (
- const BigInteger &n,
- const BigInteger &e
- ) {
- Q_UNUSED(n);
- Q_UNUSED(e);
- }
-
- virtual
- BigInteger
- n () const {
- return _pubkey.n ();
- }
-
- virtual
- BigInteger
- e () const {
- return _pubkey.e ();
- }
-
- virtual
- BigInteger
- p () const {
- return BigInteger();
- }
-
- virtual
- BigInteger
- q () const {
- return BigInteger();
- }
-
- virtual
- BigInteger
- d () const {
- return BigInteger();
- }
+ virtual
+ bool
+ isNull() const
+ {
+ return _pubkey.isNull();
+ }
+
+ virtual
+ PKey::Type
+ type() const
+ {
+ return _pubkey.type();
+ }
+
+ virtual
+ bool
+ isPrivate() const
+ {
+ return _has_privateKeyRole;
+ }
+
+ virtual
+ bool
+ canExport() const
+ {
+ return !_has_privateKeyRole;
+ }
+
+ virtual
+ void
+ convertToPublic()
+ {
+ QCA_logTextMessage(
+ "pkcs11RSAContext::convertToPublic - entry",
+ Logger::Debug
+ );
+
+ if (_has_privateKeyRole) {
+ if (_pkcs11h_certificate != NULL) {
+ pkcs11h_certificate_freeCertificate(_pkcs11h_certificate);
+ _pkcs11h_certificate = NULL;
+ }
+ _has_privateKeyRole = false;
+ }
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::convertToPublic - return",
+ Logger::Debug
+ );
+ }
+
+ virtual
+ int
+ bits() const
+ {
+ return _pubkey.bitSize();
+ }
+
+ virtual
+ int
+ maximumEncryptSize(
+ EncryptionAlgorithm alg
+ ) const
+ {
+ return _pubkey.maximumEncryptSize(alg);
+ }
+
+ virtual
+ SecureArray
+ encrypt(
+ const SecureArray &in,
+ EncryptionAlgorithm alg
+ )
+ {
+ return _pubkey.encrypt(in, alg);
+ }
+
+ virtual
+ bool
+ decrypt(
+ const SecureArray &in,
+ SecureArray *out,
+ EncryptionAlgorithm alg
+ )
+ {
+ bool session_locked = false;
+ bool ret = false;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11RSAContext::decrypt - decrypt in.size()=%d, alg=%d",
+ in.size(),
+ (int)alg
+ ),
+ Logger::Debug
+ );
+
+ try {
+ CK_MECHANISM_TYPE mech;
+ CK_RV rv;
+ size_t my_size;
+
+ switch (alg) {
+ case EME_PKCS1v15:
+ mech = CKM_RSA_PKCS;
+ break;
+ case EME_PKCS1_OAEP:
+ mech = CKM_RSA_PKCS_OAEP;
+ break;
+ default:
+ throw pkcs11Exception(CKR_FUNCTION_NOT_SUPPORTED, "Invalid algorithm");
+ break;
+ }
+
+ _ensureCertificate();
+
+ if (
+ (rv = pkcs11h_certificate_lockSession(
+ _pkcs11h_certificate
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot lock session");
+ }
+ session_locked = true;
+
+ if (
+ (rv = pkcs11h_certificate_decryptAny(
+ _pkcs11h_certificate,
+ mech,
+ (const unsigned char *)in.constData(),
+ in.size(),
+ NULL,
+ &my_size
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Decryption error");
+ }
+
+ out->resize(my_size);
+
+ if (
+ (rv = pkcs11h_certificate_decryptAny(
+ _pkcs11h_certificate,
+ mech,
+ (const unsigned char *)in.constData(),
+ in.size(),
+ (unsigned char *)out->data(),
+ &my_size
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Decryption error");
+ }
+
+ rv = out->resize(my_size);
+
+ if (
+ (rv = pkcs11h_certificate_releaseSession(
+ _pkcs11h_certificate
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot release session");
+ }
+ session_locked = false;
+
+ ret = true;
+ } catch (const pkcs11Exception &e) {
+ if (session_locked) {
+ pkcs11h_certificate_releaseSession(
+ _pkcs11h_certificate
+ );
+ session_locked = false;
+ }
+
+ if (s_keyStoreList != NULL) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Cannot decrypt: %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11RSAContext::decrypt - decrypt out->size()=%d",
+ out->size()
+ ),
+ Logger::Debug
+ );
+
+ return ret;
+ }
+
+ virtual
+ void
+ startSign(
+ SignatureAlgorithm alg,
+ SignatureFormat
+ )
+ {
+ _clearSign();
+
+ _sign_data.alg = alg;
+
+ switch (_sign_data.alg) {
+ case EMSA3_SHA1:
+ _sign_data.hash = new Hash("sha1");
+ break;
+ case EMSA3_MD5:
+ _sign_data.hash = new Hash("md5");
+ break;
+ case EMSA3_MD2:
+ _sign_data.hash = new Hash("md2");
+ break;
+ case EMSA3_Raw:
+ break;
+ case SignatureUnknown:
+ case EMSA1_SHA1:
+ case EMSA3_RIPEMD160:
+ default:
+ QCA_logTextMessage(
+ QString().sprintf(
+ "PKCS#11: Invalid hash algorithm %d",
+ _sign_data.alg
+ ),
+ Logger::Warning
+ );
+ break;
+ }
+ }
+
+ virtual
+ void
+ startVerify(
+ SignatureAlgorithm alg,
+ SignatureFormat sf
+ )
+ {
+ _pubkey.startVerify(alg, sf);
+ }
+
+ virtual
+ void
+ update(
+ const MemoryRegion &in
+ )
+ {
+ if (_has_privateKeyRole) {
+ if (_sign_data.hash != NULL) {
+ _sign_data.hash->update(in);
+ } else {
+ _sign_data.raw.append(in.toByteArray());
+ }
+ } else {
+ _pubkey.update(in);
+ }
+ }
+
+ virtual
+ QByteArray
+ endSign()
+ {
+ QByteArray result;
+ bool session_locked = false;
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::endSign - entry",
+ Logger::Debug
+ );
+
+ try {
+ QByteArray final;
+ CK_RV rv;
+
+ // from some strange reason I got 2047... (for some) <---- BUG?!?!?!
+ int myrsa_size = (_pubkey.bitSize() + 7) / 8;
+
+ if (_sign_data.hash != NULL) {
+ final = emsa3Encode(
+ _sign_data.hash->type(),
+ _sign_data.hash->final().toByteArray(),
+ myrsa_size
+ );
+ } else {
+ final = _sign_data.raw;
+ }
+
+ if (final.size() == 0) {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Cannot encode signature");
+ }
+
+ _ensureCertificate();
+
+ size_t my_size;
+
+ if (
+ (rv = pkcs11h_certificate_lockSession(
+ _pkcs11h_certificate
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot lock session");
+ }
+ session_locked = true;
+
+ if (
+ (rv = pkcs11h_certificate_signAny(
+ _pkcs11h_certificate,
+ CKM_RSA_PKCS,
+ (const unsigned char *)final.constData(),
+ (size_t)final.size(),
+ NULL,
+ &my_size
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Signature failed");
+ }
+
+ result.resize(my_size);
+
+ if (
+ (rv = pkcs11h_certificate_signAny(
+ _pkcs11h_certificate,
+ CKM_RSA_PKCS,
+ (const unsigned char *)final.constData(),
+ (size_t)final.size(),
+ (unsigned char *)result.data(),
+ &my_size
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Signature failed");
+ }
+
+ result.resize(my_size);
+
+ if (
+ (rv = pkcs11h_certificate_releaseSession(
+ _pkcs11h_certificate
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot release session");
+ }
+ session_locked = false;
+
+ } catch (const pkcs11Exception &e) {
+ result.clear();
+
+ if (session_locked) {
+ pkcs11h_certificate_releaseSession(
+ _pkcs11h_certificate
+ );
+ session_locked = false;
+ }
+
+ if (s_keyStoreList != NULL) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Cannot sign: %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+ }
+
+ _clearSign();
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11RSAContext::endSign - return result.size ()=%d",
+ result.size()
+ ),
+ Logger::Debug
+ );
+
+ return result;
+ }
+
+ virtual
+ bool
+ validSignature(
+ const QByteArray &sig
+ )
+ {
+ return _pubkey.validSignature(sig);
+ }
+
+ virtual
+ void
+ createPrivate(
+ int bits,
+ int exp,
+ bool block
+ )
+ {
+ Q_UNUSED(bits);
+ Q_UNUSED(exp);
+ Q_UNUSED(block);
+ }
+
+ virtual
+ void
+ createPrivate(
+ const BigInteger &n,
+ const BigInteger &e,
+ const BigInteger &p,
+ const BigInteger &q,
+ const BigInteger &d
+ )
+ {
+ Q_UNUSED(n);
+ Q_UNUSED(e);
+ Q_UNUSED(p);
+ Q_UNUSED(q);
+ Q_UNUSED(d);
+ }
+
+ virtual
+ void
+ createPublic(
+ const BigInteger &n,
+ const BigInteger &e
+ )
+ {
+ Q_UNUSED(n);
+ Q_UNUSED(e);
+ }
+
+ virtual
+ BigInteger
+ n() const
+ {
+ return _pubkey.n();
+ }
+
+ virtual
+ BigInteger
+ e() const
+ {
+ return _pubkey.e();
+ }
+
+ virtual
+ BigInteger
+ p() const
+ {
+ return BigInteger();
+ }
+
+ virtual
+ BigInteger
+ q() const
+ {
+ return BigInteger();
+ }
+
+ virtual
+ BigInteger
+ d() const
+ {
+ return BigInteger();
+ }
public:
- PublicKey
- _publicKey () const {
- return _pubkey;
- }
-
- bool
- _isTokenAvailable() const {
- bool ret;
-
- QCA_logTextMessage (
- "pkcs11RSAContext::_ensureTokenAvailable - entry",
- Logger::Debug
- );
-
- ret = pkcs11h_token_ensureAccess (
- _pkcs11h_certificate_id->token_id,
- NULL,
- 0
- ) == CKR_OK;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11RSAContext::_ensureTokenAvailable - return ret=%d",
- ret ? 1 : 0
- ),
- Logger::Debug
- );
-
- return ret;
- }
-
- bool
- _ensureTokenAccess () {
- bool ret;
-
- QCA_logTextMessage (
- "pkcs11RSAContext::_ensureTokenAccess - entry",
- Logger::Debug
- );
-
- ret = pkcs11h_token_ensureAccess (
- _pkcs11h_certificate_id->token_id,
- NULL,
- PKCS11H_PROMPT_MASK_ALLOW_ALL
- ) == CKR_OK;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11RSAContext::_ensureTokenAccess - return ret=%d",
- ret ? 1 : 0
- ),
- Logger::Debug
- );
-
- return ret;
- }
+ PublicKey
+ _publicKey() const
+ {
+ return _pubkey;
+ }
+
+ bool
+ _isTokenAvailable() const
+ {
+ bool ret;
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::_ensureTokenAvailable - entry",
+ Logger::Debug
+ );
+
+ ret = pkcs11h_token_ensureAccess(
+ _pkcs11h_certificate_id->token_id,
+ NULL,
+ 0
+ ) == CKR_OK;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11RSAContext::_ensureTokenAvailable - return ret=%d",
+ ret ? 1 : 0
+ ),
+ Logger::Debug
+ );
+
+ return ret;
+ }
+
+ bool
+ _ensureTokenAccess()
+ {
+ bool ret;
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::_ensureTokenAccess - entry",
+ Logger::Debug
+ );
+
+ ret = pkcs11h_token_ensureAccess(
+ _pkcs11h_certificate_id->token_id,
+ NULL,
+ PKCS11H_PROMPT_MASK_ALLOW_ALL
+ ) == CKR_OK;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11RSAContext::_ensureTokenAccess - return ret=%d",
+ ret ? 1 : 0
+ ),
+ Logger::Debug
+ );
+
+ return ret;
+ }
private:
- void
- _clearSign () {
- _sign_data.raw.clear ();
- _sign_data.alg = SignatureUnknown;
- delete _sign_data.hash;
- _sign_data.hash = NULL;
- }
-
- void
- _ensureCertificate () {
- CK_RV rv;
-
- QCA_logTextMessage (
- "pkcs11RSAContext::_ensureCertificate - entry",
- Logger::Debug
- );
-
- if (_pkcs11h_certificate == NULL) {
- if (
- (rv = pkcs11h_certificate_create (
- _pkcs11h_certificate_id,
- &_serialized,
- PKCS11H_PROMPT_MASK_ALLOW_ALL,
- PKCS11H_PIN_CACHE_INFINITE,
- &_pkcs11h_certificate
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot create low-level certificate");
- }
- }
-
- QCA_logTextMessage (
- "pkcs11RSAContext::_ensureCertificate - return",
- Logger::Debug
- );
- }
+ void
+ _clearSign()
+ {
+ _sign_data.raw.clear();
+ _sign_data.alg = SignatureUnknown;
+ delete _sign_data.hash;
+ _sign_data.hash = NULL;
+ }
+
+ void
+ _ensureCertificate()
+ {
+ CK_RV rv;
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::_ensureCertificate - entry",
+ Logger::Debug
+ );
+
+ if (_pkcs11h_certificate == NULL) {
+ if (
+ (rv = pkcs11h_certificate_create(
+ _pkcs11h_certificate_id,
+ &_serialized,
+ PKCS11H_PROMPT_MASK_ALLOW_ALL,
+ PKCS11H_PIN_CACHE_INFINITE,
+ &_pkcs11h_certificate
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot create low-level certificate");
+ }
+ }
+
+ QCA_logTextMessage(
+ "pkcs11RSAContext::_ensureCertificate - return",
+ Logger::Debug
+ );
+ }
};
//----------------------------------------------------------------------------
// pkcs11PKeyContext
//----------------------------------------------------------------------------
class pkcs11PKeyContext : public PKeyContext
{
private:
- PKeyBase *_k;
+ PKeyBase *_k;
public:
- pkcs11PKeyContext (Provider *p) : PKeyContext (p) {
- _k = NULL;
- }
-
- ~pkcs11PKeyContext () {
- delete _k;
- _k = NULL;
- }
-
- virtual
- Provider::Context *
- clone () const {
- pkcs11PKeyContext *c = new pkcs11PKeyContext (*this);
- c->_k = (PKeyBase *)_k->clone();
- return c;
- }
+ pkcs11PKeyContext(Provider *p) : PKeyContext(p)
+ {
+ _k = NULL;
+ }
+
+ ~pkcs11PKeyContext()
+ {
+ delete _k;
+ _k = NULL;
+ }
+
+ virtual
+ Provider::Context *
+ clone() const
+ {
+ pkcs11PKeyContext *c = new pkcs11PKeyContext(*this);
+ c->_k = (PKeyBase *)_k->clone();
+ return c;
+ }
public:
- virtual
- QList<PKey::Type>
- supportedTypes () const {
- QList<PKey::Type> list;
- list += PKey::RSA;
- return list;
- }
-
- virtual
- QList<PKey::Type>
- supportedIOTypes () const {
- QList<PKey::Type> list;
- list += PKey::RSA;
- return list;
- }
-
- virtual
- QList<PBEAlgorithm>
- supportedPBEAlgorithms () const {
- QList<PBEAlgorithm> list;
- return list;
- }
-
- virtual
- PKeyBase *
- key () {
- return _k;
- }
-
- virtual
- const PKeyBase *
- key () const {
- return _k;
- }
-
- virtual
- void
- setKey (PKeyBase *key) {
- delete _k;
- _k = key;
- }
-
- virtual
- bool
- importKey (
- const PKeyBase *key
- ) {
- Q_UNUSED(key);
- return false;
- }
-
- static
- int
- passphrase_cb (
- char *buf,
- int size,
- int rwflag,
- void *u
- ) {
- Q_UNUSED(buf);
- Q_UNUSED(size);
- Q_UNUSED(rwflag);
- Q_UNUSED(u);
- return 0;
- }
-
- virtual
- QByteArray
- publicToDER () const {
- return static_cast<pkcs11RSAContext *>(_k)->_publicKey ().toDER ();
- }
-
- virtual
- QString
- publicToPEM () const {
- return static_cast<pkcs11RSAContext *>(_k)->_publicKey ().toPEM ();
- }
-
- virtual
- ConvertResult
- publicFromDER (
- const QByteArray &in
- ) {
- Q_UNUSED(in);
- return ErrorDecode;
- }
-
- virtual
- ConvertResult
- publicFromPEM (
- const QString &s
- ) {
- Q_UNUSED(s);
- return ErrorDecode;
- }
-
- virtual
- SecureArray
- privateToDER(
- const SecureArray &passphrase,
- PBEAlgorithm pbe
- ) const {
- Q_UNUSED(passphrase);
- Q_UNUSED(pbe);
- return SecureArray ();
- }
-
- virtual
- QString
- privateToPEM (
- const SecureArray &passphrase,
- PBEAlgorithm pbe
- ) const {
- Q_UNUSED(passphrase);
- Q_UNUSED(pbe);
- return QString ();
- }
-
- virtual
- ConvertResult
- privateFromDER (
- const SecureArray &in,
- const SecureArray &passphrase
- ) {
- Q_UNUSED(in);
- Q_UNUSED(passphrase);
- return ErrorDecode;
- }
-
- virtual
- ConvertResult
- privateFromPEM (
- const QString &s,
- const SecureArray &passphrase
- ) {
- Q_UNUSED(s);
- Q_UNUSED(passphrase);
- return ErrorDecode;
- }
+ virtual
+ QList<PKey::Type>
+ supportedTypes() const
+ {
+ QList<PKey::Type> list;
+ list += PKey::RSA;
+ return list;
+ }
+
+ virtual
+ QList<PKey::Type>
+ supportedIOTypes() const
+ {
+ QList<PKey::Type> list;
+ list += PKey::RSA;
+ return list;
+ }
+
+ virtual
+ QList<PBEAlgorithm>
+ supportedPBEAlgorithms() const
+ {
+ QList<PBEAlgorithm> list;
+ return list;
+ }
+
+ virtual
+ PKeyBase *
+ key()
+ {
+ return _k;
+ }
+
+ virtual
+ const PKeyBase *
+ key() const
+ {
+ return _k;
+ }
+
+ virtual
+ void
+ setKey(PKeyBase *key)
+ {
+ delete _k;
+ _k = key;
+ }
+
+ virtual
+ bool
+ importKey(
+ const PKeyBase *key
+ )
+ {
+ Q_UNUSED(key);
+ return false;
+ }
+
+ static
+ int
+ passphrase_cb(
+ char *buf,
+ int size,
+ int rwflag,
+ void *u
+ )
+ {
+ Q_UNUSED(buf);
+ Q_UNUSED(size);
+ Q_UNUSED(rwflag);
+ Q_UNUSED(u);
+ return 0;
+ }
+
+ virtual
+ QByteArray
+ publicToDER() const
+ {
+ return static_cast<pkcs11RSAContext *>(_k)->_publicKey().toDER();
+ }
+
+ virtual
+ QString
+ publicToPEM() const
+ {
+ return static_cast<pkcs11RSAContext *>(_k)->_publicKey().toPEM();
+ }
+
+ virtual
+ ConvertResult
+ publicFromDER(
+ const QByteArray &in
+ )
+ {
+ Q_UNUSED(in);
+ return ErrorDecode;
+ }
+
+ virtual
+ ConvertResult
+ publicFromPEM(
+ const QString &s
+ )
+ {
+ Q_UNUSED(s);
+ return ErrorDecode;
+ }
+
+ virtual
+ SecureArray
+ privateToDER(
+ const SecureArray &passphrase,
+ PBEAlgorithm pbe
+ ) const
+ {
+ Q_UNUSED(passphrase);
+ Q_UNUSED(pbe);
+ return SecureArray();
+ }
+
+ virtual
+ QString
+ privateToPEM(
+ const SecureArray &passphrase,
+ PBEAlgorithm pbe
+ ) const
+ {
+ Q_UNUSED(passphrase);
+ Q_UNUSED(pbe);
+ return QString();
+ }
+
+ virtual
+ ConvertResult
+ privateFromDER(
+ const SecureArray &in,
+ const SecureArray &passphrase
+ )
+ {
+ Q_UNUSED(in);
+ Q_UNUSED(passphrase);
+ return ErrorDecode;
+ }
+
+ virtual
+ ConvertResult
+ privateFromPEM(
+ const QString &s,
+ const SecureArray &passphrase
+ )
+ {
+ Q_UNUSED(s);
+ Q_UNUSED(passphrase);
+ return ErrorDecode;
+ }
};
//----------------------------------------------------------------------------
// pkcs11KeyStoreEntryContext
//----------------------------------------------------------------------------
class pkcs11KeyStoreEntryContext : public KeyStoreEntryContext
{
private:
- KeyStoreEntry::Type _item_type;
- KeyBundle _key;
- Certificate _cert;
- QString _storeId;
- QString _id;
- QString _serialized;
- QString _storeName;
- QString _name;
+ KeyStoreEntry::Type _item_type;
+ KeyBundle _key;
+ Certificate _cert;
+ QString _storeId;
+ QString _id;
+ QString _serialized;
+ QString _storeName;
+ QString _name;
public:
- pkcs11KeyStoreEntryContext (
- const Certificate &cert,
- const QString &storeId,
- const QString &serialized,
- const QString &storeName,
- const QString &name,
- Provider *p
- ) : KeyStoreEntryContext(p) {
- _item_type = KeyStoreEntry::TypeCertificate;
- _cert = cert;
- _storeId = storeId;
- _id = certificateHash (_cert);
- _serialized = serialized;
- _storeName = storeName;
- _name = name;
- }
-
- pkcs11KeyStoreEntryContext (
- const KeyBundle &key,
- const QString &storeId,
- const QString &serialized,
- const QString &storeName,
- const QString &name,
- Provider *p
- ) : KeyStoreEntryContext(p) {
- _item_type = KeyStoreEntry::TypeKeyBundle;
- _key = key;
- _storeId = storeId,
- _id = certificateHash (key.certificateChain ().primary ());
- _serialized = serialized;
- _storeName = storeName;
- _name = name;
- }
-
- pkcs11KeyStoreEntryContext (
- const pkcs11KeyStoreEntryContext &from
- ) : KeyStoreEntryContext(from) {
- _item_type = from._item_type;
- _key = from._key;
- _storeId = from._storeId;
- _id = from._id;
- _serialized = from._serialized;
- _storeName = from._storeName;
- _name = from._name;
- }
-
- virtual
- Provider::Context *
- clone () const {
- return new pkcs11KeyStoreEntryContext (*this);
- }
+ pkcs11KeyStoreEntryContext(
+ const Certificate &cert,
+ const QString &storeId,
+ const QString &serialized,
+ const QString &storeName,
+ const QString &name,
+ Provider *p
+ ) : KeyStoreEntryContext(p)
+ {
+ _item_type = KeyStoreEntry::TypeCertificate;
+ _cert = cert;
+ _storeId = storeId;
+ _id = certificateHash(_cert);
+ _serialized = serialized;
+ _storeName = storeName;
+ _name = name;
+ }
+
+ pkcs11KeyStoreEntryContext(
+ const KeyBundle &key,
+ const QString &storeId,
+ const QString &serialized,
+ const QString &storeName,
+ const QString &name,
+ Provider *p
+ ) : KeyStoreEntryContext(p)
+ {
+ _item_type = KeyStoreEntry::TypeKeyBundle;
+ _key = key;
+ _storeId = storeId,
+ _id = certificateHash(key.certificateChain().primary());
+ _serialized = serialized;
+ _storeName = storeName;
+ _name = name;
+ }
+
+ pkcs11KeyStoreEntryContext(
+ const pkcs11KeyStoreEntryContext &from
+ ) : KeyStoreEntryContext(from)
+ {
+ _item_type = from._item_type;
+ _key = from._key;
+ _storeId = from._storeId;
+ _id = from._id;
+ _serialized = from._serialized;
+ _storeName = from._storeName;
+ _name = from._name;
+ }
+
+ virtual
+ Provider::Context *
+ clone() const
+ {
+ return new pkcs11KeyStoreEntryContext(*this);
+ }
public:
- virtual
- KeyStoreEntry::Type
- type () const {
- return _item_type;
- }
-
- virtual
- QString
- name () const {
- return _name;
- }
-
- virtual
- QString
- id () const {
- return _id;
- }
-
- virtual
- KeyBundle
- keyBundle () const {
- return _key;
- }
-
- virtual
- Certificate
- certificate () const {
- return _cert;
- }
-
- virtual
- QString
- storeId () const {
- return _storeId;
- }
-
- virtual
- QString
- storeName () const {
- return _storeName;
- }
-
- virtual
- bool
- isAvailable() const {
- return static_cast<pkcs11RSAContext *>(static_cast<PKeyContext *>(_key.privateKey ().context ())->key ())->_isTokenAvailable ();
- }
-
- virtual
- bool
- ensureAccess () {
- return static_cast<pkcs11RSAContext *>(static_cast<PKeyContext *>(_key.privateKey ().context ())->key ())->_ensureTokenAccess ();
- }
-
- virtual
- QString
- serialize () const {
- return _serialized;
- }
+ virtual
+ KeyStoreEntry::Type
+ type() const
+ {
+ return _item_type;
+ }
+
+ virtual
+ QString
+ name() const
+ {
+ return _name;
+ }
+
+ virtual
+ QString
+ id() const
+ {
+ return _id;
+ }
+
+ virtual
+ KeyBundle
+ keyBundle() const
+ {
+ return _key;
+ }
+
+ virtual
+ Certificate
+ certificate() const
+ {
+ return _cert;
+ }
+
+ virtual
+ QString
+ storeId() const
+ {
+ return _storeId;
+ }
+
+ virtual
+ QString
+ storeName() const
+ {
+ return _storeName;
+ }
+
+ virtual
+ bool
+ isAvailable() const
+ {
+ return static_cast<pkcs11RSAContext *>(static_cast<PKeyContext *>(_key.privateKey().context())->key())->_isTokenAvailable();
+ }
+
+ virtual
+ bool
+ ensureAccess()
+ {
+ return static_cast<pkcs11RSAContext *>(static_cast<PKeyContext *>(_key.privateKey().context())->key())->_ensureTokenAccess();
+ }
+
+ virtual
+ QString
+ serialize() const
+ {
+ return _serialized;
+ }
};
//----------------------------------------------------------------------------
// pkcs11QCACrypto
//----------------------------------------------------------------------------
-class pkcs11QCACrypto {
+class pkcs11QCACrypto
+{
private:
- static
- int
- _pkcs11h_crypto_qca_initialize (
- void * const global_data
- ) {
- Q_UNUSED(global_data);
-
- return TRUE; //krazy:exclude=captruefalse
- }
-
- static
- int
- _pkcs11h_crypto_qca_uninitialize (
- void * const global_data
- ) {
- Q_UNUSED(global_data);
-
- return TRUE; //krazy:exclude=captruefalse
- }
-
- static
- int
- _pkcs11h_crypto_qca_certificate_get_expiration (
- void * const global_data,
- const unsigned char * const blob,
- const size_t blob_size,
- time_t * const expiration
- ) {
- Q_UNUSED(global_data);
-
- Certificate cert = Certificate::fromDER (
- QByteArray (
- (char *)blob,
- blob_size
- )
- );
-
- *expiration = cert.notValidAfter ().toTime_t ();
-
- return TRUE; //krazy:exclude=captruefalse
- }
-
- static
- int
- _pkcs11h_crypto_qca_certificate_get_dn (
- void * const global_data,
- const unsigned char * const blob,
- const size_t blob_size,
- char * const dn,
- const size_t dn_max
- ) {
- Q_UNUSED(global_data);
-
- Certificate cert = Certificate::fromDER (
- QByteArray (
- (char *)blob,
- blob_size
- )
- );
- QString qdn = cert.subjectInfoOrdered ().toString ();
-
- if ((size_t)qdn.length () > dn_max-1) {
- return FALSE; //krazy:exclude=captruefalse
- }
- else {
- qstrcpy (dn, myPrintable (qdn));
- return TRUE; //krazy:exclude=captruefalse
- }
- }
-
- static
- int
- _pkcs11h_crypto_qca_certificate_is_issuer (
- void * const global_data,
- const unsigned char * const signer_blob,
- const size_t signer_blob_size,
- const unsigned char * const cert_blob,
- const size_t cert_blob_size
- ) {
- Q_UNUSED(global_data);
-
- Certificate signer = Certificate::fromDER (
- QByteArray (
- (char *)signer_blob,
- signer_blob_size
- )
- );
-
- Certificate cert = Certificate::fromDER (
- QByteArray (
- (char *)cert_blob,
- cert_blob_size
- )
- );
-
- return signer.isIssuerOf (cert);
- }
+ static
+ int
+ _pkcs11h_crypto_qca_initialize(
+ void *const global_data
+ )
+ {
+ Q_UNUSED(global_data);
+
+ return TRUE; //krazy:exclude=captruefalse
+ }
+
+ static
+ int
+ _pkcs11h_crypto_qca_uninitialize(
+ void *const global_data
+ )
+ {
+ Q_UNUSED(global_data);
+
+ return TRUE; //krazy:exclude=captruefalse
+ }
+
+ static
+ int
+ _pkcs11h_crypto_qca_certificate_get_expiration(
+ void *const global_data,
+ const unsigned char *const blob,
+ const size_t blob_size,
+ time_t *const expiration
+ )
+ {
+ Q_UNUSED(global_data);
+
+ Certificate cert = Certificate::fromDER(
+ QByteArray(
+ (char *)blob,
+ blob_size
+ )
+ );
+
+ *expiration = cert.notValidAfter().toTime_t ();
+
+ return TRUE; //krazy:exclude=captruefalse
+ }
+
+ static
+ int
+ _pkcs11h_crypto_qca_certificate_get_dn(
+ void *const global_data,
+ const unsigned char *const blob,
+ const size_t blob_size,
+ char *const dn,
+ const size_t dn_max
+ )
+ {
+ Q_UNUSED(global_data);
+
+ Certificate cert = Certificate::fromDER(
+ QByteArray(
+ (char *)blob,
+ blob_size
+ )
+ );
+ QString qdn = cert.subjectInfoOrdered().toString();
+
+ if ((size_t)qdn.length() > dn_max - 1) {
+ return FALSE; //krazy:exclude=captruefalse
+ } else {
+ qstrcpy(dn, myPrintable(qdn));
+ return TRUE; //krazy:exclude=captruefalse
+ }
+ }
+
+ static
+ int
+ _pkcs11h_crypto_qca_certificate_is_issuer(
+ void *const global_data,
+ const unsigned char *const signer_blob,
+ const size_t signer_blob_size,
+ const unsigned char *const cert_blob,
+ const size_t cert_blob_size
+ )
+ {
+ Q_UNUSED(global_data);
+
+ Certificate signer = Certificate::fromDER(
+ QByteArray(
+ (char *)signer_blob,
+ signer_blob_size
+ )
+ );
+
+ Certificate cert = Certificate::fromDER(
+ QByteArray(
+ (char *)cert_blob,
+ cert_blob_size
+ )
+ );
+
+ return signer.isIssuerOf(cert);
+ }
public:
- static pkcs11h_engine_crypto_t crypto;
+ static pkcs11h_engine_crypto_t crypto;
};
pkcs11h_engine_crypto_t pkcs11QCACrypto::crypto = {
- NULL,
- _pkcs11h_crypto_qca_initialize,
- _pkcs11h_crypto_qca_uninitialize,
- _pkcs11h_crypto_qca_certificate_get_expiration,
- _pkcs11h_crypto_qca_certificate_get_dn,
- _pkcs11h_crypto_qca_certificate_is_issuer
+ NULL,
+ _pkcs11h_crypto_qca_initialize,
+ _pkcs11h_crypto_qca_uninitialize,
+ _pkcs11h_crypto_qca_certificate_get_expiration,
+ _pkcs11h_crypto_qca_certificate_get_dn,
+ _pkcs11h_crypto_qca_certificate_is_issuer
};
//----------------------------------------------------------------------------
// pkcs11KeyStoreListContext
//----------------------------------------------------------------------------
-pkcs11KeyStoreListContext::pkcs11KeyStoreListContext (Provider *p) : KeyStoreListContext(p) {
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::pkcs11KeyStoreListContext - entry Provider=%p",
- (void *)p
- ),
- Logger::Debug
- );
-
- _last_id = 0;
- _initialized = false;
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::pkcs11KeyStoreListContext - return",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::pkcs11KeyStoreListContext(Provider *p) : KeyStoreListContext(p)
+{
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::pkcs11KeyStoreListContext - entry Provider=%p",
+ (void *)p
+ ),
+ Logger::Debug
+ );
+
+ _last_id = 0;
+ _initialized = false;
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::pkcs11KeyStoreListContext - return",
+ Logger::Debug
+ );
}
-pkcs11KeyStoreListContext::~pkcs11KeyStoreListContext () {
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::~pkcs11KeyStoreListContext - entry",
- Logger::Debug
- );
-
- s_keyStoreList = NULL;
- _clearStores ();
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::~pkcs11KeyStoreListContext - return",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::~pkcs11KeyStoreListContext()
+{
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::~pkcs11KeyStoreListContext - entry",
+ Logger::Debug
+ );
+
+ s_keyStoreList = NULL;
+ _clearStores();
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::~pkcs11KeyStoreListContext - return",
+ Logger::Debug
+ );
}
Provider::Context *
-pkcs11KeyStoreListContext::clone () const {
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::clone - entry/return",
- Logger::Debug
- );
- return NULL;
+pkcs11KeyStoreListContext::clone() const
+{
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::clone - entry/return",
+ Logger::Debug
+ );
+ return NULL;
}
void
-pkcs11KeyStoreListContext::start () {
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::start - entry",
- Logger::Debug
- );
-
- QMetaObject::invokeMethod(this, "doReady", Qt::QueuedConnection);
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::start - return",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::start()
+{
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::start - entry",
+ Logger::Debug
+ );
+
+ QMetaObject::invokeMethod(this, "doReady", Qt::QueuedConnection);
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::start - return",
+ Logger::Debug
+ );
}
void
-pkcs11KeyStoreListContext::setUpdatesEnabled (bool enabled) {
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::setUpdatesEnabled - entry enabled=%d",
- enabled ? 1 : 0
- ),
- Logger::Debug
- );
-
- try {
- pkcs11Provider *p = static_cast<pkcs11Provider *>(provider ());
- if (enabled) {
- p->startSlotEvents ();
- }
- else {
- p->stopSlotEvents ();
- }
- }
- catch (const pkcs11Exception &e) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Start event failed %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::setUpdatesEnabled - return",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::setUpdatesEnabled(bool enabled)
+{
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::setUpdatesEnabled - entry enabled=%d",
+ enabled ? 1 : 0
+ ),
+ Logger::Debug
+ );
+
+ try {
+ pkcs11Provider *p = static_cast<pkcs11Provider *>(provider());
+ if (enabled) {
+ p->startSlotEvents();
+ } else {
+ p->stopSlotEvents();
+ }
+ } catch (const pkcs11Exception &e) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Start event failed %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::setUpdatesEnabled - return",
+ Logger::Debug
+ );
}
KeyStoreEntryContext *
-pkcs11KeyStoreListContext::entry (
- int id,
- const QString &entryId
-) {
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::entry - entry/return id=%d entryId='%s'",
- id,
- myPrintable (entryId)
- ),
- Logger::Debug
- );
-
- Q_UNUSED(id);
- Q_UNUSED(entryId);
- return NULL;
+pkcs11KeyStoreListContext::entry(
+ int id,
+ const QString &entryId
+)
+{
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::entry - entry/return id=%d entryId='%s'",
+ id,
+ myPrintable(entryId)
+ ),
+ Logger::Debug
+ );
+
+ Q_UNUSED(id);
+ Q_UNUSED(entryId);
+ return NULL;
}
KeyStoreEntryContext *
-pkcs11KeyStoreListContext::entryPassive (
- const QString &serialized
-) {
- KeyStoreEntryContext *entry = NULL;
- pkcs11h_certificate_id_t certificate_id = NULL;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::entryPassive - entry serialized='%s'",
- myPrintable (serialized)
- ),
- Logger::Debug
- );
-
- try {
- if (serialized.startsWith ("qca-pkcs11/")) {
- CertificateChain chain;
- bool has_private;
-
- _deserializeCertificate (serialized, &certificate_id, &has_private, chain);
- pkcs11KeyStoreItem *sentry = _registerTokenId (certificate_id->token_id);
- sentry->registerCertificates (chain);
- QMap<QString, QString> friendlyNames = sentry->friendlyNames ();
-
- entry = _keyStoreEntryByCertificateId (
- certificate_id,
- has_private,
- chain,
- friendlyNames[certificateHash (chain.primary ())]
- );
- }
- }
- catch (const pkcs11Exception &e) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Add key store entry %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
-
- if (certificate_id != NULL) {
- pkcs11h_certificate_freeCertificateId (certificate_id);
- certificate_id = NULL;
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::entryPassive - return entry=%p",
- (void *)entry
- ),
- Logger::Debug
- );
-
- return entry;
+pkcs11KeyStoreListContext::entryPassive(
+ const QString &serialized
+)
+{
+ KeyStoreEntryContext *entry = NULL;
+ pkcs11h_certificate_id_t certificate_id = NULL;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::entryPassive - entry serialized='%s'",
+ myPrintable(serialized)
+ ),
+ Logger::Debug
+ );
+
+ try {
+ if (serialized.startsWith("qca-pkcs11/")) {
+ CertificateChain chain;
+ bool has_private;
+
+ _deserializeCertificate(serialized, &certificate_id, &has_private, chain);
+ pkcs11KeyStoreItem *sentry = _registerTokenId(certificate_id->token_id);
+ sentry->registerCertificates(chain);
+ QMap<QString, QString> friendlyNames = sentry->friendlyNames();
+
+ entry = _keyStoreEntryByCertificateId(
+ certificate_id,
+ has_private,
+ chain,
+ friendlyNames[certificateHash(chain.primary())]
+ );
+ }
+ } catch (const pkcs11Exception &e) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Add key store entry %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+
+ if (certificate_id != NULL) {
+ pkcs11h_certificate_freeCertificateId(certificate_id);
+ certificate_id = NULL;
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::entryPassive - return entry=%p",
+ (void *)entry
+ ),
+ Logger::Debug
+ );
+
+ return entry;
}
KeyStore::Type
-pkcs11KeyStoreListContext::type (int id) const {
+pkcs11KeyStoreListContext::type(int id) const
+{
- Q_UNUSED(id);
+ Q_UNUSED(id);
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::type - entry/return id=%d",
- id
- ),
- Logger::Debug
- );
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::type - entry/return id=%d",
+ id
+ ),
+ Logger::Debug
+ );
- return KeyStore::SmartCard;
+ return KeyStore::SmartCard;
}
QString
-pkcs11KeyStoreListContext::storeId (int id) const {
- QString ret;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::storeId - entry id=%d",
- id
- ),
- Logger::Debug
- );
-
- if (_storesById.contains (id)) {
- ret = _tokenId2storeId (_storesById[id]->tokenId ());
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::storeId - return ret=%s",
- myPrintable (ret)
- ),
- Logger::Debug
- );
-
- return ret;
+pkcs11KeyStoreListContext::storeId(int id) const
+{
+ QString ret;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::storeId - entry id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ if (_storesById.contains(id)) {
+ ret = _tokenId2storeId(_storesById[id]->tokenId());
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::storeId - return ret=%s",
+ myPrintable(ret)
+ ),
+ Logger::Debug
+ );
+
+ return ret;
}
QString
-pkcs11KeyStoreListContext::name (int id) const {
- QString ret;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::name - entry id=%d",
- id
- ),
- Logger::Debug
- );
-
- if (_storesById.contains (id)) {
- ret = _storesById[id]->tokenId ()->label;
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::name - return ret=%s",
- myPrintable (ret)
- ),
- Logger::Debug
- );
-
- return ret;
+pkcs11KeyStoreListContext::name(int id) const
+{
+ QString ret;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::name - entry id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ if (_storesById.contains(id)) {
+ ret = _storesById[id]->tokenId()->label;
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::name - return ret=%s",
+ myPrintable(ret)
+ ),
+ Logger::Debug
+ );
+
+ return ret;
}
QList<KeyStoreEntry::Type>
-pkcs11KeyStoreListContext::entryTypes (int id) const {
-
- Q_UNUSED(id);
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::entryTypes - entry/return id=%d",
- id
- ),
- Logger::Debug
- );
-
- QList<KeyStoreEntry::Type> list;
- list += KeyStoreEntry::TypeKeyBundle;
- list += KeyStoreEntry::TypeCertificate;
- return list;
+pkcs11KeyStoreListContext::entryTypes(int id) const
+{
+
+ Q_UNUSED(id);
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::entryTypes - entry/return id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ QList<KeyStoreEntry::Type> list;
+ list += KeyStoreEntry::TypeKeyBundle;
+ list += KeyStoreEntry::TypeCertificate;
+ return list;
}
QList<int>
-pkcs11KeyStoreListContext::keyStores () {
- pkcs11h_token_id_list_t tokens = NULL;
- QList<int> out;
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::keyStores - entry",
- Logger::Debug
- );
-
- try {
- CK_RV rv;
-
- /*
- * Get available tokens
- */
- if (
- (rv = pkcs11h_token_enumTokenIds (
- PKCS11H_ENUM_METHOD_CACHE_EXIST,
- &tokens
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Enumerating tokens");
- }
-
- /*
- * Register all tokens, unmark
- * them from remove list
- */
- QList<int> to_remove = _storesById.keys ();
- for (
- pkcs11h_token_id_list_t entry = tokens;
- entry != NULL;
- entry = entry->next
- ) {
- pkcs11KeyStoreItem *item = _registerTokenId (entry->token_id);
- out += item->id ();
- to_remove.removeAll (item->id ());
- }
-
- /*
- * Remove all items
- * that were not discovered
- */
- {
- QMutexLocker l(&_mutexStores);
-
- foreach (int i, to_remove) {
- pkcs11KeyStoreItem *item = _storesById[i];
-
- _storesById.remove (item->id ());
- _stores.removeAll (item);
-
- delete item;
- item = NULL;
- }
- }
- }
- catch (const pkcs11Exception &e) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Cannot get key stores: %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
-
- if (tokens != NULL) {
- pkcs11h_token_freeTokenIdList (tokens);
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::keyStores - return out.size()=%d",
- out.size ()
- ),
- Logger::Debug
- );
-
- return out;
+pkcs11KeyStoreListContext::keyStores()
+{
+ pkcs11h_token_id_list_t tokens = NULL;
+ QList<int> out;
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::keyStores - entry",
+ Logger::Debug
+ );
+
+ try {
+ CK_RV rv;
+
+ /*
+ * Get available tokens
+ */
+ if (
+ (rv = pkcs11h_token_enumTokenIds(
+ PKCS11H_ENUM_METHOD_CACHE_EXIST,
+ &tokens
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Enumerating tokens");
+ }
+
+ /*
+ * Register all tokens, unmark
+ * them from remove list
+ */
+ QList<int> to_remove = _storesById.keys();
+ for (
+ pkcs11h_token_id_list_t entry = tokens;
+ entry != NULL;
+ entry = entry->next
+ ) {
+ pkcs11KeyStoreItem *item = _registerTokenId(entry->token_id);
+ out += item->id();
+ to_remove.removeAll(item->id());
+ }
+
+ /*
+ * Remove all items
+ * that were not discovered
+ */
+ {
+ QMutexLocker l(&_mutexStores);
+
+ foreach (int i, to_remove) {
+ pkcs11KeyStoreItem *item = _storesById[i];
+
+ _storesById.remove(item->id());
+ _stores.removeAll(item);
+
+ delete item;
+ item = NULL;
+ }
+ }
+ } catch (const pkcs11Exception &e) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Cannot get key stores: %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+
+ if (tokens != NULL) {
+ pkcs11h_token_freeTokenIdList(tokens);
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::keyStores - return out.size()=%d",
+ out.size()
+ ),
+ Logger::Debug
+ );
+
+ return out;
}
-QList<KeyStoreEntryContext*>
-pkcs11KeyStoreListContext::entryList (int id) {
- pkcs11h_certificate_id_list_t certs = NULL;
- QList<KeyStoreEntryContext*> out;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::entryList - entry id=%d",
- id
- ),
- Logger::Debug
- );
-
- try {
- CK_RV rv;
-
- if (_storesById.contains (id)) {
- pkcs11KeyStoreItem *entry = _storesById[id];
-
- pkcs11h_certificate_id_list_t issuers = NULL;
- pkcs11h_certificate_id_list_t current = NULL;
- QList<Certificate> listCerts;
- QList<Certificate> listIssuers;
- QList<pkcs11h_certificate_id_list_t> listIds;
- int i = 0;
-
- if (
- (rv = pkcs11h_certificate_enumTokenCertificateIds (
- entry->tokenId (),
- PKCS11H_ENUM_METHOD_CACHE,
- NULL,
- PKCS11H_PROMPT_MASK_ALLOW_ALL,
- &issuers,
- &certs
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Enumerate certificates");
- }
-
- for (
- current=certs;
- current!=NULL;
- current=current->next
- ) {
- if (current->certificate_id->certificate_blob_size > 0) {
- listCerts += Certificate::fromDER (
- QByteArray (
- (char *)current->certificate_id->certificate_blob,
- current->certificate_id->certificate_blob_size
- )
- );
- }
- }
-
- for (
- current=issuers;
- current!=NULL;
- current=current->next
- ) {
- if (current->certificate_id->certificate_blob_size > 0) {
- listIssuers += Certificate::fromDER (
- QByteArray (
- (char *)current->certificate_id->certificate_blob,
- current->certificate_id->certificate_blob_size
- )
- );
- }
- }
-
- entry->registerCertificates (listIssuers + listCerts);
- QMap<QString, QString> friendlyNames = entry->friendlyNames ();
-
- QList<Certificate> listIssuersForComplete;
- if (dynamic_cast<pkcs11Provider *> (provider ())->_allowLoadRootCA) {
- listIssuersForComplete = listIssuers;
- }
- else {
- foreach (Certificate c, listIssuers) {
- if (!c.isSelfSigned ()) {
- listIssuersForComplete += c;
- }
- }
- }
-
- for (
- i=0, current=issuers;
- current!=NULL;
- i++, current=current->next
- ) {
- try {
- if (listIssuers[i].isNull ()) {
- throw pkcs11Exception (CKR_ARGUMENTS_BAD, "Invalid certificate");
- }
-
- if (
- listIssuers[i].isSelfSigned () &&
- dynamic_cast<pkcs11Provider *> (provider ())->_allowLoadRootCA
- ) {
- CertificateChain chain = CertificateChain (listIssuers[i]).complete (listIssuersForComplete);
- out += _keyStoreEntryByCertificateId (
- current->certificate_id,
- false,
- chain,
- friendlyNames[certificateHash (chain.primary ())]
- );
- }
- }
- catch (const pkcs11Exception &e) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Add key store entry %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
- }
-
- for (
- i=0, current=certs;
- current!=NULL;
- i++, current=current->next
- ) {
- try {
- if (listCerts[i].isNull ()) {
- throw pkcs11Exception (CKR_ARGUMENTS_BAD, "Invalid certificate");
- }
-
- CertificateChain chain = CertificateChain (listCerts[i]).complete (listIssuersForComplete);
- out += _keyStoreEntryByCertificateId (
- current->certificate_id,
- true,
- chain,
- friendlyNames[certificateHash (chain.primary ())]
- );
- }
- catch (const pkcs11Exception &e) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Add key store entry %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
- }
- }
- }
- catch (const pkcs11Exception &e) {
- s_keyStoreList->_emit_diagnosticText (
- QString ().sprintf (
- "PKCS#11: Enumerating store failed %lu-'%s'.\n",
- e.rv (),
- myPrintable (e.message ())
- )
- );
- }
-
- if (certs != NULL) {
- pkcs11h_certificate_freeCertificateIdList (certs);
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::entryList - return out.size()=%d",
- out.size ()
- ),
- Logger::Debug
- );
-
- return out;
+QList<KeyStoreEntryContext *>
+pkcs11KeyStoreListContext::entryList(int id)
+{
+ pkcs11h_certificate_id_list_t certs = NULL;
+ QList<KeyStoreEntryContext *> out;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::entryList - entry id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ try {
+ CK_RV rv;
+
+ if (_storesById.contains(id)) {
+ pkcs11KeyStoreItem *entry = _storesById[id];
+
+ pkcs11h_certificate_id_list_t issuers = NULL;
+ pkcs11h_certificate_id_list_t current = NULL;
+ QList<Certificate> listCerts;
+ QList<Certificate> listIssuers;
+ QList<pkcs11h_certificate_id_list_t> listIds;
+ int i = 0;
+
+ if (
+ (rv = pkcs11h_certificate_enumTokenCertificateIds(
+ entry->tokenId(),
+ PKCS11H_ENUM_METHOD_CACHE,
+ NULL,
+ PKCS11H_PROMPT_MASK_ALLOW_ALL,
+ &issuers,
+ &certs
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Enumerate certificates");
+ }
+
+ for (
+ current = certs;
+ current != NULL;
+ current = current->next
+ ) {
+ if (current->certificate_id->certificate_blob_size > 0) {
+ listCerts += Certificate::fromDER(
+ QByteArray(
+ (char *)current->certificate_id->certificate_blob,
+ current->certificate_id->certificate_blob_size
+ )
+ );
+ }
+ }
+
+ for (
+ current = issuers;
+ current != NULL;
+ current = current->next
+ ) {
+ if (current->certificate_id->certificate_blob_size > 0) {
+ listIssuers += Certificate::fromDER(
+ QByteArray(
+ (char *)current->certificate_id->certificate_blob,
+ current->certificate_id->certificate_blob_size
+ )
+ );
+ }
+ }
+
+ entry->registerCertificates(listIssuers + listCerts);
+ QMap<QString, QString> friendlyNames = entry->friendlyNames();
+
+ QList<Certificate> listIssuersForComplete;
+ if (dynamic_cast<pkcs11Provider *>(provider())->_allowLoadRootCA) {
+ listIssuersForComplete = listIssuers;
+ } else {
+ foreach (Certificate c, listIssuers) {
+ if (!c.isSelfSigned()) {
+ listIssuersForComplete += c;
+ }
+ }
+ }
+
+ for (
+ i = 0, current = issuers;
+ current != NULL;
+ i++, current = current->next
+ ) {
+ try {
+ if (listIssuers[i].isNull()) {
+ throw pkcs11Exception(CKR_ARGUMENTS_BAD, "Invalid certificate");
+ }
+
+ if (
+ listIssuers[i].isSelfSigned() &&
+ dynamic_cast<pkcs11Provider *>(provider())->_allowLoadRootCA
+ ) {
+ CertificateChain chain = CertificateChain(listIssuers[i]).complete(listIssuersForComplete);
+ out += _keyStoreEntryByCertificateId(
+ current->certificate_id,
+ false,
+ chain,
+ friendlyNames[certificateHash(chain.primary())]
+ );
+ }
+ } catch (const pkcs11Exception &e) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Add key store entry %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+ }
+
+ for (
+ i = 0, current = certs;
+ current != NULL;
+ i++, current = current->next
+ ) {
+ try {
+ if (listCerts[i].isNull()) {
+ throw pkcs11Exception(CKR_ARGUMENTS_BAD, "Invalid certificate");
+ }
+
+ CertificateChain chain = CertificateChain(listCerts[i]).complete(listIssuersForComplete);
+ out += _keyStoreEntryByCertificateId(
+ current->certificate_id,
+ true,
+ chain,
+ friendlyNames[certificateHash(chain.primary())]
+ );
+ } catch (const pkcs11Exception &e) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Add key store entry %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+ }
+ }
+ } catch (const pkcs11Exception &e) {
+ s_keyStoreList->_emit_diagnosticText(
+ QString().sprintf(
+ "PKCS#11: Enumerating store failed %lu-'%s'.\n",
+ e.rv(),
+ myPrintable(e.message())
+ )
+ );
+ }
+
+ if (certs != NULL) {
+ pkcs11h_certificate_freeCertificateIdList(certs);
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::entryList - return out.size()=%d",
+ out.size()
+ ),
+ Logger::Debug
+ );
+
+ return out;
}
bool
-pkcs11KeyStoreListContext::_tokenPrompt (
- void * const user_data,
- const pkcs11h_token_id_t token_id
-) {
- KeyStoreEntry entry;
- KeyStoreEntryContext *context = NULL;
- QString storeId, storeName;
- bool ret = false;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_tokenPrompt - entry user_data=%p, token_id=%p",
- user_data,
- (void *)token_id
- ),
- Logger::Debug
- );
-
- if (user_data != NULL) {
- QString *serialized = (QString *)user_data;
- context = entryPassive (*serialized);
- storeId = context->storeId ();
- storeName = context->storeName ();
- entry.change (context);
- }
- else {
- _registerTokenId (token_id);
- storeId = _tokenId2storeId (token_id);
- storeName = token_id->label;
- }
-
- TokenAsker asker;
- asker.ask (
- KeyStoreInfo (KeyStore::SmartCard, storeId, storeName),
- entry,
- context
- );
- asker.waitForResponse ();
- if (asker.accepted ()) {
- ret = true;
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_tokenPrompt - return ret=%d",
- ret ? 1 : 0
- ),
- Logger::Debug
- );
-
- return ret;
+pkcs11KeyStoreListContext::_tokenPrompt(
+ void *const user_data,
+ const pkcs11h_token_id_t token_id
+)
+{
+ KeyStoreEntry entry;
+ KeyStoreEntryContext *context = NULL;
+ QString storeId, storeName;
+ bool ret = false;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_tokenPrompt - entry user_data=%p, token_id=%p",
+ user_data,
+ (void *)token_id
+ ),
+ Logger::Debug
+ );
+
+ if (user_data != NULL) {
+ QString *serialized = (QString *)user_data;
+ context = entryPassive(*serialized);
+ storeId = context->storeId();
+ storeName = context->storeName();
+ entry.change(context);
+ } else {
+ _registerTokenId(token_id);
+ storeId = _tokenId2storeId(token_id);
+ storeName = token_id->label;
+ }
+
+ TokenAsker asker;
+ asker.ask(
+ KeyStoreInfo(KeyStore::SmartCard, storeId, storeName),
+ entry,
+ context
+ );
+ asker.waitForResponse();
+ if (asker.accepted()) {
+ ret = true;
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_tokenPrompt - return ret=%d",
+ ret ? 1 : 0
+ ),
+ Logger::Debug
+ );
+
+ return ret;
}
bool
-pkcs11KeyStoreListContext::_pinPrompt (
- void * const user_data,
- const pkcs11h_token_id_t token_id,
- SecureArray &pin
-) {
- KeyStoreEntry entry;
- KeyStoreEntryContext *context = NULL;
- QString storeId, storeName;
- bool ret = false;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_pinPrompt - entry user_data=%p, token_id=%p",
- user_data,
- (void *)token_id
- ),
- Logger::Debug
- );
-
- pin = SecureArray();
-
- if (user_data != NULL) {
- QString *serialized = (QString *)user_data;
- context = entryPassive (*serialized);
- storeId = context->storeId ();
- storeName = context->storeName ();
- entry.change (context);
- }
- else {
- _registerTokenId (token_id);
- storeId = _tokenId2storeId (token_id);
- storeName = token_id->label;
- }
-
- PasswordAsker asker;
- asker.ask (
- Event::StylePIN,
- KeyStoreInfo (KeyStore::SmartCard, storeId, storeName),
- entry,
- context
- );
- asker.waitForResponse ();
- if (asker.accepted ()) {
- ret = true;
- pin = asker.password ();
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_pinPrompt - return ret=%d",
- ret ? 1 : 0
- ),
- Logger::Debug
- );
-
- return ret;
+pkcs11KeyStoreListContext::_pinPrompt(
+ void *const user_data,
+ const pkcs11h_token_id_t token_id,
+ SecureArray &pin
+)
+{
+ KeyStoreEntry entry;
+ KeyStoreEntryContext *context = NULL;
+ QString storeId, storeName;
+ bool ret = false;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_pinPrompt - entry user_data=%p, token_id=%p",
+ user_data,
+ (void *)token_id
+ ),
+ Logger::Debug
+ );
+
+ pin = SecureArray();
+
+ if (user_data != NULL) {
+ QString *serialized = (QString *)user_data;
+ context = entryPassive(*serialized);
+ storeId = context->storeId();
+ storeName = context->storeName();
+ entry.change(context);
+ } else {
+ _registerTokenId(token_id);
+ storeId = _tokenId2storeId(token_id);
+ storeName = token_id->label;
+ }
+
+ PasswordAsker asker;
+ asker.ask(
+ Event::StylePIN,
+ KeyStoreInfo(KeyStore::SmartCard, storeId, storeName),
+ entry,
+ context
+ );
+ asker.waitForResponse();
+ if (asker.accepted()) {
+ ret = true;
+ pin = asker.password();
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_pinPrompt - return ret=%d",
+ ret ? 1 : 0
+ ),
+ Logger::Debug
+ );
+
+ return ret;
}
void
-pkcs11KeyStoreListContext::_emit_diagnosticText (
- const QString &t
-) {
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_emit_diagnosticText - entry t='%s'",
- myPrintable (t)
- ),
- Logger::Debug
- );
-
- QCA_logTextMessage (t, Logger::Warning);
-
- emit diagnosticText (t);
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::_emit_diagnosticText - return",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::_emit_diagnosticText(
+ const QString &t
+)
+{
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_emit_diagnosticText - entry t='%s'",
+ myPrintable(t)
+ ),
+ Logger::Debug
+ );
+
+ QCA_logTextMessage(t, Logger::Warning);
+
+ emit diagnosticText(t);
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::_emit_diagnosticText - return",
+ Logger::Debug
+ );
}
void
-pkcs11KeyStoreListContext::doReady () {
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::doReady - entry",
- Logger::Debug
- );
-
- emit busyEnd ();
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::doReady - return",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::doReady()
+{
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::doReady - entry",
+ Logger::Debug
+ );
+
+ emit busyEnd();
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::doReady - return",
+ Logger::Debug
+ );
}
void
-pkcs11KeyStoreListContext::doUpdated () {
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::doUpdated - entry",
- Logger::Debug
- );
-
- emit updated ();
-
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::doUpdated - return",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::doUpdated()
+{
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::doUpdated - entry",
+ Logger::Debug
+ );
+
+ emit updated();
+
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::doUpdated - return",
+ Logger::Debug
+ );
}
pkcs11KeyStoreListContext::pkcs11KeyStoreItem *
-pkcs11KeyStoreListContext::_registerTokenId (
- const pkcs11h_token_id_t token_id
-) {
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_registerTokenId - entry token_id=%p",
- (void *)token_id
- ),
- Logger::Debug
- );
-
- QMutexLocker l(&_mutexStores);
-
- _stores_t::iterator i=_stores.begin ();
-
- while (
- i != _stores.end () &&
- !pkcs11h_token_sameTokenId (
- token_id,
- (*i)->tokenId ()
- )
- ) {
- i++;
- }
-
- pkcs11KeyStoreItem *entry = NULL;
-
- if (i == _stores.end ()) {
- /*
- * Deal with last_id overlap
- */
- while (_storesById.find (++_last_id) != _storesById.end ());
-
- entry = new pkcs11KeyStoreItem (_last_id, token_id);
-
- _stores += entry;
- _storesById.insert (entry->id (), entry);
- }
- else {
- entry = (*i);
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_registerTokenId - return entry=%p",
- (void *)token_id
- ),
- Logger::Debug
- );
-
- return entry;
+pkcs11KeyStoreListContext::_registerTokenId(
+ const pkcs11h_token_id_t token_id
+)
+{
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_registerTokenId - entry token_id=%p",
+ (void *)token_id
+ ),
+ Logger::Debug
+ );
+
+ QMutexLocker l(&_mutexStores);
+
+ _stores_t::iterator i = _stores.begin();
+
+ while (
+ i != _stores.end() &&
+ !pkcs11h_token_sameTokenId(
+ token_id,
+ (*i)->tokenId()
+ )
+ ) {
+ i++;
+ }
+
+ pkcs11KeyStoreItem *entry = NULL;
+
+ if (i == _stores.end()) {
+ /*
+ * Deal with last_id overlap
+ */
+ while (_storesById.find(++_last_id) != _storesById.end());
+
+ entry = new pkcs11KeyStoreItem(_last_id, token_id);
+
+ _stores += entry;
+ _storesById.insert(entry->id(), entry);
+ } else {
+ entry = (*i);
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_registerTokenId - return entry=%p",
+ (void *)token_id
+ ),
+ Logger::Debug
+ );
+
+ return entry;
}
void
-pkcs11KeyStoreListContext::_clearStores () {
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::_clearStores - entry",
- Logger::Debug
- );
+pkcs11KeyStoreListContext::_clearStores()
+{
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::_clearStores - entry",
+ Logger::Debug
+ );
- QMutexLocker l(&_mutexStores);
+ QMutexLocker l(&_mutexStores);
- _storesById.clear ();
- foreach (pkcs11KeyStoreItem *i, _stores) {
- delete i;
- }
+ _storesById.clear();
+ foreach (pkcs11KeyStoreItem *i, _stores) {
+ delete i;
+ }
- _stores.clear ();
+ _stores.clear();
- QCA_logTextMessage (
- "pkcs11KeyStoreListContext::_clearStores - return",
- Logger::Debug
- );
+ QCA_logTextMessage(
+ "pkcs11KeyStoreListContext::_clearStores - return",
+ Logger::Debug
+ );
}
pkcs11KeyStoreEntryContext *
-pkcs11KeyStoreListContext::_keyStoreEntryByCertificateId (
- const pkcs11h_certificate_id_t certificate_id,
- const bool has_private,
- const CertificateChain &chain,
- const QString &_description
-) const {
- pkcs11KeyStoreEntryContext *entry = NULL;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_keyStoreEntryByCertificateId - entry certificate_id=%p, has_private=%d, chain.size()=%d",
- (void *)certificate_id,
- has_private ? 1 : 0,
- chain.size ()
- ),
- Logger::Debug
- );
-
- if (certificate_id == NULL) {
- throw pkcs11Exception (CKR_ARGUMENTS_BAD, "Missing certificate object");
- }
-
- QString serialized = _serializeCertificate (
- certificate_id,
- chain,
- has_private
- );
-
- QString description = _description;
- Certificate cert = chain.primary ();
- if (description.isEmpty ()) {
- description = cert.subjectInfoOrdered ().toString () + " by " + cert.issuerInfo ().value (CommonName, "Unknown");
- }
-
- if (has_private) {
- pkcs11RSAContext *rsakey = new pkcs11RSAContext (
- provider(),
- certificate_id,
- serialized,
- cert.subjectPublicKey ().toRSA ()
- );
-
- pkcs11PKeyContext *pkc = new pkcs11PKeyContext (provider ());
- pkc->setKey (rsakey);
- PrivateKey privkey;
- privkey.change (pkc);
- KeyBundle key;
- key.setCertificateChainAndKey (
- chain,
- privkey
- );
-
- entry = new pkcs11KeyStoreEntryContext (
- key,
- _tokenId2storeId (certificate_id->token_id),
- serialized,
- certificate_id->token_id->label,
- description,
- provider ()
- );
- }
- else {
- entry = new pkcs11KeyStoreEntryContext (
- cert,
- _tokenId2storeId (certificate_id->token_id),
- serialized,
- certificate_id->token_id->label,
- description,
- provider()
- );
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_keyStoreEntryByCertificateId - return entry=%p",
- (void *)entry
- ),
- Logger::Debug
- );
-
- return entry;
+pkcs11KeyStoreListContext::_keyStoreEntryByCertificateId(
+ const pkcs11h_certificate_id_t certificate_id,
+ const bool has_private,
+ const CertificateChain &chain,
+ const QString &_description
+) const
+{
+ pkcs11KeyStoreEntryContext *entry = NULL;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_keyStoreEntryByCertificateId - entry certificate_id=%p, has_private=%d, chain.size()=%d",
+ (void *)certificate_id,
+ has_private ? 1 : 0,
+ chain.size()
+ ),
+ Logger::Debug
+ );
+
+ if (certificate_id == NULL) {
+ throw pkcs11Exception(CKR_ARGUMENTS_BAD, "Missing certificate object");
+ }
+
+ QString serialized = _serializeCertificate(
+ certificate_id,
+ chain,
+ has_private
+ );
+
+ QString description = _description;
+ Certificate cert = chain.primary();
+ if (description.isEmpty()) {
+ description = cert.subjectInfoOrdered().toString() + " by " + cert.issuerInfo().value(CommonName, "Unknown");
+ }
+
+ if (has_private) {
+ pkcs11RSAContext *rsakey = new pkcs11RSAContext(
+ provider(),
+ certificate_id,
+ serialized,
+ cert.subjectPublicKey().toRSA()
+ );
+
+ pkcs11PKeyContext *pkc = new pkcs11PKeyContext(provider());
+ pkc->setKey(rsakey);
+ PrivateKey privkey;
+ privkey.change(pkc);
+ KeyBundle key;
+ key.setCertificateChainAndKey(
+ chain,
+ privkey
+ );
+
+ entry = new pkcs11KeyStoreEntryContext(
+ key,
+ _tokenId2storeId(certificate_id->token_id),
+ serialized,
+ certificate_id->token_id->label,
+ description,
+ provider()
+ );
+ } else {
+ entry = new pkcs11KeyStoreEntryContext(
+ cert,
+ _tokenId2storeId(certificate_id->token_id),
+ serialized,
+ certificate_id->token_id->label,
+ description,
+ provider()
+ );
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_keyStoreEntryByCertificateId - return entry=%p",
+ (void *)entry
+ ),
+ Logger::Debug
+ );
+
+ return entry;
}
QString
-pkcs11KeyStoreListContext::_tokenId2storeId (
- const pkcs11h_token_id_t token_id
-) const {
- QString storeId;
- size_t len;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_tokenId2storeId - entry token_id=%p",
- (void *)token_id
- ),
- Logger::Debug
- );
-
- if (
- pkcs11h_token_serializeTokenId (
- NULL,
- &len,
- token_id
- ) != CKR_OK
- ) {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Cannot serialize token id");
- }
-
- QByteArray buf;
- buf.resize ((int)len);
-
- if (
- pkcs11h_token_serializeTokenId (
- buf.data (),
- &len,
- token_id
- ) != CKR_OK
- ) {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Cannot serialize token id");
- }
-
- buf.resize ((int)len);
-
- storeId = "qca-pkcs11/" + _escapeString (QString::fromUtf8 (buf));
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_tokenId2storeId - return storeId='%s'",
- myPrintable (storeId)
- ),
- Logger::Debug
- );
-
- return storeId;
+pkcs11KeyStoreListContext::_tokenId2storeId(
+ const pkcs11h_token_id_t token_id
+) const
+{
+ QString storeId;
+ size_t len;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_tokenId2storeId - entry token_id=%p",
+ (void *)token_id
+ ),
+ Logger::Debug
+ );
+
+ if (
+ pkcs11h_token_serializeTokenId(
+ NULL,
+ &len,
+ token_id
+ ) != CKR_OK
+ ) {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Cannot serialize token id");
+ }
+
+ QByteArray buf;
+ buf.resize((int)len);
+
+ if (
+ pkcs11h_token_serializeTokenId(
+ buf.data(),
+ &len,
+ token_id
+ ) != CKR_OK
+ ) {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Cannot serialize token id");
+ }
+
+ buf.resize((int)len);
+
+ storeId = "qca-pkcs11/" + _escapeString(QString::fromUtf8(buf));
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_tokenId2storeId - return storeId='%s'",
+ myPrintable(storeId)
+ ),
+ Logger::Debug
+ );
+
+ return storeId;
}
QString
-pkcs11KeyStoreListContext::_serializeCertificate (
- const pkcs11h_certificate_id_t certificate_id,
- const CertificateChain &chain,
- const bool has_private
-) const {
- QString serialized;
- size_t len;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_serializeCertificate - entry certificate_id=%p, xx, has_private=%d",
- (void *)certificate_id,
- has_private ? 1 : 0
- ),
- Logger::Debug
- );
-
- if (
- pkcs11h_certificate_serializeCertificateId (
- NULL,
- &len,
- certificate_id
- ) != CKR_OK
- ) {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Cannot serialize certificate id");
- }
-
- QByteArray buf;
- buf.resize ((int)len);
-
- if (
- pkcs11h_certificate_serializeCertificateId (
- buf.data (),
- &len,
- certificate_id
- ) != CKR_OK
- ) {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Cannot serialize certificate id");
- }
-
- buf.resize ((int)len);
-
- serialized = QString ().sprintf (
- "qca-pkcs11/0/%s/%d/",
- myPrintable(_escapeString (QString::fromUtf8 (buf))),
- has_private ? 1 : 0
- );
-
- QStringList list;
- foreach (Certificate i, chain) {
- list += _escapeString (Base64 ().arrayToString (i.toDER ()));
- }
-
- serialized.append (list.join ("/"));
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_serializeCertificate - return serialized='%s'",
- myPrintable (serialized)
- ),
- Logger::Debug
- );
-
- return serialized;
+pkcs11KeyStoreListContext::_serializeCertificate(
+ const pkcs11h_certificate_id_t certificate_id,
+ const CertificateChain &chain,
+ const bool has_private
+) const
+{
+ QString serialized;
+ size_t len;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_serializeCertificate - entry certificate_id=%p, xx, has_private=%d",
+ (void *)certificate_id,
+ has_private ? 1 : 0
+ ),
+ Logger::Debug
+ );
+
+ if (
+ pkcs11h_certificate_serializeCertificateId(
+ NULL,
+ &len,
+ certificate_id
+ ) != CKR_OK
+ ) {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Cannot serialize certificate id");
+ }
+
+ QByteArray buf;
+ buf.resize((int)len);
+
+ if (
+ pkcs11h_certificate_serializeCertificateId(
+ buf.data(),
+ &len,
+ certificate_id
+ ) != CKR_OK
+ ) {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Cannot serialize certificate id");
+ }
+
+ buf.resize((int)len);
+
+ serialized = QString().sprintf(
+ "qca-pkcs11/0/%s/%d/",
+ myPrintable(_escapeString(QString::fromUtf8(buf))),
+ has_private ? 1 : 0
+ );
+
+ QStringList list;
+ foreach (Certificate i, chain) {
+ list += _escapeString(Base64().arrayToString(i.toDER()));
+ }
+
+ serialized.append(list.join("/"));
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_serializeCertificate - return serialized='%s'",
+ myPrintable(serialized)
+ ),
+ Logger::Debug
+ );
+
+ return serialized;
}
void
-pkcs11KeyStoreListContext::_deserializeCertificate (
- const QString &from,
- pkcs11h_certificate_id_t * const p_certificate_id,
- bool * const p_has_private,
- CertificateChain &chain
-) const {
- pkcs11h_certificate_id_t certificate_id = NULL;
- chain.clear ();
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_deserializeCertificate - entry from='%s', p_certificate_id=%p, p_has_private=%p",
- myPrintable (from),
- (void *)p_certificate_id,
- (void *)p_has_private
- ),
- Logger::Debug
- );
-
- try {
- int n = 0;
- CK_RV rv;
-
- *p_certificate_id = NULL;
- *p_has_private = false;
-
- QStringList list = from.split ("/");
-
- if (list.size () < 5) {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Invalid serialization");
- }
-
- if (list[n++] != "qca-pkcs11") {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Invalid serialization");
- }
-
- if (list[n++].toInt () != 0) {
- throw pkcs11Exception (CKR_FUNCTION_FAILED, "Invalid serialization version");
- }
-
- if (
- (rv = pkcs11h_certificate_deserializeCertificateId (
- &certificate_id,
- myPrintable (_unescapeString (list[n++]))
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Invalid serialization");
- }
-
- *p_has_private = list[n++].toInt () != 0;
-
- QByteArray endCertificateBytes = Base64 ().stringToArray (_unescapeString (list[n++])).toByteArray ();
- Certificate endCertificate = Certificate::fromDER (endCertificateBytes);
-
- if (endCertificate.isNull ()) {
- throw pkcs11Exception (rv, "Invalid certificate");
- }
-
- if (
- (rv = pkcs11h_certificate_setCertificateIdCertificateBlob (
- certificate_id,
- (unsigned char *)endCertificateBytes.data (),
- (size_t)endCertificateBytes.size ()
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Invalid serialization");
- }
-
- chain = endCertificate;
- while (n < list.size ()) {
- Certificate cert = Certificate::fromDER (
- Base64 ().stringToArray (_unescapeString (list[n++])).toByteArray ()
- );
- if (cert.isNull ()) {
- throw pkcs11Exception (rv, "Invalid certificate");
- }
- chain += cert;
- }
-
- *p_certificate_id = certificate_id;
- certificate_id = NULL;
- }
- catch (...) {
- if (certificate_id != NULL) {
- pkcs11h_certificate_freeCertificateId (certificate_id);
- certificate_id = NULL;
- }
- throw;
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11KeyStoreListContext::_deserializeCertificate - return *p_certificate_id=%p, chain.size()=%d",
- (void *)*p_certificate_id,
- chain.size ()
- ),
- Logger::Debug
- );
+pkcs11KeyStoreListContext::_deserializeCertificate(
+ const QString &from,
+ pkcs11h_certificate_id_t *const p_certificate_id,
+ bool *const p_has_private,
+ CertificateChain &chain
+) const
+{
+ pkcs11h_certificate_id_t certificate_id = NULL;
+ chain.clear();
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_deserializeCertificate - entry from='%s', p_certificate_id=%p, p_has_private=%p",
+ myPrintable(from),
+ (void *)p_certificate_id,
+ (void *)p_has_private
+ ),
+ Logger::Debug
+ );
+
+ try {
+ int n = 0;
+ CK_RV rv;
+
+ *p_certificate_id = NULL;
+ *p_has_private = false;
+
+ QStringList list = from.split("/");
+
+ if (list.size() < 5) {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Invalid serialization");
+ }
+
+ if (list[n++] != "qca-pkcs11") {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Invalid serialization");
+ }
+
+ if (list[n++].toInt() != 0) {
+ throw pkcs11Exception(CKR_FUNCTION_FAILED, "Invalid serialization version");
+ }
+
+ if (
+ (rv = pkcs11h_certificate_deserializeCertificateId(
+ &certificate_id,
+ myPrintable(_unescapeString(list[n++]))
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Invalid serialization");
+ }
+
+ *p_has_private = list[n++].toInt() != 0;
+
+ QByteArray endCertificateBytes = Base64().stringToArray(_unescapeString(list[n++])).toByteArray();
+ Certificate endCertificate = Certificate::fromDER(endCertificateBytes);
+
+ if (endCertificate.isNull()) {
+ throw pkcs11Exception(rv, "Invalid certificate");
+ }
+
+ if (
+ (rv = pkcs11h_certificate_setCertificateIdCertificateBlob(
+ certificate_id,
+ (unsigned char *)endCertificateBytes.data(),
+ (size_t)endCertificateBytes.size()
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Invalid serialization");
+ }
+
+ chain = endCertificate;
+ while (n < list.size()) {
+ Certificate cert = Certificate::fromDER(
+ Base64().stringToArray(_unescapeString(list[n++])).toByteArray()
+ );
+ if (cert.isNull()) {
+ throw pkcs11Exception(rv, "Invalid certificate");
+ }
+ chain += cert;
+ }
+
+ *p_certificate_id = certificate_id;
+ certificate_id = NULL;
+ } catch (...) {
+ if (certificate_id != NULL) {
+ pkcs11h_certificate_freeCertificateId(certificate_id);
+ certificate_id = NULL;
+ }
+ throw;
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11KeyStoreListContext::_deserializeCertificate - return *p_certificate_id=%p, chain.size()=%d",
+ (void *)*p_certificate_id,
+ chain.size()
+ ),
+ Logger::Debug
+ );
}
QString
-pkcs11KeyStoreListContext::_escapeString (
- const QString &from
-) const {
- QString to;
-
- foreach (QChar c, from) {
- if (c == '/' || c == '\\') {
- to += QString ().sprintf ("\\x%04x", c.unicode ());
- }
- else {
- to += c;
- }
- }
-
- return to;
+pkcs11KeyStoreListContext::_escapeString(
+ const QString &from
+) const
+{
+ QString to;
+
+ foreach (QChar c, from) {
+ if (c == '/' || c == '\\') {
+ to += QString().sprintf("\\x%04x", c.unicode());
+ } else {
+ to += c;
+ }
+ }
+
+ return to;
}
QString
-pkcs11KeyStoreListContext::_unescapeString (
- const QString &from
-) const {
- QString to;
-
- for (int i=0;i<from.size ();i++) {
- QChar c = from[i];
-
- if (c == '\\') {
- to += QChar ((ushort)from.mid (i+2, 4).toInt (0, 16));
- i+=5;
- }
- else {
- to += c;
- }
- }
-
- return to;
+pkcs11KeyStoreListContext::_unescapeString(
+ const QString &from
+) const
+{
+ QString to;
+
+ for (int i = 0; i < from.size(); i++) {
+ QChar c = from[i];
+
+ if (c == '\\') {
+ to += QChar((ushort)from.mid(i + 2, 4).toInt(0, 16));
+ i += 5;
+ } else {
+ to += c;
+ }
+ }
+
+ return to;
}
}
using namespace pkcs11QCAPlugin;
const int pkcs11Provider::_CONFIG_MAX_PROVIDERS = 10;
//----------------------------------------------------------------------------
// pkcs11Provider
//----------------------------------------------------------------------------
-pkcs11Provider::pkcs11Provider () {
-
- QCA_logTextMessage (
- "pkcs11Provider::pkcs11Provider - entry",
- Logger::Debug
- );
-
- _lowLevelInitialized = false;
- _slotEventsActive = false;
- _slotEventsLowLevelActive = false;
- _allowLoadRootCA = false;
-
- QCA_logTextMessage (
- "pkcs11Provider::pkcs11Provider - return",
- Logger::Debug
- );
+pkcs11Provider::pkcs11Provider()
+{
+
+ QCA_logTextMessage(
+ "pkcs11Provider::pkcs11Provider - entry",
+ Logger::Debug
+ );
+
+ _lowLevelInitialized = false;
+ _slotEventsActive = false;
+ _slotEventsLowLevelActive = false;
+ _allowLoadRootCA = false;
+
+ QCA_logTextMessage(
+ "pkcs11Provider::pkcs11Provider - return",
+ Logger::Debug
+ );
}
-pkcs11Provider::~pkcs11Provider () {
- QCA_logTextMessage (
- "pkcs11Provider::~pkcs11Provider - entry/return",
- Logger::Debug
- );
+pkcs11Provider::~pkcs11Provider()
+{
+ QCA_logTextMessage(
+ "pkcs11Provider::~pkcs11Provider - entry/return",
+ Logger::Debug
+ );
}
int pkcs11Provider::qcaVersion() const
{
- QCA_logTextMessage (
- "pkcs11Provider::qcaVersion - entry/return",
- Logger::Debug
- );
+ QCA_logTextMessage(
+ "pkcs11Provider::qcaVersion - entry/return",
+ Logger::Debug
+ );
- return QCA_VERSION;
+ return QCA_VERSION;
}
-void pkcs11Provider::init () {
- QCA_logTextMessage (
- "pkcs11Provider::init - entry",
- Logger::Debug
- );
-
- try {
- CK_RV rv;
-
- if ((rv = pkcs11h_engine_setCrypto (&pkcs11QCACrypto::crypto)) != CKR_OK) {
- throw pkcs11Exception (rv, "Cannot set crypto");
- }
-
- if ((rv = pkcs11h_initialize ()) != CKR_OK) {
- throw pkcs11Exception (rv, "Cannot initialize");
- }
-
- if (
- (rv = pkcs11h_setLogHook (
- __logHook,
- this
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot set hook");
- }
-
- pkcs11h_setLogLevel (0);
-
- if (
- (rv = pkcs11h_setTokenPromptHook (
- __tokenPromptHook,
- this
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot set hook");
- }
-
- if (
- (rv = pkcs11h_setPINPromptHook (
- __pinPromptHook,
- this
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot set hook");
- }
-
- _lowLevelInitialized = true;
- }
- catch (const pkcs11Exception &e) {
- QCA_logTextMessage (e.message (), Logger::Error);
- appendPluginDiagnosticText (
- QString().sprintf (
- "An error %s during initialization of qca-pkcs11 plugin\n",
- myPrintable (e.message ())
- )
- );
- }
- catch (...) {
- QCA_logTextMessage ("PKCS#11: Unknown error during provider initialization", Logger::Error);
- appendPluginDiagnosticText ("Unknown error during initialization of qca-pkcs11 plugin\n");
- }
-
- QCA_logTextMessage (
- "pkcs11Provider::init - return",
- Logger::Debug
- );
+void pkcs11Provider::init()
+{
+ QCA_logTextMessage(
+ "pkcs11Provider::init - entry",
+ Logger::Debug
+ );
+
+ try {
+ CK_RV rv;
+
+ if ((rv = pkcs11h_engine_setCrypto(&pkcs11QCACrypto::crypto)) != CKR_OK) {
+ throw pkcs11Exception(rv, "Cannot set crypto");
+ }
+
+ if ((rv = pkcs11h_initialize()) != CKR_OK) {
+ throw pkcs11Exception(rv, "Cannot initialize");
+ }
+
+ if (
+ (rv = pkcs11h_setLogHook(
+ __logHook,
+ this
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot set hook");
+ }
+
+ pkcs11h_setLogLevel(0);
+
+ if (
+ (rv = pkcs11h_setTokenPromptHook(
+ __tokenPromptHook,
+ this
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot set hook");
+ }
+
+ if (
+ (rv = pkcs11h_setPINPromptHook(
+ __pinPromptHook,
+ this
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot set hook");
+ }
+
+ _lowLevelInitialized = true;
+ } catch (const pkcs11Exception &e) {
+ QCA_logTextMessage(e.message(), Logger::Error);
+ appendPluginDiagnosticText(
+ QString().sprintf(
+ "An error %s during initialization of qca-pkcs11 plugin\n",
+ myPrintable(e.message())
+ )
+ );
+ } catch (...) {
+ QCA_logTextMessage("PKCS#11: Unknown error during provider initialization", Logger::Error);
+ appendPluginDiagnosticText("Unknown error during initialization of qca-pkcs11 plugin\n");
+ }
+
+ QCA_logTextMessage(
+ "pkcs11Provider::init - return",
+ Logger::Debug
+ );
}
-void pkcs11Provider::deinit () {
- QCA_logTextMessage (
- "pkcs11Provider::deinit - entry",
- Logger::Debug
- );
+void pkcs11Provider::deinit()
+{
+ QCA_logTextMessage(
+ "pkcs11Provider::deinit - entry",
+ Logger::Debug
+ );
- delete s_keyStoreList;
- s_keyStoreList = NULL;
+ delete s_keyStoreList;
+ s_keyStoreList = NULL;
- pkcs11h_terminate ();
+ pkcs11h_terminate();
- QCA_logTextMessage (
- "pkcs11Provider::deinit - return",
- Logger::Debug
- );
+ QCA_logTextMessage(
+ "pkcs11Provider::deinit - return",
+ Logger::Debug
+ );
}
QString
-pkcs11Provider::name () const {
- QCA_logTextMessage (
- "pkcs11Provider::name - entry/return",
- Logger::Debug
- );
+pkcs11Provider::name() const
+{
+ QCA_logTextMessage(
+ "pkcs11Provider::name - entry/return",
+ Logger::Debug
+ );
- return "qca-pkcs11";
+ return "qca-pkcs11";
}
QStringList
-pkcs11Provider::features() const {
- QCA_logTextMessage (
- "pkcs11Provider::features - entry/return",
- Logger::Debug
- );
-
- QStringList list;
- list += "smartcard"; // indicator, not algorithm
- list += "pkey";
- list += "keystorelist";
- return list;
+pkcs11Provider::features() const
+{
+ QCA_logTextMessage(
+ "pkcs11Provider::features - entry/return",
+ Logger::Debug
+ );
+
+ QStringList list;
+ list += "smartcard"; // indicator, not algorithm
+ list += "pkey";
+ list += "keystorelist";
+ return list;
}
Provider::Context *
-pkcs11Provider::createContext (const QString &type) {
-
- Provider::Context *context = NULL;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11Provider::createContext - entry type='%s'",
- myPrintable (type)
- ),
- Logger::Debug
- );
-
- if (_lowLevelInitialized) {
- if (type == "keystorelist") {
- if (s_keyStoreList == NULL) {
- s_keyStoreList = new pkcs11KeyStoreListContext (this);
- }
- context = s_keyStoreList;
- }
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "pkcs11Provider::createContext - return context=%p",
- (void *)context
- ),
- Logger::Debug
- );
-
- return context;
+pkcs11Provider::createContext(const QString &type)
+{
+
+ Provider::Context *context = NULL;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11Provider::createContext - entry type='%s'",
+ myPrintable(type)
+ ),
+ Logger::Debug
+ );
+
+ if (_lowLevelInitialized) {
+ if (type == "keystorelist") {
+ if (s_keyStoreList == NULL) {
+ s_keyStoreList = new pkcs11KeyStoreListContext(this);
+ }
+ context = s_keyStoreList;
+ }
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "pkcs11Provider::createContext - return context=%p",
+ (void *)context
+ ),
+ Logger::Debug
+ );
+
+ return context;
}
void
-pkcs11Provider::startSlotEvents () {
- CK_RV rv;
-
- QCA_logTextMessage (
- "pkcs11Provider::startSlotEvents - entry",
- Logger::Debug
- );
-
- if (_lowLevelInitialized) {
- if (!_slotEventsLowLevelActive) {
- if (
- (rv = pkcs11h_setSlotEventHook (
- __slotEventHook,
- this
- )) != CKR_OK
- ) {
- throw pkcs11Exception (rv, "Cannot start slot events");
- }
-
- _slotEventsLowLevelActive = true;
- }
-
- _slotEventsActive = true;
- }
-
- QCA_logTextMessage (
- "pkcs11Provider::startSlotEvents - return",
- Logger::Debug
- );
+pkcs11Provider::startSlotEvents()
+{
+ CK_RV rv;
+
+ QCA_logTextMessage(
+ "pkcs11Provider::startSlotEvents - entry",
+ Logger::Debug
+ );
+
+ if (_lowLevelInitialized) {
+ if (!_slotEventsLowLevelActive) {
+ if (
+ (rv = pkcs11h_setSlotEventHook(
+ __slotEventHook,
+ this
+ )) != CKR_OK
+ ) {
+ throw pkcs11Exception(rv, "Cannot start slot events");
+ }
+
+ _slotEventsLowLevelActive = true;
+ }
+
+ _slotEventsActive = true;
+ }
+
+ QCA_logTextMessage(
+ "pkcs11Provider::startSlotEvents - return",
+ Logger::Debug
+ );
}
void
-pkcs11Provider::stopSlotEvents () {
- QCA_logTextMessage (
- "pkcs11Provider::stopSlotEvents - entry/return",
- Logger::Debug
- );
+pkcs11Provider::stopSlotEvents()
+{
+ QCA_logTextMessage(
+ "pkcs11Provider::stopSlotEvents - entry/return",
+ Logger::Debug
+ );
- _slotEventsActive = false;
+ _slotEventsActive = false;
}
QVariantMap
-pkcs11Provider::defaultConfig () const {
- QVariantMap mytemplate;
-
- QCA_logTextMessage (
- "pkcs11Provider::defaultConfig - entry/return",
- Logger::Debug
- );
-
- mytemplate["formtype"] = "http://affinix.com/qca/forms/qca-pkcs11#1.0";
- mytemplate["allow_load_rootca"] = false;
- mytemplate["allow_protected_authentication"] = true;
- mytemplate["pin_cache"] = PKCS11H_PIN_CACHE_INFINITE;
- mytemplate["log_level"] = 0;
- for (int i=0;i<_CONFIG_MAX_PROVIDERS;i++) {
- mytemplate[QString ().sprintf ("provider_%02d_enabled", i)] = false;
- mytemplate[QString ().sprintf ("provider_%02d_name", i)] = "";
- mytemplate[QString ().sprintf ("provider_%02d_library", i)] = "";
- mytemplate[QString ().sprintf ("provider_%02d_allow_protected_authentication", i)] = true;
- mytemplate[QString ().sprintf ("provider_%02d_cert_private", i)] = false;
- mytemplate[QString ().sprintf ("provider_%02d_private_mask", i)] = PKCS11H_PRIVATEMODE_MASK_AUTO;
- mytemplate[QString ().sprintf ("provider_%02d_slotevent_method", i)] = "auto";
- mytemplate[QString ().sprintf ("provider_%02d_slotevent_timeout", i)] = 0;
- }
-
- return mytemplate;
+pkcs11Provider::defaultConfig() const
+{
+ QVariantMap mytemplate;
+
+ QCA_logTextMessage(
+ "pkcs11Provider::defaultConfig - entry/return",
+ Logger::Debug
+ );
+
+ mytemplate["formtype"] = "http://affinix.com/qca/forms/qca-pkcs11#1.0";
+ mytemplate["allow_load_rootca"] = false;
+ mytemplate["allow_protected_authentication"] = true;
+ mytemplate["pin_cache"] = PKCS11H_PIN_CACHE_INFINITE;
+ mytemplate["log_level"] = 0;
+ for (int i = 0; i < _CONFIG_MAX_PROVIDERS; i++) {
+ mytemplate[QString().sprintf("provider_%02d_enabled", i)] = false;
+ mytemplate[QString().sprintf("provider_%02d_name", i)] = "";
+ mytemplate[QString().sprintf("provider_%02d_library", i)] = "";
+ mytemplate[QString().sprintf("provider_%02d_allow_protected_authentication", i)] = true;
+ mytemplate[QString().sprintf("provider_%02d_cert_private", i)] = false;
+ mytemplate[QString().sprintf("provider_%02d_private_mask", i)] = PKCS11H_PRIVATEMODE_MASK_AUTO;
+ mytemplate[QString().sprintf("provider_%02d_slotevent_method", i)] = "auto";
+ mytemplate[QString().sprintf("provider_%02d_slotevent_timeout", i)] = 0;
+ }
+
+ return mytemplate;
}
void
-pkcs11Provider::configChanged (const QVariantMap &config) {
- CK_RV rv = CKR_OK;
-
- QCA_logTextMessage (
- "pkcs11Provider::configChanged - entry",
- Logger::Debug
- );
-
- if (!_lowLevelInitialized) {
- QCA_logTextMessage ("PKCS#11: Not initialized", Logger::Error);
- return;
- }
-
- _allowLoadRootCA = config["allow_load_rootca"].toBool ();
-
- pkcs11h_setLogLevel (config["log_level"].toInt ());
- pkcs11h_setProtectedAuthentication (
- config["allow_protected_authentication"].toBool () != false ? TRUE : FALSE //krazy:exclude=captruefalse
- );
- pkcs11h_setPINCachePeriod (config["pin_cache"].toInt ());
-
- /*
- * Remove current providers
- */
- foreach (QString i, _providers) {
- pkcs11h_removeProvider (myPrintable (i));
- }
- _providers.clear ();
-
- /*
- * Add new providers
- */
- for (int i=0;i<_CONFIG_MAX_PROVIDERS;i++) {
- bool enabled = config[QString ().sprintf ("provider_%02d_enabled", i)].toBool ();
- QString provider = config[QString ().sprintf ("provider_%02d_library", i)].toString ();
- QString name = config[QString ().sprintf ("provider_%02d_name", i)].toString ();
- QString qslotevent = config[QString ().sprintf ("provider_%02d_slotevent_method", i)].toString ();
- unsigned slotevent = PKCS11H_SLOTEVENT_METHOD_AUTO;
- if (qslotevent == "trigger") {
- slotevent = PKCS11H_SLOTEVENT_METHOD_TRIGGER;
- }
- else if (qslotevent == "poll") {
- slotevent = PKCS11H_SLOTEVENT_METHOD_POLL;
- }
-
- if (name.isEmpty ()) {
- name = provider;
- }
-
- if (enabled && !provider.isEmpty()) {
-
- QCA_logTextMessage (
- QString ().sprintf (
- "Loading PKCS#11 provider '%s' (%s)",
- myPrintable (name),
- myPrintable (provider)
- ),
- Logger::Information
- );
-
- if (
- (rv = pkcs11h_addProvider (
- myPrintable (name),
- myPrintable (provider),
- config[
- QString ().sprintf ("provider_%02d_allow_protected_authentication", i)
- ].toBool () != false ? TRUE : FALSE, //krazy:exclude=captruefalse
- (unsigned)config[
- QString ().sprintf ("provider_%02d_private_mask", i)
- ].toInt (),
- slotevent,
- (unsigned)config[
- QString ().sprintf ("provider_%02d_slotevent_timeout", i)
- ].toInt (),
- config[
- QString ().sprintf ("provider_%02d_cert_private", i)
- ].toBool () != false ? TRUE : FALSE //krazy:exclude=captruefalse
- )) != CKR_OK
- ) {
- QCA_logTextMessage (
- QString ().sprintf (
- "PKCS#11: Cannot log provider '%s'-'%s' %lu-'%s'.\n",
- myPrintable (name),
- myPrintable (provider),
- rv,
- pkcs11h_getMessage (rv)
- ),
- Logger::Error
- );
- appendPluginDiagnosticText (
- QString ().sprintf (
- "Cannot load PKCS#11 provider '%s'\n",
- myPrintable (name)
- )
- );
- }
- else {
- _providers += provider;
- }
- }
- }
-
- QCA_logTextMessage (
- "pkcs11Provider::configChanged - return",
- Logger::Debug
- );
+pkcs11Provider::configChanged(const QVariantMap &config)
+{
+ CK_RV rv = CKR_OK;
+
+ QCA_logTextMessage(
+ "pkcs11Provider::configChanged - entry",
+ Logger::Debug
+ );
+
+ if (!_lowLevelInitialized) {
+ QCA_logTextMessage("PKCS#11: Not initialized", Logger::Error);
+ return;
+ }
+
+ _allowLoadRootCA = config["allow_load_rootca"].toBool();
+
+ pkcs11h_setLogLevel(config["log_level"].toInt());
+ pkcs11h_setProtectedAuthentication(
+ config["allow_protected_authentication"].toBool() != false ? TRUE : FALSE //krazy:exclude=captruefalse
+ );
+ pkcs11h_setPINCachePeriod(config["pin_cache"].toInt());
+
+ /*
+ * Remove current providers
+ */
+ foreach (QString i, _providers) {
+ pkcs11h_removeProvider(myPrintable(i));
+ }
+ _providers.clear();
+
+ /*
+ * Add new providers
+ */
+ for (int i = 0; i < _CONFIG_MAX_PROVIDERS; i++) {
+ bool enabled = config[QString().sprintf("provider_%02d_enabled", i)].toBool();
+ QString provider = config[QString().sprintf("provider_%02d_library", i)].toString();
+ QString name = config[QString().sprintf("provider_%02d_name", i)].toString();
+ QString qslotevent = config[QString().sprintf("provider_%02d_slotevent_method", i)].toString();
+ unsigned slotevent = PKCS11H_SLOTEVENT_METHOD_AUTO;
+ if (qslotevent == "trigger") {
+ slotevent = PKCS11H_SLOTEVENT_METHOD_TRIGGER;
+ } else if (qslotevent == "poll") {
+ slotevent = PKCS11H_SLOTEVENT_METHOD_POLL;
+ }
+
+ if (name.isEmpty()) {
+ name = provider;
+ }
+
+ if (enabled && !provider.isEmpty()) {
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "Loading PKCS#11 provider '%s' (%s)",
+ myPrintable(name),
+ myPrintable(provider)
+ ),
+ Logger::Information
+ );
+
+ if (
+ (rv = pkcs11h_addProvider(
+ myPrintable(name),
+ myPrintable(provider),
+ config[
+ QString().sprintf("provider_%02d_allow_protected_authentication", i)
+ ].toBool() != false ? TRUE : FALSE, //krazy:exclude=captruefalse
+ (unsigned)config[
+ QString().sprintf("provider_%02d_private_mask", i)
+ ].toInt(),
+ slotevent,
+ (unsigned)config[
+ QString().sprintf("provider_%02d_slotevent_timeout", i)
+ ].toInt(),
+ config[
+ QString().sprintf("provider_%02d_cert_private", i)
+ ].toBool() != false ? TRUE : FALSE //krazy:exclude=captruefalse
+ )) != CKR_OK
+ ) {
+ QCA_logTextMessage(
+ QString().sprintf(
+ "PKCS#11: Cannot log provider '%s'-'%s' %lu-'%s'.\n",
+ myPrintable(name),
+ myPrintable(provider),
+ rv,
+ pkcs11h_getMessage(rv)
+ ),
+ Logger::Error
+ );
+ appendPluginDiagnosticText(
+ QString().sprintf(
+ "Cannot load PKCS#11 provider '%s'\n",
+ myPrintable(name)
+ )
+ );
+ } else {
+ _providers += provider;
+ }
+ }
+ }
+
+ QCA_logTextMessage(
+ "pkcs11Provider::configChanged - return",
+ Logger::Debug
+ );
}
void
-pkcs11Provider::__logHook (
- void * const global_data,
- const unsigned flags,
- const char * const format,
- va_list args
-) {
- pkcs11Provider *me = (pkcs11Provider *)global_data;
- me->_logHook (flags, format, args);
+pkcs11Provider::__logHook(
+ void *const global_data,
+ const unsigned flags,
+ const char *const format,
+ va_list args
+)
+{
+ pkcs11Provider *me = (pkcs11Provider *)global_data;
+ me->_logHook(flags, format, args);
}
void
-pkcs11Provider::__slotEventHook (
- void * const global_data
-) {
- pkcs11Provider *me = (pkcs11Provider *)global_data;
- me->_slotEventHook ();
+pkcs11Provider::__slotEventHook(
+ void *const global_data
+)
+{
+ pkcs11Provider *me = (pkcs11Provider *)global_data;
+ me->_slotEventHook();
}
PKCS11H_BOOL
-pkcs11Provider::__tokenPromptHook (
- void * const global_data,
- void * const user_data,
- const pkcs11h_token_id_t token,
- const unsigned retry
-) {
- Q_UNUSED(retry);
-
- pkcs11Provider *me = (pkcs11Provider *)global_data;
- return me->_tokenPromptHook (user_data, token);
+pkcs11Provider::__tokenPromptHook(
+ void *const global_data,
+ void *const user_data,
+ const pkcs11h_token_id_t token,
+ const unsigned retry
+)
+{
+ Q_UNUSED(retry);
+
+ pkcs11Provider *me = (pkcs11Provider *)global_data;
+ return me->_tokenPromptHook(user_data, token);
}
PKCS11H_BOOL
-pkcs11Provider::__pinPromptHook (
- void * const global_data,
- void * const user_data,
- const pkcs11h_token_id_t token,
- const unsigned retry,
- char * const pin,
- const size_t pin_max
-) {
- Q_UNUSED(retry);
-
- pkcs11Provider *me = (pkcs11Provider *)global_data;
- return me->_pinPromptHook (user_data, token, pin, pin_max);
+pkcs11Provider::__pinPromptHook(
+ void *const global_data,
+ void *const user_data,
+ const pkcs11h_token_id_t token,
+ const unsigned retry,
+ char *const pin,
+ const size_t pin_max
+)
+{
+ Q_UNUSED(retry);
+
+ pkcs11Provider *me = (pkcs11Provider *)global_data;
+ return me->_pinPromptHook(user_data, token, pin, pin_max);
}
void
-pkcs11Provider::_logHook (
- const unsigned flags,
- const char * const format,
- va_list args
-) {
- Logger::Severity severity;
-
- switch (flags) {
- case PKCS11H_LOG_DEBUG2:
- case PKCS11H_LOG_DEBUG1:
- severity = Logger::Debug;
- break;
- case PKCS11H_LOG_INFO:
- severity = Logger::Information;
- break;
- case PKCS11H_LOG_WARN:
- severity = Logger::Warning;
- break;
- case PKCS11H_LOG_ERROR:
- severity = Logger::Error;
- break;
- default:
- severity = Logger::Debug;
- break;
- }
-
+pkcs11Provider::_logHook(
+ const unsigned flags,
+ const char *const format,
+ va_list args
+)
+{
+ Logger::Severity severity;
+
+ switch (flags) {
+ case PKCS11H_LOG_DEBUG2:
+ case PKCS11H_LOG_DEBUG1:
+ severity = Logger::Debug;
+ break;
+ case PKCS11H_LOG_INFO:
+ severity = Logger::Information;
+ break;
+ case PKCS11H_LOG_WARN:
+ severity = Logger::Warning;
+ break;
+ case PKCS11H_LOG_ERROR:
+ severity = Logger::Error;
+ break;
+ default:
+ severity = Logger::Debug;
+ break;
+ }
//@BEGIN-WORKAROUND
// Qt vsprintf cannot can NULL for %s as vsprintf does.
-// QCA_logTextMessage (QString ().vsprintf (format, args), severity);
- char buffer[2048];
- qvsnprintf (buffer, sizeof (buffer)-1, format, args);
- buffer[sizeof (buffer)-1] = '\x0';
- QCA_logTextMessage (buffer, severity);
+// QCA_logTextMessage (QString ().vsprintf (format, args), severity);
+ char buffer[2048];
+ qvsnprintf(buffer, sizeof(buffer) - 1, format, args);
+ buffer[sizeof(buffer) - 1] = '\x0';
+ QCA_logTextMessage(buffer, severity);
//@END-WORKAROUND
}
void
-pkcs11Provider::_slotEventHook () {
- /*
- * This is called from a separate
- * thread.
- */
- if (s_keyStoreList != NULL && _slotEventsActive) {
- QMetaObject::invokeMethod(s_keyStoreList, "doUpdated", Qt::QueuedConnection);
- }
+pkcs11Provider::_slotEventHook()
+{
+ /*
+ * This is called from a separate
+ * thread.
+ */
+ if (s_keyStoreList != NULL && _slotEventsActive) {
+ QMetaObject::invokeMethod(s_keyStoreList, "doUpdated", Qt::QueuedConnection);
+ }
}
PKCS11H_BOOL
-pkcs11Provider::_tokenPromptHook (
- void * const user_data,
- const pkcs11h_token_id_t token
-) {
- if (s_keyStoreList != NULL) {
- return s_keyStoreList->_tokenPrompt (user_data, token) ? TRUE : FALSE; //krazy:exclude=captruefalse
- }
-
- return FALSE; //krazy:exclude=captruefalse
+pkcs11Provider::_tokenPromptHook(
+ void *const user_data,
+ const pkcs11h_token_id_t token
+)
+{
+ if (s_keyStoreList != NULL) {
+ return s_keyStoreList->_tokenPrompt(user_data, token) ? TRUE : FALSE; //krazy:exclude=captruefalse
+ }
+
+ return FALSE; //krazy:exclude=captruefalse
}
PKCS11H_BOOL
-pkcs11Provider::_pinPromptHook (
- void * const user_data,
- const pkcs11h_token_id_t token,
- char * const pin,
- const size_t pin_max
-) {
- PKCS11H_BOOL ret = FALSE; //krazy:exclude=captruefalse
-
- if (s_keyStoreList != NULL) {
- SecureArray qpin;
-
- if (s_keyStoreList->_pinPrompt (user_data, token, qpin)) {
- if ((size_t)qpin.size () < pin_max-1) {
- memmove (pin, qpin.constData (), qpin.size ());
- pin[qpin.size ()] = '\0';
- ret = TRUE; //krazy:exclude=captruefalse
- }
- }
- }
-
- return ret; //krazy:exclude=captruefalse
+pkcs11Provider::_pinPromptHook(
+ void *const user_data,
+ const pkcs11h_token_id_t token,
+ char *const pin,
+ const size_t pin_max
+)
+{
+ PKCS11H_BOOL ret = FALSE; //krazy:exclude=captruefalse
+
+ if (s_keyStoreList != NULL) {
+ SecureArray qpin;
+
+ if (s_keyStoreList->_pinPrompt(user_data, token, qpin)) {
+ if ((size_t)qpin.size() < pin_max - 1) {
+ memmove(pin, qpin.constData(), qpin.size());
+ pin[qpin.size()] = '\0';
+ ret = TRUE; //krazy:exclude=captruefalse
+ }
+ }
+ }
+
+ return ret; //krazy:exclude=captruefalse
}
class pkcs11Plugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { return new pkcs11Provider; }
+ virtual Provider *createProvider()
+ {
+ return new pkcs11Provider;
+ }
};
#include "qca-pkcs11.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_pkcs11, pkcs11Plugin)
#endif
diff --git a/plugins/qca-softstore/qca-softstore.cpp b/plugins/qca-softstore/qca-softstore.cpp
index 1d119830..7b4854f3 100644
--- a/plugins/qca-softstore/qca-softstore.cpp
+++ b/plugins/qca-softstore/qca-softstore.cpp
@@ -1,1519 +1,1597 @@
/*
* Copyright (C) 2007 Alon Bar-Lev <alon.barlev@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <QtPlugin>
#include <QHash>
#include <QFile>
using namespace QCA;
// qPrintable is ASCII only!!!
#define myPrintable(s) (s).toUtf8 ().constData ()
-namespace softstoreQCAPlugin {
+namespace softstoreQCAPlugin
+{
class softstoreKeyStoreListContext;
static softstoreKeyStoreListContext *s_keyStoreList = NULL;
enum KeyType {
- keyTypeInvalid,
- keyTypePKCS12,
- keyTypePKCS8Inline,
- keyTypePKCS8FilePEM,
- keyTypePKCS8FileDER
+ keyTypeInvalid,
+ keyTypePKCS12,
+ keyTypePKCS8Inline,
+ keyTypePKCS8FilePEM,
+ keyTypePKCS8FileDER
};
enum PublicType {
- publicTypeInvalid,
- publicTypeX509Chain
+ publicTypeInvalid,
+ publicTypeX509Chain
};
struct SoftStoreEntry {
- QString name;
- CertificateChain chain;
- KeyType keyReferenceType;
- QString keyReference;
- bool noPassphrase;
- int unlockTimeout;
+ QString name;
+ CertificateChain chain;
+ KeyType keyReferenceType;
+ QString keyReference;
+ bool noPassphrase;
+ int unlockTimeout;
};
class softstorePKeyBase : public PKeyBase
{
- Q_OBJECT
+ Q_OBJECT
private:
- bool _has_privateKeyRole;
- SoftStoreEntry _entry;
- QString _serialized;
- PrivateKey _privkey;
- PrivateKey _privkeySign;
- PublicKey _pubkey;
- QDateTime dueTime;
+ bool _has_privateKeyRole;
+ SoftStoreEntry _entry;
+ QString _serialized;
+ PrivateKey _privkey;
+ PrivateKey _privkeySign;
+ PublicKey _pubkey;
+ QDateTime dueTime;
public:
- static inline QString typeToString (PKey::Type t) {
- switch (t) {
- case PKey::RSA:
- return "rsa";
- case PKey::DSA:
- return "dsa";
- case PKey::DH:
- return "dh";
- default:
- return "";
- }
- }
-
- softstorePKeyBase (
- const SoftStoreEntry &entry,
- const QString &serialized,
- Provider *p
- ) : PKeyBase (p, "rsa"/*typeToString (entry.chain.primary ().subjectPublicKey ().type ())*/) {
- QCA_logTextMessage (
- "softstorePKeyBase::softstorePKeyBase1 - entry",
- Logger::Debug
- );
-
- _has_privateKeyRole = true;
- _entry = entry;
- _serialized = serialized;
- _pubkey = _entry.chain.primary ().subjectPublicKey ();
-
- QCA_logTextMessage (
- "softstorePKeyBase::softstorePKeyBase1 - return",
- Logger::Debug
- );
- }
-
- softstorePKeyBase (const softstorePKeyBase &from) : PKeyBase (from.provider (), "rsa"/*typeToString (from._pubkey.type ())*/) {
- QCA_logTextMessage (
- "softstorePKeyBase::softstorePKeyBaseC - entry",
- Logger::Debug
- );
-
- _has_privateKeyRole = from._has_privateKeyRole;
- _entry = from._entry;
- _serialized = from._serialized;
- _pubkey = from._pubkey;
- _privkey = from._privkey;
-
- QCA_logTextMessage (
- "softstorePKeyBase::softstorePKeyBaseC - return",
- Logger::Debug
- );
- }
-
- ~softstorePKeyBase () {
- QCA_logTextMessage (
- "softstorePKeyBase::~softstorePKeyBase - entry",
- Logger::Debug
- );
-
- QCA_logTextMessage (
- "softstorePKeyBase::~softstorePKeyBase - return",
- Logger::Debug
- );
- }
-
- virtual
- Provider::Context *
- clone () const {
- return new softstorePKeyBase (*this);
- }
+ static inline QString typeToString(PKey::Type t)
+ {
+ switch (t) {
+ case PKey::RSA:
+ return "rsa";
+ case PKey::DSA:
+ return "dsa";
+ case PKey::DH:
+ return "dh";
+ default:
+ return "";
+ }
+ }
+
+ softstorePKeyBase(
+ const SoftStoreEntry &entry,
+ const QString &serialized,
+ Provider *p
+ ) : PKeyBase(p, "rsa"/*typeToString (entry.chain.primary ().subjectPublicKey ().type ())*/)
+ {
+ QCA_logTextMessage(
+ "softstorePKeyBase::softstorePKeyBase1 - entry",
+ Logger::Debug
+ );
+
+ _has_privateKeyRole = true;
+ _entry = entry;
+ _serialized = serialized;
+ _pubkey = _entry.chain.primary().subjectPublicKey();
+
+ QCA_logTextMessage(
+ "softstorePKeyBase::softstorePKeyBase1 - return",
+ Logger::Debug
+ );
+ }
+
+ softstorePKeyBase(const softstorePKeyBase &from) : PKeyBase(from.provider(), "rsa"/*typeToString (from._pubkey.type ())*/)
+ {
+ QCA_logTextMessage(
+ "softstorePKeyBase::softstorePKeyBaseC - entry",
+ Logger::Debug
+ );
+
+ _has_privateKeyRole = from._has_privateKeyRole;
+ _entry = from._entry;
+ _serialized = from._serialized;
+ _pubkey = from._pubkey;
+ _privkey = from._privkey;
+
+ QCA_logTextMessage(
+ "softstorePKeyBase::softstorePKeyBaseC - return",
+ Logger::Debug
+ );
+ }
+
+ ~softstorePKeyBase()
+ {
+ QCA_logTextMessage(
+ "softstorePKeyBase::~softstorePKeyBase - entry",
+ Logger::Debug
+ );
+
+ QCA_logTextMessage(
+ "softstorePKeyBase::~softstorePKeyBase - return",
+ Logger::Debug
+ );
+ }
+
+ virtual
+ Provider::Context *
+ clone() const
+ {
+ return new softstorePKeyBase(*this);
+ }
public:
- virtual
- bool
- isNull () const {
- return _pubkey.isNull ();
- }
-
- virtual
- PKey::Type
- type () const {
- return _pubkey.type ();
- }
-
- virtual
- bool
- isPrivate () const {
- return _has_privateKeyRole;
- }
-
- virtual
- bool
- canExport () const {
- return !_has_privateKeyRole;
- }
-
- virtual
- void
- convertToPublic () {
- QCA_logTextMessage (
- "softstorePKeyBase::convertToPublic - entry",
- Logger::Debug
- );
-
- if (_has_privateKeyRole) {
- _has_privateKeyRole = false;
- }
-
- QCA_logTextMessage (
- "softstorePKeyBase::convertToPublic - return",
- Logger::Debug
- );
- }
-
- virtual
- int
- bits () const {
- return _pubkey.bitSize ();
- }
-
- virtual
- int
- maximumEncryptSize (
- EncryptionAlgorithm alg
- ) const {
- return _pubkey.maximumEncryptSize (alg);
- }
-
- virtual
- SecureArray
- encrypt (
- const SecureArray &in,
- EncryptionAlgorithm alg
- ) {
- return _pubkey.encrypt (in, alg);
- }
-
- virtual
- bool
- decrypt (
- const SecureArray &in,
- SecureArray *out,
- EncryptionAlgorithm alg
- ) {
- if (_ensureAccess ()) {
- return _privkey.decrypt (in, out, alg);
- }
- else {
- return false;
- }
- }
-
- virtual
- void
- startSign (
- SignatureAlgorithm alg,
- SignatureFormat format
- ) {
- if (_ensureAccess ()) {
- /*
- * We must use one object thought
- * signing, so it won't expire by
- * it-self or during passphrase.
- */
- _privkeySign = _privkey;
- _privkeySign.startSign (alg, format);
- }
- }
-
- virtual
- void
- startVerify (
- SignatureAlgorithm alg,
- SignatureFormat sf
- ) {
- _pubkey.startVerify (alg, sf);
- }
-
- virtual
- void
- update (
- const MemoryRegion &in
- ) {
- if (_has_privateKeyRole) {
- _privkeySign.update (in);
- }
- else {
- _pubkey.update (in);
- }
- }
-
- virtual
- QByteArray
- endSign () {
- QByteArray r = _privkeySign.signature ();
- _privkeySign = PrivateKey ();
- return r;
- }
-
- virtual
- bool
- validSignature (
- const QByteArray &sig
- ) {
- return _pubkey.validSignature (sig);
- }
-
- virtual
- void
- createPrivate (
- int bits,
- int exp,
- bool block
- ) {
- Q_UNUSED(bits);
- Q_UNUSED(exp);
- Q_UNUSED(block);
- }
-
- virtual
- void
- createPrivate (
- const BigInteger &n,
- const BigInteger &e,
- const BigInteger &p,
- const BigInteger &q,
- const BigInteger &d
- ) {
- Q_UNUSED(n);
- Q_UNUSED(e);
- Q_UNUSED(p);
- Q_UNUSED(q);
- Q_UNUSED(d);
- }
-
- virtual
- void
- createPublic (
- const BigInteger &n,
- const BigInteger &e
- ) {
- Q_UNUSED(n);
- Q_UNUSED(e);
- }
+ virtual
+ bool
+ isNull() const
+ {
+ return _pubkey.isNull();
+ }
+
+ virtual
+ PKey::Type
+ type() const
+ {
+ return _pubkey.type();
+ }
+
+ virtual
+ bool
+ isPrivate() const
+ {
+ return _has_privateKeyRole;
+ }
+
+ virtual
+ bool
+ canExport() const
+ {
+ return !_has_privateKeyRole;
+ }
+
+ virtual
+ void
+ convertToPublic()
+ {
+ QCA_logTextMessage(
+ "softstorePKeyBase::convertToPublic - entry",
+ Logger::Debug
+ );
+
+ if (_has_privateKeyRole) {
+ _has_privateKeyRole = false;
+ }
+
+ QCA_logTextMessage(
+ "softstorePKeyBase::convertToPublic - return",
+ Logger::Debug
+ );
+ }
+
+ virtual
+ int
+ bits() const
+ {
+ return _pubkey.bitSize();
+ }
+
+ virtual
+ int
+ maximumEncryptSize(
+ EncryptionAlgorithm alg
+ ) const
+ {
+ return _pubkey.maximumEncryptSize(alg);
+ }
+
+ virtual
+ SecureArray
+ encrypt(
+ const SecureArray &in,
+ EncryptionAlgorithm alg
+ )
+ {
+ return _pubkey.encrypt(in, alg);
+ }
+
+ virtual
+ bool
+ decrypt(
+ const SecureArray &in,
+ SecureArray *out,
+ EncryptionAlgorithm alg
+ )
+ {
+ if (_ensureAccess()) {
+ return _privkey.decrypt(in, out, alg);
+ } else {
+ return false;
+ }
+ }
+
+ virtual
+ void
+ startSign(
+ SignatureAlgorithm alg,
+ SignatureFormat format
+ )
+ {
+ if (_ensureAccess()) {
+ /*
+ * We must use one object thought
+ * signing, so it won't expire by
+ * it-self or during passphrase.
+ */
+ _privkeySign = _privkey;
+ _privkeySign.startSign(alg, format);
+ }
+ }
+
+ virtual
+ void
+ startVerify(
+ SignatureAlgorithm alg,
+ SignatureFormat sf
+ )
+ {
+ _pubkey.startVerify(alg, sf);
+ }
+
+ virtual
+ void
+ update(
+ const MemoryRegion &in
+ )
+ {
+ if (_has_privateKeyRole) {
+ _privkeySign.update(in);
+ } else {
+ _pubkey.update(in);
+ }
+ }
+
+ virtual
+ QByteArray
+ endSign()
+ {
+ QByteArray r = _privkeySign.signature();
+ _privkeySign = PrivateKey();
+ return r;
+ }
+
+ virtual
+ bool
+ validSignature(
+ const QByteArray &sig
+ )
+ {
+ return _pubkey.validSignature(sig);
+ }
+
+ virtual
+ void
+ createPrivate(
+ int bits,
+ int exp,
+ bool block
+ )
+ {
+ Q_UNUSED(bits);
+ Q_UNUSED(exp);
+ Q_UNUSED(block);
+ }
+
+ virtual
+ void
+ createPrivate(
+ const BigInteger &n,
+ const BigInteger &e,
+ const BigInteger &p,
+ const BigInteger &q,
+ const BigInteger &d
+ )
+ {
+ Q_UNUSED(n);
+ Q_UNUSED(e);
+ Q_UNUSED(p);
+ Q_UNUSED(q);
+ Q_UNUSED(d);
+ }
+
+ virtual
+ void
+ createPublic(
+ const BigInteger &n,
+ const BigInteger &e
+ )
+ {
+ Q_UNUSED(n);
+ Q_UNUSED(e);
+ }
public:
- PublicKey
- _publicKey () const {
- return _pubkey;
- }
-
- bool
- _ensureAccess () {
- bool ret = false;
-
- QCA_logTextMessage (
- "softstorePKeyBase::_ensureAccess - entry",
- Logger::Debug
- );
-
- if (_entry.unlockTimeout != -1) {
- if (dueTime >= QDateTime::currentDateTime ()) {
- QCA_logTextMessage (
- "softstorePKeyBase::_ensureAccess - dueTime reached, clearing",
- Logger::Debug
- );
- _privkey = PrivateKey ();
- }
- }
-
- if (!_privkey.isNull ()) {
- ret = true;
- }
- else {
- KeyStoreEntry entry;
- KeyStoreEntryContext *context = NULL;
- QString storeId, storeName;
- ConvertResult cresult;
-
- QCA_logTextMessage (
- "softstorePKeyBase::_ensureAccess - no current key, creating",
- Logger::Debug
- );
-
- // too lazy to create scope
- context = reinterpret_cast<KeyStoreListContext *> (s_keyStoreList)->entryPassive (_serialized);
- if (context != NULL) {
- storeId = context->storeId ();
- storeName = context->storeName ();
- entry.change (context);
- }
-
- while (!ret) {
-
- SecureArray passphrase;
-
- switch (_entry.keyReferenceType) {
- case keyTypeInvalid:
- case keyTypePKCS8Inline:
- break;
- case keyTypePKCS12:
- case keyTypePKCS8FilePEM:
- case keyTypePKCS8FileDER:
- {
- QFile file (_entry.keyReference);
- while (!file.open (QIODevice::ReadOnly)) {
- TokenAsker asker;
- asker.ask (
- KeyStoreInfo (KeyStore::SmartCard, storeId, storeName),
- entry,
- context
- );
- asker.waitForResponse ();
- if (!asker.accepted ()) {
- goto cleanup1;
- }
- }
- }
- break;
- }
-
- if (!_entry.noPassphrase) {
- PasswordAsker asker;
- asker.ask (
- Event::StylePassphrase,
- KeyStoreInfo (KeyStore::User, storeId, storeName),
- entry,
- context
- );
- asker.waitForResponse ();
- passphrase = asker.password ();
- if (!asker.accepted ()) {
- goto cleanup1;
- }
- }
-
- switch (_entry.keyReferenceType) {
- case keyTypeInvalid:
- break;
- case keyTypePKCS12:
- {
- KeyBundle bundle = KeyBundle::fromFile (
- _entry.keyReference,
- passphrase,
- &cresult
- );
- if (cresult == ConvertGood) {
- _privkey = bundle.privateKey ();
- ret = true;
- }
- }
- break;
- case keyTypePKCS8Inline:
- {
- PrivateKey k = PrivateKey::fromDER (
- Base64 ().stringToArray (_entry.keyReference),
- passphrase,
- &cresult
- );
- if (cresult == ConvertGood) {
- _privkey = k;
- ret = true;
- }
- }
- break;
- case keyTypePKCS8FilePEM:
- {
- PrivateKey k = PrivateKey::fromPEMFile (
- _entry.keyReference,
- passphrase,
- &cresult
- );
- if (cresult == ConvertGood) {
- _privkey = k;
- ret = true;
- }
- }
- break;
- case keyTypePKCS8FileDER:
- {
- QFile file (_entry.keyReference);
- if (file.open (QIODevice::ReadOnly)) {
- QByteArray contents = file.readAll ();
-
- PrivateKey k = PrivateKey::fromDER (
- contents,
- passphrase,
- &cresult
- );
- if (cresult == ConvertGood) {
- _privkey = k;
- ret = true;
- }
- }
- }
- break;
- }
- }
-
- if (_entry.unlockTimeout != -1) {
- dueTime = QDateTime::currentDateTime ().addSecs (_entry.unlockTimeout);
- }
-
- cleanup1:
- ;
-
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstorePKeyBase::_ensureAccess - return ret=%d",
- ret ? 1 : 0
- ),
- Logger::Debug
- );
-
- return ret;
- }
+ PublicKey
+ _publicKey() const
+ {
+ return _pubkey;
+ }
+
+ bool
+ _ensureAccess()
+ {
+ bool ret = false;
+
+ QCA_logTextMessage(
+ "softstorePKeyBase::_ensureAccess - entry",
+ Logger::Debug
+ );
+
+ if (_entry.unlockTimeout != -1) {
+ if (dueTime >= QDateTime::currentDateTime()) {
+ QCA_logTextMessage(
+ "softstorePKeyBase::_ensureAccess - dueTime reached, clearing",
+ Logger::Debug
+ );
+ _privkey = PrivateKey();
+ }
+ }
+
+ if (!_privkey.isNull()) {
+ ret = true;
+ } else {
+ KeyStoreEntry entry;
+ KeyStoreEntryContext *context = NULL;
+ QString storeId, storeName;
+ ConvertResult cresult;
+
+ QCA_logTextMessage(
+ "softstorePKeyBase::_ensureAccess - no current key, creating",
+ Logger::Debug
+ );
+
+ // too lazy to create scope
+ context = reinterpret_cast<KeyStoreListContext *>(s_keyStoreList)->entryPassive(_serialized);
+ if (context != NULL) {
+ storeId = context->storeId();
+ storeName = context->storeName();
+ entry.change(context);
+ }
+
+ while (!ret) {
+
+ SecureArray passphrase;
+
+ switch (_entry.keyReferenceType) {
+ case keyTypeInvalid:
+ case keyTypePKCS8Inline:
+ break;
+ case keyTypePKCS12:
+ case keyTypePKCS8FilePEM:
+ case keyTypePKCS8FileDER: {
+ QFile file(_entry.keyReference);
+ while (!file.open(QIODevice::ReadOnly)) {
+ TokenAsker asker;
+ asker.ask(
+ KeyStoreInfo(KeyStore::SmartCard, storeId, storeName),
+ entry,
+ context
+ );
+ asker.waitForResponse();
+ if (!asker.accepted()) {
+ goto cleanup1;
+ }
+ }
+ }
+ break;
+ }
+
+ if (!_entry.noPassphrase) {
+ PasswordAsker asker;
+ asker.ask(
+ Event::StylePassphrase,
+ KeyStoreInfo(KeyStore::User, storeId, storeName),
+ entry,
+ context
+ );
+ asker.waitForResponse();
+ passphrase = asker.password();
+ if (!asker.accepted()) {
+ goto cleanup1;
+ }
+ }
+
+ switch (_entry.keyReferenceType) {
+ case keyTypeInvalid:
+ break;
+ case keyTypePKCS12: {
+ KeyBundle bundle = KeyBundle::fromFile(
+ _entry.keyReference,
+ passphrase,
+ &cresult
+ );
+ if (cresult == ConvertGood) {
+ _privkey = bundle.privateKey();
+ ret = true;
+ }
+ }
+ break;
+ case keyTypePKCS8Inline: {
+ PrivateKey k = PrivateKey::fromDER(
+ Base64().stringToArray(_entry.keyReference),
+ passphrase,
+ &cresult
+ );
+ if (cresult == ConvertGood) {
+ _privkey = k;
+ ret = true;
+ }
+ }
+ break;
+ case keyTypePKCS8FilePEM: {
+ PrivateKey k = PrivateKey::fromPEMFile(
+ _entry.keyReference,
+ passphrase,
+ &cresult
+ );
+ if (cresult == ConvertGood) {
+ _privkey = k;
+ ret = true;
+ }
+ }
+ break;
+ case keyTypePKCS8FileDER: {
+ QFile file(_entry.keyReference);
+ if (file.open(QIODevice::ReadOnly)) {
+ QByteArray contents = file.readAll();
+
+ PrivateKey k = PrivateKey::fromDER(
+ contents,
+ passphrase,
+ &cresult
+ );
+ if (cresult == ConvertGood) {
+ _privkey = k;
+ ret = true;
+ }
+ }
+ }
+ break;
+ }
+ }
+
+ if (_entry.unlockTimeout != -1) {
+ dueTime = QDateTime::currentDateTime().addSecs(_entry.unlockTimeout);
+ }
+
+ cleanup1:
+ ;
+
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstorePKeyBase::_ensureAccess - return ret=%d",
+ ret ? 1 : 0
+ ),
+ Logger::Debug
+ );
+
+ return ret;
+ }
};
class softstorePKeyContext : public PKeyContext
{
private:
- PKeyBase *_k;
+ PKeyBase *_k;
public:
- softstorePKeyContext (Provider *p) : PKeyContext (p) {
- _k = NULL;
- }
-
- ~softstorePKeyContext () {
- delete _k;
- _k = NULL;
- }
-
- virtual
- Provider::Context *
- clone () const {
- softstorePKeyContext *c = new softstorePKeyContext (*this);
- c->_k = (PKeyBase *)_k->clone();
- return c;
- }
+ softstorePKeyContext(Provider *p) : PKeyContext(p)
+ {
+ _k = NULL;
+ }
+
+ ~softstorePKeyContext()
+ {
+ delete _k;
+ _k = NULL;
+ }
+
+ virtual
+ Provider::Context *
+ clone() const
+ {
+ softstorePKeyContext *c = new softstorePKeyContext(*this);
+ c->_k = (PKeyBase *)_k->clone();
+ return c;
+ }
public:
- virtual
- QList<PKey::Type>
- supportedTypes () const {
- QList<PKey::Type> list;
- list += static_cast<softstorePKeyBase *>(_k)->_publicKey ().type ();
- return list;
- }
-
- virtual
- QList<PKey::Type>
- supportedIOTypes () const {
- QList<PKey::Type> list;
- list += static_cast<softstorePKeyBase *>(_k)->_publicKey ().type ();
- return list;
- }
-
- virtual
- QList<PBEAlgorithm>
- supportedPBEAlgorithms () const {
- QList<PBEAlgorithm> list;
- return list;
- }
-
- virtual
- PKeyBase *
- key () {
- return _k;
- }
-
- virtual
- const PKeyBase *
- key () const {
- return _k;
- }
-
- virtual
- void
- setKey (PKeyBase *key) {
- delete _k;
- _k = key;
- }
-
- virtual
- bool
- importKey (
- const PKeyBase *key
- ) {
- Q_UNUSED(key);
- return false;
- }
-
- static
- int
- passphrase_cb (
- char *buf,
- int size,
- int rwflag,
- void *u
- ) {
- Q_UNUSED(buf);
- Q_UNUSED(size);
- Q_UNUSED(rwflag);
- Q_UNUSED(u);
- return 0;
- }
-
- virtual
- QByteArray
- publicToDER () const {
- return static_cast<softstorePKeyBase *>(_k)->_publicKey ().toDER ();
- }
-
- virtual
- QString
- publicToPEM () const {
- return static_cast<softstorePKeyBase *>(_k)->_publicKey ().toPEM ();
- }
-
- virtual
- ConvertResult
- publicFromDER (
- const QByteArray &in
- ) {
- Q_UNUSED(in);
- return ErrorDecode;
- }
-
- virtual
- ConvertResult
- publicFromPEM (
- const QString &s
- ) {
- Q_UNUSED(s);
- return ErrorDecode;
- }
-
- virtual
- SecureArray
- privateToDER(
- const SecureArray &passphrase,
- PBEAlgorithm pbe
- ) const {
- Q_UNUSED(passphrase);
- Q_UNUSED(pbe);
- return SecureArray ();
- }
-
- virtual
- QString
- privateToPEM (
- const SecureArray &passphrase,
- PBEAlgorithm pbe
- ) const {
- Q_UNUSED(passphrase);
- Q_UNUSED(pbe);
- return QString ();
- }
-
- virtual
- ConvertResult
- privateFromDER (
- const SecureArray &in,
- const SecureArray &passphrase
- ) {
- Q_UNUSED(in);
- Q_UNUSED(passphrase);
- return ErrorDecode;
- }
-
- virtual
- ConvertResult
- privateFromPEM (
- const QString &s,
- const SecureArray &passphrase
- ) {
- Q_UNUSED(s);
- Q_UNUSED(passphrase);
- return ErrorDecode;
- }
+ virtual
+ QList<PKey::Type>
+ supportedTypes() const
+ {
+ QList<PKey::Type> list;
+ list += static_cast<softstorePKeyBase *>(_k)->_publicKey().type();
+ return list;
+ }
+
+ virtual
+ QList<PKey::Type>
+ supportedIOTypes() const
+ {
+ QList<PKey::Type> list;
+ list += static_cast<softstorePKeyBase *>(_k)->_publicKey().type();
+ return list;
+ }
+
+ virtual
+ QList<PBEAlgorithm>
+ supportedPBEAlgorithms() const
+ {
+ QList<PBEAlgorithm> list;
+ return list;
+ }
+
+ virtual
+ PKeyBase *
+ key()
+ {
+ return _k;
+ }
+
+ virtual
+ const PKeyBase *
+ key() const
+ {
+ return _k;
+ }
+
+ virtual
+ void
+ setKey(PKeyBase *key)
+ {
+ delete _k;
+ _k = key;
+ }
+
+ virtual
+ bool
+ importKey(
+ const PKeyBase *key
+ )
+ {
+ Q_UNUSED(key);
+ return false;
+ }
+
+ static
+ int
+ passphrase_cb(
+ char *buf,
+ int size,
+ int rwflag,
+ void *u
+ )
+ {
+ Q_UNUSED(buf);
+ Q_UNUSED(size);
+ Q_UNUSED(rwflag);
+ Q_UNUSED(u);
+ return 0;
+ }
+
+ virtual
+ QByteArray
+ publicToDER() const
+ {
+ return static_cast<softstorePKeyBase *>(_k)->_publicKey().toDER();
+ }
+
+ virtual
+ QString
+ publicToPEM() const
+ {
+ return static_cast<softstorePKeyBase *>(_k)->_publicKey().toPEM();
+ }
+
+ virtual
+ ConvertResult
+ publicFromDER(
+ const QByteArray &in
+ )
+ {
+ Q_UNUSED(in);
+ return ErrorDecode;
+ }
+
+ virtual
+ ConvertResult
+ publicFromPEM(
+ const QString &s
+ )
+ {
+ Q_UNUSED(s);
+ return ErrorDecode;
+ }
+
+ virtual
+ SecureArray
+ privateToDER(
+ const SecureArray &passphrase,
+ PBEAlgorithm pbe
+ ) const
+ {
+ Q_UNUSED(passphrase);
+ Q_UNUSED(pbe);
+ return SecureArray();
+ }
+
+ virtual
+ QString
+ privateToPEM(
+ const SecureArray &passphrase,
+ PBEAlgorithm pbe
+ ) const
+ {
+ Q_UNUSED(passphrase);
+ Q_UNUSED(pbe);
+ return QString();
+ }
+
+ virtual
+ ConvertResult
+ privateFromDER(
+ const SecureArray &in,
+ const SecureArray &passphrase
+ )
+ {
+ Q_UNUSED(in);
+ Q_UNUSED(passphrase);
+ return ErrorDecode;
+ }
+
+ virtual
+ ConvertResult
+ privateFromPEM(
+ const QString &s,
+ const SecureArray &passphrase
+ )
+ {
+ Q_UNUSED(s);
+ Q_UNUSED(passphrase);
+ return ErrorDecode;
+ }
};
class softstoreKeyStoreEntryContext : public KeyStoreEntryContext
{
private:
- KeyStoreEntry::Type _item_type;
- KeyBundle _key;
- SoftStoreEntry _entry;
- QString _serialized;
+ KeyStoreEntry::Type _item_type;
+ KeyBundle _key;
+ SoftStoreEntry _entry;
+ QString _serialized;
public:
- softstoreKeyStoreEntryContext (
- const KeyBundle &key,
- const SoftStoreEntry &entry,
- const QString &serialized,
- Provider *p
- ) : KeyStoreEntryContext(p) {
- _item_type = KeyStoreEntry::TypeKeyBundle;
- _key = key;
- _entry = entry;
- _serialized = serialized;
- }
-
- softstoreKeyStoreEntryContext (
- const softstoreKeyStoreEntryContext &from
- ) : KeyStoreEntryContext(from) {
- _item_type = from._item_type;
- _key = from._key;
- _entry = from._entry;
- _serialized = from._serialized;
- }
-
- virtual
- Provider::Context *
- clone () const {
- return new softstoreKeyStoreEntryContext (*this);
- }
+ softstoreKeyStoreEntryContext(
+ const KeyBundle &key,
+ const SoftStoreEntry &entry,
+ const QString &serialized,
+ Provider *p
+ ) : KeyStoreEntryContext(p)
+ {
+ _item_type = KeyStoreEntry::TypeKeyBundle;
+ _key = key;
+ _entry = entry;
+ _serialized = serialized;
+ }
+
+ softstoreKeyStoreEntryContext(
+ const softstoreKeyStoreEntryContext &from
+ ) : KeyStoreEntryContext(from)
+ {
+ _item_type = from._item_type;
+ _key = from._key;
+ _entry = from._entry;
+ _serialized = from._serialized;
+ }
+
+ virtual
+ Provider::Context *
+ clone() const
+ {
+ return new softstoreKeyStoreEntryContext(*this);
+ }
public:
- virtual
- KeyStoreEntry::Type
- type () const {
- return KeyStoreEntry::TypeKeyBundle;
- }
-
- virtual
- QString
- name () const {
- return _entry.name;
- }
-
- virtual
- QString
- id () const {
- return _entry.name;
- }
-
- virtual
- KeyBundle
- keyBundle () const {
- return _key;
- }
-
- virtual
- Certificate
- certificate () const {
- return _entry.chain.primary ();
- }
-
- virtual
- QString
- storeId () const {
- return QString ().sprintf ("%s/%s", "qca-softstore", myPrintable (_entry.name));
- }
-
- virtual
- QString
- storeName () const {
- return _entry.name;
- }
-
- virtual
- bool
- ensureAccess () {
- return static_cast<softstorePKeyBase *>(static_cast<PKeyContext *>(_key.privateKey ().context ())->key ())->_ensureAccess ();
- }
-
- virtual
- QString
- serialize () const {
- return _serialized;
- }
+ virtual
+ KeyStoreEntry::Type
+ type() const
+ {
+ return KeyStoreEntry::TypeKeyBundle;
+ }
+
+ virtual
+ QString
+ name() const
+ {
+ return _entry.name;
+ }
+
+ virtual
+ QString
+ id() const
+ {
+ return _entry.name;
+ }
+
+ virtual
+ KeyBundle
+ keyBundle() const
+ {
+ return _key;
+ }
+
+ virtual
+ Certificate
+ certificate() const
+ {
+ return _entry.chain.primary();
+ }
+
+ virtual
+ QString
+ storeId() const
+ {
+ return QString().sprintf("%s/%s", "qca-softstore", myPrintable(_entry.name));
+ }
+
+ virtual
+ QString
+ storeName() const
+ {
+ return _entry.name;
+ }
+
+ virtual
+ bool
+ ensureAccess()
+ {
+ return static_cast<softstorePKeyBase *>(static_cast<PKeyContext *>(_key.privateKey().context())->key())->_ensureAccess();
+ }
+
+ virtual
+ QString
+ serialize() const
+ {
+ return _serialized;
+ }
};
class softstoreKeyStoreListContext : public KeyStoreListContext
{
- Q_OBJECT
+ Q_OBJECT
private:
- int _last_id;
- QList<SoftStoreEntry> _entries;
+ int _last_id;
+ QList<SoftStoreEntry> _entries;
public:
- softstoreKeyStoreListContext (Provider *p) : KeyStoreListContext (p) {
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::softstoreKeyStoreListContext - entry Provider=%p",
- (void *)p
- ),
- Logger::Debug
- );
-
- _last_id = 0;
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::softstoreKeyStoreListContext - return",
- Logger::Debug
- );
- }
-
- ~softstoreKeyStoreListContext () {
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::~softstoreKeyStoreListContext - entry",
- Logger::Debug
- );
-
- s_keyStoreList = NULL;
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::~softstoreKeyStoreListContext - return",
- Logger::Debug
- );
- }
-
- virtual
- Provider::Context *
- clone () const {
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::clone - entry/return",
- Logger::Debug
- );
- return NULL;
- }
+ softstoreKeyStoreListContext(Provider *p) : KeyStoreListContext(p)
+ {
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::softstoreKeyStoreListContext - entry Provider=%p",
+ (void *)p
+ ),
+ Logger::Debug
+ );
+
+ _last_id = 0;
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::softstoreKeyStoreListContext - return",
+ Logger::Debug
+ );
+ }
+
+ ~softstoreKeyStoreListContext()
+ {
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::~softstoreKeyStoreListContext - entry",
+ Logger::Debug
+ );
+
+ s_keyStoreList = NULL;
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::~softstoreKeyStoreListContext - return",
+ Logger::Debug
+ );
+ }
+
+ virtual
+ Provider::Context *
+ clone() const
+ {
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::clone - entry/return",
+ Logger::Debug
+ );
+ return NULL;
+ }
public:
- virtual
- void
- start () {
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::start - entry",
- Logger::Debug
- );
-
- QMetaObject::invokeMethod(this, "doReady", Qt::QueuedConnection);
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::start - return",
- Logger::Debug
- );
- }
-
- virtual
- void
- setUpdatesEnabled (bool enabled) {
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::setUpdatesEnabled - entry/return enabled=%d",
- enabled ? 1 : 0
- ),
- Logger::Debug
- );
- }
-
- virtual
- KeyStoreEntryContext *
- entry (
- int id,
- const QString &entryId
- ) {
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::entry - entry/return id=%d entryId='%s'",
- id,
- myPrintable (entryId)
- ),
- Logger::Debug
- );
-
- Q_UNUSED(id);
- Q_UNUSED(entryId);
- return NULL;
- }
-
- virtual
- KeyStoreEntryContext *
- entryPassive (
- const QString &serialized
- ) {
- KeyStoreEntryContext *entry = NULL;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::entryPassive - entry serialized='%s'",
- myPrintable (serialized)
- ),
- Logger::Debug
- );
-
- if (serialized.startsWith ("qca-softstore/")) {
- SoftStoreEntry sentry;
-
- if (_deserializeSoftStoreEntry (serialized, sentry)) {
- entry = _keyStoreEntryBySoftStoreEntry (sentry);
- }
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::entryPassive - return entry=%p",
- (void *)entry
- ),
- Logger::Debug
- );
-
- return entry;
- }
-
- virtual
- KeyStore::Type
- type (int id) const {
- Q_UNUSED(id);
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::type - entry/return id=%d",
- id
- ),
- Logger::Debug
- );
-
- return KeyStore::User;
- }
-
- virtual
- QString
- storeId (int id) const {
- QString ret;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::storeId - entry id=%d",
- id
- ),
- Logger::Debug
- );
-
- ret = "qca-softstore";
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::storeId - return ret=%s",
- myPrintable (ret)
- ),
- Logger::Debug
- );
-
- return ret;
- }
-
- virtual
- QString
- name (int id) const {
- QString ret;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::name - entry id=%d",
- id
- ),
- Logger::Debug
- );
-
- ret = "User Software Store";
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::name - return ret=%s",
- myPrintable (ret)
- ),
- Logger::Debug
- );
-
- return ret;
- }
-
- virtual
- QList<KeyStoreEntry::Type>
- entryTypes (int id) const {
- Q_UNUSED(id);
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::entryTypes - entry/return id=%d",
- id
- ),
- Logger::Debug
- );
-
- QList<KeyStoreEntry::Type> list;
- list += KeyStoreEntry::TypeKeyBundle;
- list += KeyStoreEntry::TypeCertificate;
- return list;
- }
-
- virtual
- QList<int>
- keyStores () {
- QList<int> list;
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::keyStores - entry",
- Logger::Debug
- );
-
- list += _last_id;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::keyStores - return out.size()=%d",
- list.size ()
- ),
- Logger::Debug
- );
-
- return list;
- }
-
- virtual
- QList<KeyStoreEntryContext *>
- entryList (int id) {
- QList<KeyStoreEntryContext*> list;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::entryList - entry id=%d",
- id
- ),
- Logger::Debug
- );
-
- foreach (const SoftStoreEntry &e, _entries) {
- list += _keyStoreEntryBySoftStoreEntry (e);
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::entryList - return out.size()=%d",
- list.size ()
- ),
- Logger::Debug
- );
-
- return list;
- }
-
- void
- _emit_diagnosticText (
- const QString &t
- ) {
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::_emit_diagnosticText - entry t='%s'",
- myPrintable (t)
- ),
- Logger::Debug
- );
-
- QCA_logTextMessage (t, Logger::Warning);
-
- emit diagnosticText (t);
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::_emit_diagnosticText - return",
- Logger::Debug
- );
- }
+ virtual
+ void
+ start()
+ {
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::start - entry",
+ Logger::Debug
+ );
+
+ QMetaObject::invokeMethod(this, "doReady", Qt::QueuedConnection);
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::start - return",
+ Logger::Debug
+ );
+ }
+
+ virtual
+ void
+ setUpdatesEnabled(bool enabled)
+ {
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::setUpdatesEnabled - entry/return enabled=%d",
+ enabled ? 1 : 0
+ ),
+ Logger::Debug
+ );
+ }
+
+ virtual
+ KeyStoreEntryContext *
+ entry(
+ int id,
+ const QString &entryId
+ )
+ {
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::entry - entry/return id=%d entryId='%s'",
+ id,
+ myPrintable(entryId)
+ ),
+ Logger::Debug
+ );
+
+ Q_UNUSED(id);
+ Q_UNUSED(entryId);
+ return NULL;
+ }
+
+ virtual
+ KeyStoreEntryContext *
+ entryPassive(
+ const QString &serialized
+ )
+ {
+ KeyStoreEntryContext *entry = NULL;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::entryPassive - entry serialized='%s'",
+ myPrintable(serialized)
+ ),
+ Logger::Debug
+ );
+
+ if (serialized.startsWith("qca-softstore/")) {
+ SoftStoreEntry sentry;
+
+ if (_deserializeSoftStoreEntry(serialized, sentry)) {
+ entry = _keyStoreEntryBySoftStoreEntry(sentry);
+ }
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::entryPassive - return entry=%p",
+ (void *)entry
+ ),
+ Logger::Debug
+ );
+
+ return entry;
+ }
+
+ virtual
+ KeyStore::Type
+ type(int id) const
+ {
+ Q_UNUSED(id);
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::type - entry/return id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ return KeyStore::User;
+ }
+
+ virtual
+ QString
+ storeId(int id) const
+ {
+ QString ret;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::storeId - entry id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ ret = "qca-softstore";
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::storeId - return ret=%s",
+ myPrintable(ret)
+ ),
+ Logger::Debug
+ );
+
+ return ret;
+ }
+
+ virtual
+ QString
+ name(int id) const
+ {
+ QString ret;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::name - entry id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ ret = "User Software Store";
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::name - return ret=%s",
+ myPrintable(ret)
+ ),
+ Logger::Debug
+ );
+
+ return ret;
+ }
+
+ virtual
+ QList<KeyStoreEntry::Type>
+ entryTypes(int id) const
+ {
+ Q_UNUSED(id);
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::entryTypes - entry/return id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ QList<KeyStoreEntry::Type> list;
+ list += KeyStoreEntry::TypeKeyBundle;
+ list += KeyStoreEntry::TypeCertificate;
+ return list;
+ }
+
+ virtual
+ QList<int>
+ keyStores()
+ {
+ QList<int> list;
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::keyStores - entry",
+ Logger::Debug
+ );
+
+ list += _last_id;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::keyStores - return out.size()=%d",
+ list.size()
+ ),
+ Logger::Debug
+ );
+
+ return list;
+ }
+
+ virtual
+ QList<KeyStoreEntryContext *>
+ entryList(int id)
+ {
+ QList<KeyStoreEntryContext *> list;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::entryList - entry id=%d",
+ id
+ ),
+ Logger::Debug
+ );
+
+ foreach (const SoftStoreEntry &e, _entries) {
+ list += _keyStoreEntryBySoftStoreEntry(e);
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::entryList - return out.size()=%d",
+ list.size()
+ ),
+ Logger::Debug
+ );
+
+ return list;
+ }
+
+ void
+ _emit_diagnosticText(
+ const QString &t
+ )
+ {
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::_emit_diagnosticText - entry t='%s'",
+ myPrintable(t)
+ ),
+ Logger::Debug
+ );
+
+ QCA_logTextMessage(t, Logger::Warning);
+
+ emit diagnosticText(t);
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::_emit_diagnosticText - return",
+ Logger::Debug
+ );
+ }
private slots:
- void
- doReady () {
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::doReady - entry",
- Logger::Debug
- );
-
- emit busyEnd ();
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::doReady - return",
- Logger::Debug
- );
- }
-
- void
- doUpdated () {
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::doUpdated - entry",
- Logger::Debug
- );
-
- emit updated ();
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::doUpdated - return",
- Logger::Debug
- );
- }
+ void
+ doReady()
+ {
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::doReady - entry",
+ Logger::Debug
+ );
+
+ emit busyEnd();
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::doReady - return",
+ Logger::Debug
+ );
+ }
+
+ void
+ doUpdated()
+ {
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::doUpdated - entry",
+ Logger::Debug
+ );
+
+ emit updated();
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::doUpdated - return",
+ Logger::Debug
+ );
+ }
public:
- void
- _updateConfig (const QVariantMap &config, const int maxEntries) {
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::_updateConfig - entry",
- Logger::Debug
- );
-
- QMap<QString, KeyType> keyTypeMap;
- keyTypeMap["pkcs12"] = keyTypePKCS12;
- keyTypeMap["pkcs8"] = keyTypePKCS8Inline;
- keyTypeMap["pkcs8-file-pem"] = keyTypePKCS8FilePEM;
- keyTypeMap["pkcs8-file-der"] = keyTypePKCS8FileDER;
-
- QMap<QString, PublicType> publicTypeMap;
- publicTypeMap["x509chain"] = publicTypeX509Chain;
-
- _last_id++;
- _entries.clear ();
-
- for (int i=0;i<maxEntries;i++) {
- if (config[QString ().sprintf ("entry_%02d_enabled", i)].toBool ()) {
- ConvertResult cresult;
- SoftStoreEntry entry;
- PublicType publicType = publicTypeInvalid;
-
- entry.name = config[QString ().sprintf ("entry_%02d_name", i)].toString ();
- QString stringReferenceType = config[QString ().sprintf ("entry_%02d_private_type", i)].toString ();
- QString stringPublicType = config[QString ().sprintf ("entry_%02d_public_type", i)].toString ();
- entry.noPassphrase = config[QString ().sprintf ("entry_%02d_no_passphrase", i)].toBool ();
- entry.unlockTimeout = config[QString ().sprintf ("entry_%02d_unlock_timeout", i)].toInt ();
-
- if (publicTypeMap.contains (stringPublicType)) {
- publicType = publicTypeMap[stringPublicType];
- }
- else {
- _emit_diagnosticText (
- QString ().sprintf (
- "Software Store: Bad public key type of '%s' entry.\n",
- myPrintable (entry.name)
- )
- );
- goto cleanup1;
- }
-
- if (keyTypeMap.contains (stringReferenceType)) {
- entry.keyReferenceType = keyTypeMap[stringReferenceType];
- }
- else {
- _emit_diagnosticText (
- QString ().sprintf (
- "Software Store: Bad private key type of '%s' entry.\n",
- myPrintable (entry.name)
- )
- );
- goto cleanup1;
- }
-
- entry.keyReference = config[QString ().sprintf ("entry_%02d_private", i)].toString ();
-
- switch (publicType) {
- case publicTypeInvalid:
- goto cleanup1;
- break;
- case publicTypeX509Chain:
- QStringList base64certs = config[QString ().sprintf ("entry_%02d_public", i)].toString ().split ("!");
-
- foreach (const QString &s, base64certs) {
- entry.chain += Certificate::fromDER (
- Base64 ().stringToArray (s).toByteArray (),
- &cresult
- );
- }
-
- if (cresult != ConvertGood) {
- _emit_diagnosticText (
- QString ().sprintf (
- "Software Store: Cannot load certificate of '%s' entry.\n",
- myPrintable (entry.name)
- )
- );
- goto cleanup1;
- }
- break;
- }
-
- _entries += entry;
-
- cleanup1:
- ; //nothing to do for this entry.
- }
- }
-
- QMetaObject::invokeMethod(s_keyStoreList, "doUpdated", Qt::QueuedConnection);
-
- QCA_logTextMessage (
- "softstoreKeyStoreListContext::_updateConfig - return",
- Logger::Debug
- );
- }
+ void
+ _updateConfig(const QVariantMap &config, const int maxEntries)
+ {
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::_updateConfig - entry",
+ Logger::Debug
+ );
+
+ QMap<QString, KeyType> keyTypeMap;
+ keyTypeMap["pkcs12"] = keyTypePKCS12;
+ keyTypeMap["pkcs8"] = keyTypePKCS8Inline;
+ keyTypeMap["pkcs8-file-pem"] = keyTypePKCS8FilePEM;
+ keyTypeMap["pkcs8-file-der"] = keyTypePKCS8FileDER;
+
+ QMap<QString, PublicType> publicTypeMap;
+ publicTypeMap["x509chain"] = publicTypeX509Chain;
+
+ _last_id++;
+ _entries.clear();
+
+ for (int i = 0; i < maxEntries; i++) {
+ if (config[QString().sprintf("entry_%02d_enabled", i)].toBool()) {
+ ConvertResult cresult;
+ SoftStoreEntry entry;
+ PublicType publicType = publicTypeInvalid;
+
+ entry.name = config[QString().sprintf("entry_%02d_name", i)].toString();
+ QString stringReferenceType = config[QString().sprintf("entry_%02d_private_type", i)].toString();
+ QString stringPublicType = config[QString().sprintf("entry_%02d_public_type", i)].toString();
+ entry.noPassphrase = config[QString().sprintf("entry_%02d_no_passphrase", i)].toBool();
+ entry.unlockTimeout = config[QString().sprintf("entry_%02d_unlock_timeout", i)].toInt();
+
+ if (publicTypeMap.contains(stringPublicType)) {
+ publicType = publicTypeMap[stringPublicType];
+ } else {
+ _emit_diagnosticText(
+ QString().sprintf(
+ "Software Store: Bad public key type of '%s' entry.\n",
+ myPrintable(entry.name)
+ )
+ );
+ goto cleanup1;
+ }
+
+ if (keyTypeMap.contains(stringReferenceType)) {
+ entry.keyReferenceType = keyTypeMap[stringReferenceType];
+ } else {
+ _emit_diagnosticText(
+ QString().sprintf(
+ "Software Store: Bad private key type of '%s' entry.\n",
+ myPrintable(entry.name)
+ )
+ );
+ goto cleanup1;
+ }
+
+ entry.keyReference = config[QString().sprintf("entry_%02d_private", i)].toString();
+
+ switch (publicType) {
+ case publicTypeInvalid:
+ goto cleanup1;
+ break;
+ case publicTypeX509Chain:
+ QStringList base64certs = config[QString().sprintf("entry_%02d_public", i)].toString().split("!");
+
+ foreach (const QString &s, base64certs) {
+ entry.chain += Certificate::fromDER(
+ Base64().stringToArray(s).toByteArray(),
+ &cresult
+ );
+ }
+
+ if (cresult != ConvertGood) {
+ _emit_diagnosticText(
+ QString().sprintf(
+ "Software Store: Cannot load certificate of '%s' entry.\n",
+ myPrintable(entry.name)
+ )
+ );
+ goto cleanup1;
+ }
+ break;
+ }
+
+ _entries += entry;
+
+ cleanup1:
+ ; //nothing to do for this entry.
+ }
+ }
+
+ QMetaObject::invokeMethod(s_keyStoreList, "doUpdated", Qt::QueuedConnection);
+
+ QCA_logTextMessage(
+ "softstoreKeyStoreListContext::_updateConfig - return",
+ Logger::Debug
+ );
+ }
private:
- QString
- _serializeSoftStoreEntry (
- const SoftStoreEntry &entry
- ) const {
- QString serialized;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::_serializeSoftStoreEntry - entry name=%s",
- myPrintable (entry.name)
- ),
- Logger::Debug
- );
-
- serialized = QString ().sprintf (
- "qca-softstore/0/%s/%d/%s/%d/%d/x509chain/",
- myPrintable (_escapeString (entry.name)),
- entry.keyReferenceType,
- myPrintable (_escapeString (entry.keyReference)),
- entry.noPassphrase ? 1 : 0,
- entry.unlockTimeout
- );
-
- QStringList list;
- foreach (const Certificate &i, entry.chain) {
- list += _escapeString (Base64 ().arrayToString (i.toDER ()));
- }
-
- serialized.append (list.join ("/"));
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::_serializeSoftStoreEntry - return serialized='%s'",
- myPrintable (serialized)
- ),
- Logger::Debug
- );
-
- return serialized;
- }
-
- bool
- _deserializeSoftStoreEntry (
- const QString &serialized,
- SoftStoreEntry &entry
- ) const {
- bool ret = false;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::_deserializeSoftStoreEntry - entry from='%s'",
- myPrintable (serialized)
- ),
- Logger::Debug
- );
-
- entry = SoftStoreEntry ();
-
- QStringList list = serialized.split ("/");
- int n=0;
-
- if (list.size () < 8) {
- goto cleanup;
- }
-
- if (list[n++] != "qca-softstore") {
- goto cleanup;
- }
-
- if (list[n++].toInt () != 0) {
- goto cleanup;
- }
-
- entry.name = _unescapeString (list[n++]);
- entry.keyReferenceType = (KeyType)list[n++].toInt ();
- entry.keyReference = _unescapeString (list[n++]);
- entry.noPassphrase = list[n++].toInt () != 0;
- entry.unlockTimeout = list[n++].toInt ();
- n++; // skip public key for now.
-
- while (n < list.size ()) {
- Certificate cert = Certificate::fromDER (
- Base64 ().stringToArray (_unescapeString (list[n++])).toByteArray ()
- );
- if (cert.isNull ()) {
- goto cleanup;
- }
- entry.chain += cert;
- }
-
- ret = true;
-
- cleanup:
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::_deserializeSoftStoreEntry - return ret=%d chain.size()=%d",
- ret ? 1 : 0,
- entry.chain.size ()
- ),
- Logger::Debug
- );
-
- return ret;
- }
-
- softstoreKeyStoreEntryContext *
- _keyStoreEntryBySoftStoreEntry (
- const SoftStoreEntry &sentry
- ) const {
- softstoreKeyStoreEntryContext *entry = NULL;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::_keyStoreEntryBySoftStoreEntry - entry name=%s",
- myPrintable (sentry.name)
- ),
- Logger::Debug
- );
-
- QString serialized = _serializeSoftStoreEntry (sentry);
-
- softstorePKeyBase *pkey = new softstorePKeyBase (
- sentry,
- serialized,
- provider()
- );
-
- softstorePKeyContext *pkc = new softstorePKeyContext (provider ());
- pkc->setKey (pkey);
- PrivateKey privkey;
- privkey.change (pkc);
- KeyBundle key;
- key.setCertificateChainAndKey (
- sentry.chain,
- privkey
- );
-
- entry = new softstoreKeyStoreEntryContext (
- key,
- sentry,
- serialized,
- provider ()
- );
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreKeyStoreListContext::_keyStoreEntryBySoftStoreEntry - return entry=%p",
- (void *)entry
- ),
- Logger::Debug
- );
-
- return entry;
- }
-
- QString
- _escapeString (
- const QString &from
- ) const {
- QString to;
-
- foreach (const QChar &c, from) {
- if (c == '/' || c == '\\') {
- to += QString ().sprintf ("\\x%04x", c.unicode ());
- }
- else {
- to += c;
- }
- }
-
- return to;
- }
-
- QString
- _unescapeString (
- const QString &from
- ) const {
- QString to;
-
- for (int i=0;i<from.size ();i++) {
- QChar c = from[i];
-
- if (c == '\\') {
- to += QChar ((ushort)from.mid (i+2, 4).toInt (0, 16));
- i+=5;
- }
- else {
- to += c;
- }
- }
-
- return to;
- }
+ QString
+ _serializeSoftStoreEntry(
+ const SoftStoreEntry &entry
+ ) const
+ {
+ QString serialized;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::_serializeSoftStoreEntry - entry name=%s",
+ myPrintable(entry.name)
+ ),
+ Logger::Debug
+ );
+
+ serialized = QString().sprintf(
+ "qca-softstore/0/%s/%d/%s/%d/%d/x509chain/",
+ myPrintable(_escapeString(entry.name)),
+ entry.keyReferenceType,
+ myPrintable(_escapeString(entry.keyReference)),
+ entry.noPassphrase ? 1 : 0,
+ entry.unlockTimeout
+ );
+
+ QStringList list;
+ foreach (const Certificate &i, entry.chain) {
+ list += _escapeString(Base64().arrayToString(i.toDER()));
+ }
+
+ serialized.append(list.join("/"));
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::_serializeSoftStoreEntry - return serialized='%s'",
+ myPrintable(serialized)
+ ),
+ Logger::Debug
+ );
+
+ return serialized;
+ }
+
+ bool
+ _deserializeSoftStoreEntry(
+ const QString &serialized,
+ SoftStoreEntry &entry
+ ) const
+ {
+ bool ret = false;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::_deserializeSoftStoreEntry - entry from='%s'",
+ myPrintable(serialized)
+ ),
+ Logger::Debug
+ );
+
+ entry = SoftStoreEntry();
+
+ QStringList list = serialized.split("/");
+ int n = 0;
+
+ if (list.size() < 8) {
+ goto cleanup;
+ }
+
+ if (list[n++] != "qca-softstore") {
+ goto cleanup;
+ }
+
+ if (list[n++].toInt() != 0) {
+ goto cleanup;
+ }
+
+ entry.name = _unescapeString(list[n++]);
+ entry.keyReferenceType = (KeyType)list[n++].toInt();
+ entry.keyReference = _unescapeString(list[n++]);
+ entry.noPassphrase = list[n++].toInt() != 0;
+ entry.unlockTimeout = list[n++].toInt();
+ n++; // skip public key for now.
+
+ while (n < list.size()) {
+ Certificate cert = Certificate::fromDER(
+ Base64().stringToArray(_unescapeString(list[n++])).toByteArray()
+ );
+ if (cert.isNull()) {
+ goto cleanup;
+ }
+ entry.chain += cert;
+ }
+
+ ret = true;
+
+ cleanup:
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::_deserializeSoftStoreEntry - return ret=%d chain.size()=%d",
+ ret ? 1 : 0,
+ entry.chain.size()
+ ),
+ Logger::Debug
+ );
+
+ return ret;
+ }
+
+ softstoreKeyStoreEntryContext *
+ _keyStoreEntryBySoftStoreEntry(
+ const SoftStoreEntry &sentry
+ ) const
+ {
+ softstoreKeyStoreEntryContext *entry = NULL;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::_keyStoreEntryBySoftStoreEntry - entry name=%s",
+ myPrintable(sentry.name)
+ ),
+ Logger::Debug
+ );
+
+ QString serialized = _serializeSoftStoreEntry(sentry);
+
+ softstorePKeyBase *pkey = new softstorePKeyBase(
+ sentry,
+ serialized,
+ provider()
+ );
+
+ softstorePKeyContext *pkc = new softstorePKeyContext(provider());
+ pkc->setKey(pkey);
+ PrivateKey privkey;
+ privkey.change(pkc);
+ KeyBundle key;
+ key.setCertificateChainAndKey(
+ sentry.chain,
+ privkey
+ );
+
+ entry = new softstoreKeyStoreEntryContext(
+ key,
+ sentry,
+ serialized,
+ provider()
+ );
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreKeyStoreListContext::_keyStoreEntryBySoftStoreEntry - return entry=%p",
+ (void *)entry
+ ),
+ Logger::Debug
+ );
+
+ return entry;
+ }
+
+ QString
+ _escapeString(
+ const QString &from
+ ) const
+ {
+ QString to;
+
+ foreach (const QChar &c, from) {
+ if (c == '/' || c == '\\') {
+ to += QString().sprintf("\\x%04x", c.unicode());
+ } else {
+ to += c;
+ }
+ }
+
+ return to;
+ }
+
+ QString
+ _unescapeString(
+ const QString &from
+ ) const
+ {
+ QString to;
+
+ for (int i = 0; i < from.size(); i++) {
+ QChar c = from[i];
+
+ if (c == '\\') {
+ to += QChar((ushort)from.mid(i + 2, 4).toInt(0, 16));
+ i += 5;
+ } else {
+ to += c;
+ }
+ }
+
+ return to;
+ }
};
}
using namespace softstoreQCAPlugin;
class softstoreProvider : public Provider
{
private:
- static const int _CONFIG_MAX_ENTRIES;
+ static const int _CONFIG_MAX_ENTRIES;
- QVariantMap _config;
+ QVariantMap _config;
public:
- softstoreProvider () {
- }
+ softstoreProvider()
+ {
+ }
- ~softstoreProvider () {
- }
+ ~softstoreProvider()
+ {
+ }
public:
- virtual
- int
- qcaVersion() const {
- return QCA_VERSION;
- }
-
- virtual
- void
- init () {
- }
-
- virtual
- QString
- name () const {
- return "qca-softstore";
- }
-
- virtual
- QStringList
- features () const {
- QCA_logTextMessage (
- "softstoreProvider::features - entry/return",
- Logger::Debug
- );
-
- QStringList list;
- list += "pkey";
- list += "keystorelist";
- return list;
- }
-
- virtual
- Context *
- createContext (
- const QString &type
- ) {
- Provider::Context *context = NULL;
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreProvider::createContext - entry type='%s'",
- myPrintable (type)
- ),
- Logger::Debug
- );
-
- if (type == "keystorelist") {
- if (s_keyStoreList == NULL) {
- s_keyStoreList = new softstoreKeyStoreListContext (this);
- s_keyStoreList->_updateConfig (_config, _CONFIG_MAX_ENTRIES);
- }
- context = s_keyStoreList;
- }
-
- QCA_logTextMessage (
- QString ().sprintf (
- "softstoreProvider::createContext - return context=%p",
- (void *)context
- ),
- Logger::Debug
- );
-
- return context;
- }
-
- virtual
- QVariantMap
- defaultConfig () const {
- QVariantMap mytemplate;
-
- QCA_logTextMessage (
- "softstoreProvider::defaultConfig - entry/return",
- Logger::Debug
- );
-
- mytemplate["formtype"] = "http://affinix.com/qca/forms/qca-softstore#1.0";
- for (int i=0;i<_CONFIG_MAX_ENTRIES;i++) {
- mytemplate[QString ().sprintf ("entry_%02d_enabled", i)] = false;
- mytemplate[QString ().sprintf ("entry_%02d_name", i)] = "";
- mytemplate[QString ().sprintf ("entry_%02d_public_type", i)] = "";
- mytemplate[QString ().sprintf ("entry_%02d_private_type", i)] = "";
- mytemplate[QString ().sprintf ("entry_%02d_public", i)] = "";
- mytemplate[QString ().sprintf ("entry_%02d_private", i)] = "";
- mytemplate[QString ().sprintf ("entry_%02d_unlock_timeout", i)] = -1;
- mytemplate[QString ().sprintf ("entry_%02d_no_passphrase", i)] = false;
- }
-
- return mytemplate;
- }
-
- virtual
- void
- configChanged (const QVariantMap &config) {
-
- QCA_logTextMessage (
- "softstoreProvider::configChanged - entry",
- Logger::Debug
- );
-
- _config = config;
-
- if (s_keyStoreList != NULL) {
- s_keyStoreList->_updateConfig (_config, _CONFIG_MAX_ENTRIES);
- }
-
- QCA_logTextMessage (
- "softstoreProvider::configChanged - return",
- Logger::Debug
- );
- }
+ virtual
+ int
+ qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ virtual
+ void
+ init()
+ {
+ }
+
+ virtual
+ QString
+ name() const
+ {
+ return "qca-softstore";
+ }
+
+ virtual
+ QStringList
+ features() const
+ {
+ QCA_logTextMessage(
+ "softstoreProvider::features - entry/return",
+ Logger::Debug
+ );
+
+ QStringList list;
+ list += "pkey";
+ list += "keystorelist";
+ return list;
+ }
+
+ virtual
+ Context *
+ createContext(
+ const QString &type
+ )
+ {
+ Provider::Context *context = NULL;
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreProvider::createContext - entry type='%s'",
+ myPrintable(type)
+ ),
+ Logger::Debug
+ );
+
+ if (type == "keystorelist") {
+ if (s_keyStoreList == NULL) {
+ s_keyStoreList = new softstoreKeyStoreListContext(this);
+ s_keyStoreList->_updateConfig(_config, _CONFIG_MAX_ENTRIES);
+ }
+ context = s_keyStoreList;
+ }
+
+ QCA_logTextMessage(
+ QString().sprintf(
+ "softstoreProvider::createContext - return context=%p",
+ (void *)context
+ ),
+ Logger::Debug
+ );
+
+ return context;
+ }
+
+ virtual
+ QVariantMap
+ defaultConfig() const
+ {
+ QVariantMap mytemplate;
+
+ QCA_logTextMessage(
+ "softstoreProvider::defaultConfig - entry/return",
+ Logger::Debug
+ );
+
+ mytemplate["formtype"] = "http://affinix.com/qca/forms/qca-softstore#1.0";
+ for (int i = 0; i < _CONFIG_MAX_ENTRIES; i++) {
+ mytemplate[QString().sprintf("entry_%02d_enabled", i)] = false;
+ mytemplate[QString().sprintf("entry_%02d_name", i)] = "";
+ mytemplate[QString().sprintf("entry_%02d_public_type", i)] = "";
+ mytemplate[QString().sprintf("entry_%02d_private_type", i)] = "";
+ mytemplate[QString().sprintf("entry_%02d_public", i)] = "";
+ mytemplate[QString().sprintf("entry_%02d_private", i)] = "";
+ mytemplate[QString().sprintf("entry_%02d_unlock_timeout", i)] = -1;
+ mytemplate[QString().sprintf("entry_%02d_no_passphrase", i)] = false;
+ }
+
+ return mytemplate;
+ }
+
+ virtual
+ void
+ configChanged(const QVariantMap &config)
+ {
+
+ QCA_logTextMessage(
+ "softstoreProvider::configChanged - entry",
+ Logger::Debug
+ );
+
+ _config = config;
+
+ if (s_keyStoreList != NULL) {
+ s_keyStoreList->_updateConfig(_config, _CONFIG_MAX_ENTRIES);
+ }
+
+ QCA_logTextMessage(
+ "softstoreProvider::configChanged - return",
+ Logger::Debug
+ );
+ }
};
const int softstoreProvider::_CONFIG_MAX_ENTRIES = 50;
class softstorePlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { return new softstoreProvider; }
+ virtual Provider *createProvider()
+ {
+ return new softstoreProvider;
+ }
};
#include "qca-softstore.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_softstore, softstorePlugin)
#endif
diff --git a/plugins/qca-test/qca-test.cpp b/plugins/qca-test/qca-test.cpp
index 6023f6ab..38b8a49f 100644
--- a/plugins/qca-test/qca-test.cpp
+++ b/plugins/qca-test/qca-test.cpp
@@ -1,822 +1,818 @@
/*
* Copyright (C) 2007 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <QtCore>
using namespace QCA;
static char cert_pem[] =
- "-----BEGIN CERTIFICATE-----\n"
- "MIIBsTCCAVugAwIBAgIBADANBgkqhkiG9w0BAQUFADA4MRQwEgYDVQQDEwtUZXN0\n"
- "IENlcnQgMTELMAkGA1UEBhMCVVMxEzARBgNVBAoTClRlc3QgT3JnIDEwHhcNMDcw\n"
- "NjE5MjAzOTI4WhcNMTIwNjE5MjAzOTI4WjA4MRQwEgYDVQQDEwtUZXN0IENlcnQg\n"
- "MTELMAkGA1UEBhMCVVMxEzARBgNVBAoTClRlc3QgT3JnIDEwXDANBgkqhkiG9w0B\n"
- "AQEFAANLADBIAkEA3645RS/xBlWnjju6moaRYQuIDo7fwM+GxhE91HECLAg3Hnkr\n"
- "I+qx96VXd006olOn8MrkbjSqcTJ4LcDaCGI1YwIDAQABo1AwTjAdBgNVHQ4EFgQU\n"
- "nm5lNkkblHdoB0gLeh8mB6Ed+TMwDwYDVR0TAQH/BAUwAwIBADAcBgNVHREEFTAT\n"
- "gRF0ZXN0MUBleGFtcGxlLmNvbTANBgkqhkiG9w0BAQUFAANBAFTtXtwfYcJZBsXJ\n"
- "+Ckm9qbg7qR/XRERDzeR0yhHZE7F/jU5YQv7+iJL4l95iH9PkZNOk15Tu/Kzzekx\n"
- "6CTXzKA=\n"
- "-----END CERTIFICATE-----";
+ "-----BEGIN CERTIFICATE-----\n"
+ "MIIBsTCCAVugAwIBAgIBADANBgkqhkiG9w0BAQUFADA4MRQwEgYDVQQDEwtUZXN0\n"
+ "IENlcnQgMTELMAkGA1UEBhMCVVMxEzARBgNVBAoTClRlc3QgT3JnIDEwHhcNMDcw\n"
+ "NjE5MjAzOTI4WhcNMTIwNjE5MjAzOTI4WjA4MRQwEgYDVQQDEwtUZXN0IENlcnQg\n"
+ "MTELMAkGA1UEBhMCVVMxEzARBgNVBAoTClRlc3QgT3JnIDEwXDANBgkqhkiG9w0B\n"
+ "AQEFAANLADBIAkEA3645RS/xBlWnjju6moaRYQuIDo7fwM+GxhE91HECLAg3Hnkr\n"
+ "I+qx96VXd006olOn8MrkbjSqcTJ4LcDaCGI1YwIDAQABo1AwTjAdBgNVHQ4EFgQU\n"
+ "nm5lNkkblHdoB0gLeh8mB6Ed+TMwDwYDVR0TAQH/BAUwAwIBADAcBgNVHREEFTAT\n"
+ "gRF0ZXN0MUBleGFtcGxlLmNvbTANBgkqhkiG9w0BAQUFAANBAFTtXtwfYcJZBsXJ\n"
+ "+Ckm9qbg7qR/XRERDzeR0yhHZE7F/jU5YQv7+iJL4l95iH9PkZNOk15Tu/Kzzekx\n"
+ "6CTXzKA=\n"
+ "-----END CERTIFICATE-----";
static char key_n_dec[] =
- "1171510158037441543813157379806833168225785177834459013412026750"
- "9262193808059395366696241600386200064326196137137376912654785051"
- "560621331316573341676090723";
+ "1171510158037441543813157379806833168225785177834459013412026750"
+ "9262193808059395366696241600386200064326196137137376912654785051"
+ "560621331316573341676090723";
static char key_e_dec[] =
- "65537";
+ "65537";
//----------------------------------------------------------------------------
// TestProvider
//----------------------------------------------------------------------------
class TestProvider : public Provider
{
public:
- TestProvider()
- {
- appendPluginDiagnosticText("TestProvider constructed\n");
- }
-
- void init()
- {
- appendPluginDiagnosticText("TestProvider initialized\n");
- }
-
- void deinit()
- {
- appendPluginDiagnosticText("TestProvider deinitialized\n");
- }
-
- ~TestProvider()
- {
- appendPluginDiagnosticText("TestProvider destructed\n");
- }
-
- int version() const
- {
- return 0x010203; // 1.2.3
- }
-
- int qcaVersion() const
- {
- return QCA_VERSION;
- }
-
- QString name() const
- {
- return "qca-test";
- }
-
- QStringList features() const
- {
- QStringList list;
- list += "keystorelist";
- return list;
- }
-
- Context *createContext(const QString &type);
+ TestProvider()
+ {
+ appendPluginDiagnosticText("TestProvider constructed\n");
+ }
+
+ void init()
+ {
+ appendPluginDiagnosticText("TestProvider initialized\n");
+ }
+
+ void deinit()
+ {
+ appendPluginDiagnosticText("TestProvider deinitialized\n");
+ }
+
+ ~TestProvider()
+ {
+ appendPluginDiagnosticText("TestProvider destructed\n");
+ }
+
+ int version() const
+ {
+ return 0x010203; // 1.2.3
+ }
+
+ int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ QString name() const
+ {
+ return "qca-test";
+ }
+
+ QStringList features() const
+ {
+ QStringList list;
+ list += "keystorelist";
+ return list;
+ }
+
+ Context *createContext(const QString &type);
};
//----------------------------------------------------------------------------
// TestData
//----------------------------------------------------------------------------
class TestKeyStore
{
public:
- int contextId;
- KeyStore::Type type;
- QString storeId;
- QString name;
- bool readOnly;
- bool avail; // for simplicity, all items share this global toggle
-
- QList<KeyBundle> certs;
-
- TestKeyStore() :
- contextId(-1),
- type(KeyStore::SmartCard),
- readOnly(true),
- avail(true)
- {
- }
+ int contextId;
+ KeyStore::Type type;
+ QString storeId;
+ QString name;
+ bool readOnly;
+ bool avail; // for simplicity, all items share this global toggle
+
+ QList<KeyBundle> certs;
+
+ TestKeyStore() :
+ contextId(-1),
+ type(KeyStore::SmartCard),
+ readOnly(true),
+ avail(true)
+ {
+ }
};
class TestData
{
public:
- int context_at;
- QList<TestKeyStore> stores;
+ int context_at;
+ QList<TestKeyStore> stores;
- TestData() :
- context_at(0)
- {
- }
+ TestData() :
+ context_at(0)
+ {
+ }
};
//----------------------------------------------------------------------------
// TestRSAContext
//----------------------------------------------------------------------------
static KeyStoreEntry make_entry(Provider *p, TestKeyStore *store);
class TestRSAContext : public RSAContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- bool priv;
- TestKeyStore *store;
-
- TestRSAContext(Provider *p) :
- RSAContext(p),
- priv(true),
- store(0)
- {
- }
-
- TestRSAContext(const TestRSAContext &from) :
- RSAContext(from),
- priv(from.priv),
- store(from.store)
- {
- }
-
- Context *clone() const
- {
- return new TestRSAContext(*this);
- }
-
- virtual bool isNull() const
- {
- return false;
- }
-
- virtual PKey::Type type() const
- {
- return PKey::RSA;
- }
-
- virtual bool isPrivate() const
- {
- return priv;
- }
-
- virtual bool canExport() const
- {
- return false;
- }
-
- virtual void convertToPublic()
- {
- priv = false;
- }
-
- virtual int bits() const
- {
- return 2048;
- }
-
- virtual void startSign(SignatureAlgorithm alg, SignatureFormat format)
- {
- Q_UNUSED(alg);
- Q_UNUSED(format);
- }
-
- virtual void update(const MemoryRegion &in)
- {
- Q_UNUSED(in);
- }
-
- virtual QByteArray endSign()
- {
- if(!store)
- return QByteArray();
-
- while(store->contextId == -1 || !store->avail)
- {
- KeyStoreInfo info(store->type, store->storeId, store->name);
- KeyStoreEntry entry = make_entry(provider(), store);
-
- TokenAsker asker;
- asker.ask(info, entry, 0);
- asker.waitForResponse();
- if(!asker.accepted())
- return QByteArray();
- }
-
- return "foobar";
- }
-
- virtual void createPrivate(int bits, int exp, bool block)
- {
- Q_UNUSED(bits);
- Q_UNUSED(exp);
- Q_UNUSED(block);
- }
-
- virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d)
- {
- Q_UNUSED(n);
- Q_UNUSED(e);
- Q_UNUSED(p);
- Q_UNUSED(q);
- Q_UNUSED(d);
- }
-
- virtual void createPublic(const BigInteger &n, const BigInteger &e)
- {
- Q_UNUSED(n);
- Q_UNUSED(e);
- }
-
- virtual BigInteger n() const
- {
- return BigInteger(QString(key_n_dec));
- }
-
- virtual BigInteger e() const
- {
- return BigInteger(QString(key_e_dec));
- }
-
- virtual BigInteger p() const
- {
- return BigInteger();
- }
-
- virtual BigInteger q() const
- {
- return BigInteger();
- }
-
- virtual BigInteger d() const
- {
- return BigInteger();
- }
+ bool priv;
+ TestKeyStore *store;
+
+ TestRSAContext(Provider *p) :
+ RSAContext(p),
+ priv(true),
+ store(0)
+ {
+ }
+
+ TestRSAContext(const TestRSAContext &from) :
+ RSAContext(from),
+ priv(from.priv),
+ store(from.store)
+ {
+ }
+
+ Context *clone() const
+ {
+ return new TestRSAContext(*this);
+ }
+
+ virtual bool isNull() const
+ {
+ return false;
+ }
+
+ virtual PKey::Type type() const
+ {
+ return PKey::RSA;
+ }
+
+ virtual bool isPrivate() const
+ {
+ return priv;
+ }
+
+ virtual bool canExport() const
+ {
+ return false;
+ }
+
+ virtual void convertToPublic()
+ {
+ priv = false;
+ }
+
+ virtual int bits() const
+ {
+ return 2048;
+ }
+
+ virtual void startSign(SignatureAlgorithm alg, SignatureFormat format)
+ {
+ Q_UNUSED(alg);
+ Q_UNUSED(format);
+ }
+
+ virtual void update(const MemoryRegion &in)
+ {
+ Q_UNUSED(in);
+ }
+
+ virtual QByteArray endSign()
+ {
+ if (!store) {
+ return QByteArray();
+ }
+
+ while (store->contextId == -1 || !store->avail) {
+ KeyStoreInfo info(store->type, store->storeId, store->name);
+ KeyStoreEntry entry = make_entry(provider(), store);
+
+ TokenAsker asker;
+ asker.ask(info, entry, 0);
+ asker.waitForResponse();
+ if (!asker.accepted()) {
+ return QByteArray();
+ }
+ }
+
+ return "foobar";
+ }
+
+ virtual void createPrivate(int bits, int exp, bool block)
+ {
+ Q_UNUSED(bits);
+ Q_UNUSED(exp);
+ Q_UNUSED(block);
+ }
+
+ virtual void createPrivate(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d)
+ {
+ Q_UNUSED(n);
+ Q_UNUSED(e);
+ Q_UNUSED(p);
+ Q_UNUSED(q);
+ Q_UNUSED(d);
+ }
+
+ virtual void createPublic(const BigInteger &n, const BigInteger &e)
+ {
+ Q_UNUSED(n);
+ Q_UNUSED(e);
+ }
+
+ virtual BigInteger n() const
+ {
+ return BigInteger(QString(key_n_dec));
+ }
+
+ virtual BigInteger e() const
+ {
+ return BigInteger(QString(key_e_dec));
+ }
+
+ virtual BigInteger p() const
+ {
+ return BigInteger();
+ }
+
+ virtual BigInteger q() const
+ {
+ return BigInteger();
+ }
+
+ virtual BigInteger d() const
+ {
+ return BigInteger();
+ }
};
//----------------------------------------------------------------------------
// TestPKeyContext
//----------------------------------------------------------------------------
class TestPKeyContext : public PKeyContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- TestRSAContext *_key;
-
- TestPKeyContext(Provider *p) :
- PKeyContext(p),
- _key(0)
- {
- }
-
- TestPKeyContext(const TestPKeyContext &from) :
- PKeyContext(from),
- _key(0)
- {
- if(from._key)
- _key = (TestRSAContext *)from._key->clone();
- }
-
- ~TestPKeyContext()
- {
- delete _key;
- }
-
- Context *clone() const
- {
- return new TestPKeyContext(*this);
- }
-
- virtual QList<PKey::Type> supportedTypes() const
- {
- QList<PKey::Type> list;
- list += PKey::RSA;
- return list;
- }
-
- virtual QList<PKey::Type> supportedIOTypes() const
- {
- return QList<PKey::Type>();
- }
-
- virtual QList<PBEAlgorithm> supportedPBEAlgorithms() const
- {
- return QList<PBEAlgorithm>();
- }
-
- virtual PKeyBase *key()
- {
- return _key;
- }
-
- virtual const PKeyBase *key() const
- {
- return _key;
- }
-
- virtual void setKey(PKeyBase *key)
- {
- delete _key;
- _key = (TestRSAContext *)key;
- }
-
- virtual bool importKey(const PKeyBase *key)
- {
- Q_UNUSED(key);
- return false;
- }
+ TestRSAContext *_key;
+
+ TestPKeyContext(Provider *p) :
+ PKeyContext(p),
+ _key(0)
+ {
+ }
+
+ TestPKeyContext(const TestPKeyContext &from) :
+ PKeyContext(from),
+ _key(0)
+ {
+ if (from._key) {
+ _key = (TestRSAContext *)from._key->clone();
+ }
+ }
+
+ ~TestPKeyContext()
+ {
+ delete _key;
+ }
+
+ Context *clone() const
+ {
+ return new TestPKeyContext(*this);
+ }
+
+ virtual QList<PKey::Type> supportedTypes() const
+ {
+ QList<PKey::Type> list;
+ list += PKey::RSA;
+ return list;
+ }
+
+ virtual QList<PKey::Type> supportedIOTypes() const
+ {
+ return QList<PKey::Type>();
+ }
+
+ virtual QList<PBEAlgorithm> supportedPBEAlgorithms() const
+ {
+ return QList<PBEAlgorithm>();
+ }
+
+ virtual PKeyBase *key()
+ {
+ return _key;
+ }
+
+ virtual const PKeyBase *key() const
+ {
+ return _key;
+ }
+
+ virtual void setKey(PKeyBase *key)
+ {
+ delete _key;
+ _key = (TestRSAContext *)key;
+ }
+
+ virtual bool importKey(const PKeyBase *key)
+ {
+ Q_UNUSED(key);
+ return false;
+ }
};
//----------------------------------------------------------------------------
// TestCertContext
//----------------------------------------------------------------------------
class TestCertContext : public CertContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- CertContextProps _props;
-
- TestCertContext(Provider *p) :
- CertContext(p)
- {
- }
-
- Context *clone() const
- {
- return new TestCertContext(*this);
- }
-
- virtual QByteArray toDER() const
- {
- QStringList lines = toPEM().split('\n');
- lines.removeFirst();
- lines.removeLast();
- QString enc = lines.join("");
- return Base64().stringToArray(enc).toByteArray();
- }
-
- virtual QString toPEM() const
- {
- return QString(cert_pem);
- }
-
- virtual ConvertResult fromDER(const QByteArray &a)
- {
- Q_UNUSED(a);
- return ErrorDecode;
- }
-
- virtual ConvertResult fromPEM(const QString &s)
- {
- Q_UNUSED(s);
- return ErrorDecode;
- }
-
- virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv)
- {
- Q_UNUSED(opts);
- Q_UNUSED(priv);
- return false;
- }
-
- virtual const CertContextProps *props() const
- {
- return &_props;
- }
-
- virtual bool compare(const CertContext *other) const
- {
- Q_UNUSED(other);
- return false;
- }
-
- virtual PKeyContext *subjectPublicKey() const
- {
- TestRSAContext *rsa1 = new TestRSAContext(provider());
- rsa1->priv = false;
- TestPKeyContext *kc1 = new TestPKeyContext(provider());
- kc1->setKey(rsa1);
- return kc1;
- }
-
- virtual bool isIssuerOf(const CertContext *other) const
- {
- Q_UNUSED(other);
- return false;
- }
-
- virtual Validity validate(const QList<CertContext*> &trusted, const QList<CertContext*> &untrusted, const QList<CRLContext*> &crls, UsageMode u, ValidateFlags vf) const
- {
- Q_UNUSED(trusted);
- Q_UNUSED(untrusted);
- Q_UNUSED(crls);
- Q_UNUSED(u);
- Q_UNUSED(vf);
- return ErrorValidityUnknown;
- }
-
- virtual Validity validate_chain(const QList<CertContext*> &chain, const QList<CertContext*> &trusted, const QList<CRLContext*> &crls, UsageMode u, ValidateFlags vf) const
- {
- Q_UNUSED(chain);
- Q_UNUSED(trusted);
- Q_UNUSED(crls);
- Q_UNUSED(u);
- Q_UNUSED(vf);
- return ErrorValidityUnknown;
- }
+ CertContextProps _props;
+
+ TestCertContext(Provider *p) :
+ CertContext(p)
+ {
+ }
+
+ Context *clone() const
+ {
+ return new TestCertContext(*this);
+ }
+
+ virtual QByteArray toDER() const
+ {
+ QStringList lines = toPEM().split('\n');
+ lines.removeFirst();
+ lines.removeLast();
+ QString enc = lines.join("");
+ return Base64().stringToArray(enc).toByteArray();
+ }
+
+ virtual QString toPEM() const
+ {
+ return QString(cert_pem);
+ }
+
+ virtual ConvertResult fromDER(const QByteArray &a)
+ {
+ Q_UNUSED(a);
+ return ErrorDecode;
+ }
+
+ virtual ConvertResult fromPEM(const QString &s)
+ {
+ Q_UNUSED(s);
+ return ErrorDecode;
+ }
+
+ virtual bool createSelfSigned(const CertificateOptions &opts, const PKeyContext &priv)
+ {
+ Q_UNUSED(opts);
+ Q_UNUSED(priv);
+ return false;
+ }
+
+ virtual const CertContextProps *props() const
+ {
+ return &_props;
+ }
+
+ virtual bool compare(const CertContext *other) const
+ {
+ Q_UNUSED(other);
+ return false;
+ }
+
+ virtual PKeyContext *subjectPublicKey() const
+ {
+ TestRSAContext *rsa1 = new TestRSAContext(provider());
+ rsa1->priv = false;
+ TestPKeyContext *kc1 = new TestPKeyContext(provider());
+ kc1->setKey(rsa1);
+ return kc1;
+ }
+
+ virtual bool isIssuerOf(const CertContext *other) const
+ {
+ Q_UNUSED(other);
+ return false;
+ }
+
+ virtual Validity validate(const QList<CertContext *> &trusted, const QList<CertContext *> &untrusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const
+ {
+ Q_UNUSED(trusted);
+ Q_UNUSED(untrusted);
+ Q_UNUSED(crls);
+ Q_UNUSED(u);
+ Q_UNUSED(vf);
+ return ErrorValidityUnknown;
+ }
+
+ virtual Validity validate_chain(const QList<CertContext *> &chain, const QList<CertContext *> &trusted, const QList<CRLContext *> &crls, UsageMode u, ValidateFlags vf) const
+ {
+ Q_UNUSED(chain);
+ Q_UNUSED(trusted);
+ Q_UNUSED(crls);
+ Q_UNUSED(u);
+ Q_UNUSED(vf);
+ return ErrorValidityUnknown;
+ }
};
//----------------------------------------------------------------------------
// TestKeyStoreEntryContext
//----------------------------------------------------------------------------
class TestKeyStoreEntryContext : public KeyStoreEntryContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- QString _id, _name, _storeId, _storeName;
- KeyBundle kb;
- TestKeyStore *store;
-
- TestKeyStoreEntryContext(Provider *p) :
- KeyStoreEntryContext(p)
- {
- }
-
- virtual Context *clone() const
- {
- return new TestKeyStoreEntryContext(*this);
- }
-
- virtual KeyStoreEntry::Type type() const
- {
- return KeyStoreEntry::TypeKeyBundle;
- }
-
- virtual QString id() const
- {
- return _id;
- }
-
- virtual QString name() const
- {
- return _name;
- }
-
- virtual QString storeId() const
- {
- return _storeId;
- }
-
- virtual QString storeName() const
- {
- return _storeName;
- }
-
- virtual bool isAvailable() const
- {
- return store->avail;
- }
-
- virtual QString serialize() const
- {
- return QString("qca-test-1/fake_serialized");
- }
-
- virtual KeyBundle keyBundle() const
- {
- return kb;
- }
-
- virtual bool ensureAccess()
- {
- return true;
- }
+ QString _id, _name, _storeId, _storeName;
+ KeyBundle kb;
+ TestKeyStore *store;
+
+ TestKeyStoreEntryContext(Provider *p) :
+ KeyStoreEntryContext(p)
+ {
+ }
+
+ virtual Context *clone() const
+ {
+ return new TestKeyStoreEntryContext(*this);
+ }
+
+ virtual KeyStoreEntry::Type type() const
+ {
+ return KeyStoreEntry::TypeKeyBundle;
+ }
+
+ virtual QString id() const
+ {
+ return _id;
+ }
+
+ virtual QString name() const
+ {
+ return _name;
+ }
+
+ virtual QString storeId() const
+ {
+ return _storeId;
+ }
+
+ virtual QString storeName() const
+ {
+ return _storeName;
+ }
+
+ virtual bool isAvailable() const
+ {
+ return store->avail;
+ }
+
+ virtual QString serialize() const
+ {
+ return QString("qca-test-1/fake_serialized");
+ }
+
+ virtual KeyBundle keyBundle() const
+ {
+ return kb;
+ }
+
+ virtual bool ensureAccess()
+ {
+ return true;
+ }
};
KeyStoreEntry make_entry(Provider *p, TestKeyStore *store)
{
- KeyStoreEntry entry;
- TestKeyStoreEntryContext *kse = new TestKeyStoreEntryContext(p);
- kse->_id = QString::number(0);
- kse->_name = store->certs[0].certificateChain().primary().commonName();
- kse->_storeId = store->storeId;
- kse->_storeName = store->name;
- kse->kb = store->certs[0];
- kse->store = store;
- entry.change(kse);
- return entry;
+ KeyStoreEntry entry;
+ TestKeyStoreEntryContext *kse = new TestKeyStoreEntryContext(p);
+ kse->_id = QString::number(0);
+ kse->_name = store->certs[0].certificateChain().primary().commonName();
+ kse->_storeId = store->storeId;
+ kse->_storeName = store->name;
+ kse->kb = store->certs[0];
+ kse->store = store;
+ entry.change(kse);
+ return entry;
}
//----------------------------------------------------------------------------
// TestKeyStoreListContext
//----------------------------------------------------------------------------
class TestKeyStoreListContext : public KeyStoreListContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- TestData data;
- int step;
- QTimer t;
- bool first;
- int next_id;
-
- TestKeyStoreListContext(Provider *p) :
- KeyStoreListContext(p),
- t(this)
- {
- step = 0;
- next_id = 1;
-
- KeyBundle cert1;
- Certificate pub1;
- TestCertContext *cc1 = new TestCertContext(provider());
- cc1->_props.subject += CertificateInfoPair(CertificateInfoType(CommonName), "Test Cert 1");
- pub1.change(cc1);
- PrivateKey sec1;
- TestRSAContext *rsa1 = new TestRSAContext(provider());
- TestPKeyContext *kc1 = new TestPKeyContext(provider());
- kc1->setKey(rsa1);
- sec1.change(kc1);
- cert1.setCertificateChainAndKey(pub1, sec1);
-
- TestKeyStore ks1;
- ks1.storeId = "store1";
- ks1.name = "Test Store 1";
- ks1.certs += cert1;
- ks1.avail = false;
- data.stores += ks1;
-
- TestKeyStore ks2;
- ks2.storeId = "store2";
- ks2.name = "Test Store 2";
- ks2.readOnly = false;
- data.stores += ks2;
-
- rsa1->store = &data.stores[0];
-
- connect(&t, SIGNAL(timeout()), SLOT(do_step()));
- }
-
- int findStore(int contextId) const
- {
- for(int n = 0; n < data.stores.count(); ++n)
- {
- if(data.stores[n].contextId == contextId)
- return n;
- }
- return -1;
- }
-
- virtual Context *clone() const
- {
- return 0;
- }
-
- virtual void start()
- {
- first = true;
- emit diagnosticText("qca-test: TestKeyStoreListContext started\n");
- t.start(2000);
- }
-
- virtual void setUpdatesEnabled(bool enabled)
- {
- Q_UNUSED(enabled);
- }
-
- virtual QList<int> keyStores()
- {
- QList<int> list;
- for(int n = 0; n < data.stores.count(); ++n)
- {
- int id = data.stores[n].contextId;
- if(id != -1)
- list += id;
- }
- return list;
- }
-
- virtual KeyStore::Type type(int id) const
- {
- int at = findStore(id);
- if(at == -1)
- return KeyStore::SmartCard;
- return data.stores[at].type;
- }
-
- virtual QString storeId(int id) const
- {
- int at = findStore(id);
- if(at == -1)
- return QString();
- return data.stores[at].storeId;
- }
-
- virtual QString name(int id) const
- {
- int at = findStore(id);
- if(at == -1)
- return QString();
- return data.stores[at].name;
- }
-
- virtual bool isReadOnly(int id) const
- {
- int at = findStore(id);
- if(at == -1)
- return true;
- return data.stores[at].readOnly;
- }
-
- virtual QList<KeyStoreEntry::Type> entryTypes(int id) const
- {
- Q_UNUSED(id);
- QList<KeyStoreEntry::Type> list;
- list += KeyStoreEntry::TypeKeyBundle;
- return list;
- }
-
- virtual QList<KeyStoreEntryContext*> entryList(int id)
- {
- QList<KeyStoreEntryContext*> out;
- int at = findStore(id);
- if(at == -1)
- return out;
- TestKeyStore &store = data.stores[at];
- for(int n = 0; n < store.certs.count(); ++n)
- {
- TestKeyStoreEntryContext *kse = new TestKeyStoreEntryContext(provider());
- kse->_id = QString::number(n);
- kse->_name = store.certs[n].certificateChain().primary().commonName();
- kse->_storeId = store.storeId;
- kse->_storeName = store.name;
- kse->kb = store.certs[n];
- kse->store = &store;
- out += kse;
- }
- return out;
- }
-
- virtual KeyStoreEntryContext *entryPassive(const QString &serialized)
- {
- if(serialized == "qca-test-1/fake_serialized")
- {
- TestKeyStore &store = data.stores[0];
- TestKeyStoreEntryContext *kse = new TestKeyStoreEntryContext(provider());
- kse->_id = QString::number(0);
- kse->_name = store.certs[0].certificateChain().primary().commonName();
- kse->_storeId = store.storeId;
- kse->_storeName = store.name;
- kse->kb = store.certs[0];
- kse->store = &store;
- return kse;
- }
- else
- return 0;
- }
-
- virtual QString writeEntry(int id, const KeyBundle &kb)
- {
- int at = findStore(id);
- if(at == -1)
- return QString();
- if(data.stores[at].readOnly)
- return QString();
- data.stores[at].certs += kb;
- return QString::number(data.stores[at].certs.count() - 1);
- }
-
- virtual bool removeEntry(int id, const QString &entryId)
- {
- int at = findStore(id);
- if(at == -1)
- return false;
- if(data.stores[at].readOnly)
- return false;
- int index = entryId.toInt();
- if(index < 0 || index >= data.stores[at].certs.count())
- return false;
- data.stores[at].certs.removeAt(index);
- return true;
- }
+ TestData data;
+ int step;
+ QTimer t;
+ bool first;
+ int next_id;
+
+ TestKeyStoreListContext(Provider *p) :
+ KeyStoreListContext(p),
+ t(this)
+ {
+ step = 0;
+ next_id = 1;
+
+ KeyBundle cert1;
+ Certificate pub1;
+ TestCertContext *cc1 = new TestCertContext(provider());
+ cc1->_props.subject += CertificateInfoPair(CertificateInfoType(CommonName), "Test Cert 1");
+ pub1.change(cc1);
+ PrivateKey sec1;
+ TestRSAContext *rsa1 = new TestRSAContext(provider());
+ TestPKeyContext *kc1 = new TestPKeyContext(provider());
+ kc1->setKey(rsa1);
+ sec1.change(kc1);
+ cert1.setCertificateChainAndKey(pub1, sec1);
+
+ TestKeyStore ks1;
+ ks1.storeId = "store1";
+ ks1.name = "Test Store 1";
+ ks1.certs += cert1;
+ ks1.avail = false;
+ data.stores += ks1;
+
+ TestKeyStore ks2;
+ ks2.storeId = "store2";
+ ks2.name = "Test Store 2";
+ ks2.readOnly = false;
+ data.stores += ks2;
+
+ rsa1->store = &data.stores[0];
+
+ connect(&t, SIGNAL(timeout()), SLOT(do_step()));
+ }
+
+ int findStore(int contextId) const
+ {
+ for (int n = 0; n < data.stores.count(); ++n) {
+ if (data.stores[n].contextId == contextId) {
+ return n;
+ }
+ }
+ return -1;
+ }
+
+ virtual Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual void start()
+ {
+ first = true;
+ emit diagnosticText("qca-test: TestKeyStoreListContext started\n");
+ t.start(2000);
+ }
+
+ virtual void setUpdatesEnabled(bool enabled)
+ {
+ Q_UNUSED(enabled);
+ }
+
+ virtual QList<int> keyStores()
+ {
+ QList<int> list;
+ for (int n = 0; n < data.stores.count(); ++n) {
+ int id = data.stores[n].contextId;
+ if (id != -1) {
+ list += id;
+ }
+ }
+ return list;
+ }
+
+ virtual KeyStore::Type type(int id) const
+ {
+ int at = findStore(id);
+ if (at == -1) {
+ return KeyStore::SmartCard;
+ }
+ return data.stores[at].type;
+ }
+
+ virtual QString storeId(int id) const
+ {
+ int at = findStore(id);
+ if (at == -1) {
+ return QString();
+ }
+ return data.stores[at].storeId;
+ }
+
+ virtual QString name(int id) const
+ {
+ int at = findStore(id);
+ if (at == -1) {
+ return QString();
+ }
+ return data.stores[at].name;
+ }
+
+ virtual bool isReadOnly(int id) const
+ {
+ int at = findStore(id);
+ if (at == -1) {
+ return true;
+ }
+ return data.stores[at].readOnly;
+ }
+
+ virtual QList<KeyStoreEntry::Type> entryTypes(int id) const
+ {
+ Q_UNUSED(id);
+ QList<KeyStoreEntry::Type> list;
+ list += KeyStoreEntry::TypeKeyBundle;
+ return list;
+ }
+
+ virtual QList<KeyStoreEntryContext *> entryList(int id)
+ {
+ QList<KeyStoreEntryContext *> out;
+ int at = findStore(id);
+ if (at == -1) {
+ return out;
+ }
+ TestKeyStore &store = data.stores[at];
+ for (int n = 0; n < store.certs.count(); ++n) {
+ TestKeyStoreEntryContext *kse = new TestKeyStoreEntryContext(provider());
+ kse->_id = QString::number(n);
+ kse->_name = store.certs[n].certificateChain().primary().commonName();
+ kse->_storeId = store.storeId;
+ kse->_storeName = store.name;
+ kse->kb = store.certs[n];
+ kse->store = &store;
+ out += kse;
+ }
+ return out;
+ }
+
+ virtual KeyStoreEntryContext *entryPassive(const QString &serialized)
+ {
+ if (serialized == "qca-test-1/fake_serialized") {
+ TestKeyStore &store = data.stores[0];
+ TestKeyStoreEntryContext *kse = new TestKeyStoreEntryContext(provider());
+ kse->_id = QString::number(0);
+ kse->_name = store.certs[0].certificateChain().primary().commonName();
+ kse->_storeId = store.storeId;
+ kse->_storeName = store.name;
+ kse->kb = store.certs[0];
+ kse->store = &store;
+ return kse;
+ } else {
+ return 0;
+ }
+ }
+
+ virtual QString writeEntry(int id, const KeyBundle &kb)
+ {
+ int at = findStore(id);
+ if (at == -1) {
+ return QString();
+ }
+ if (data.stores[at].readOnly) {
+ return QString();
+ }
+ data.stores[at].certs += kb;
+ return QString::number(data.stores[at].certs.count() - 1);
+ }
+
+ virtual bool removeEntry(int id, const QString &entryId)
+ {
+ int at = findStore(id);
+ if (at == -1) {
+ return false;
+ }
+ if (data.stores[at].readOnly) {
+ return false;
+ }
+ int index = entryId.toInt();
+ if (index < 0 || index >= data.stores[at].certs.count()) {
+ return false;
+ }
+ data.stores[at].certs.removeAt(index);
+ return true;
+ }
private slots:
- void do_step()
- {
- emit diagnosticText(QString("qca-test: TestKeyStoreListContext do_step %1\n").arg(step));
-
- if(step == 0)
- {
- // make first store available
- data.stores[0].contextId = next_id++;
- if(first)
- {
- first = false;
- emit busyEnd();
- }
- else
- emit updated();
- }
- else if(step == 1)
- {
- // make second store available
- data.stores[1].contextId = next_id++;
- emit updated();
- }
- else if(step == 2)
- {
- // make items in the first store available
- data.stores[0].avail = true;
- emit storeUpdated(data.stores[0].contextId);
- }
- else if(step == 3)
- {
- // make the first store unavailable
- data.stores[0].contextId = -1;
- emit updated();
- }
- else if(step == 4)
- {
- // make the first store available
- data.stores[0].contextId = next_id++;
- emit updated();
- }
- else if(step == 5)
- {
- // make the second store unavailable
- data.stores[1].contextId = -1;
- emit updated();
- }
- else if(step == 6)
- {
- // make the first store unavailable
- data.stores[0].contextId = -1;
- emit updated();
- }
- else if(step == 7)
- {
- // do it all over again in 10 seconds
- // (2 seconds before, 6 seconds here, 2 seconds after)
- t.start(6000);
- }
- else
- {
- step = 0;
- data.stores[0].avail = false;
-
- // set interval to 2 seconds
- t.start(2000);
- return;
- }
-
- ++step;
- }
+ void do_step()
+ {
+ emit diagnosticText(QString("qca-test: TestKeyStoreListContext do_step %1\n").arg(step));
+
+ if (step == 0) {
+ // make first store available
+ data.stores[0].contextId = next_id++;
+ if (first) {
+ first = false;
+ emit busyEnd();
+ } else {
+ emit updated();
+ }
+ } else if (step == 1) {
+ // make second store available
+ data.stores[1].contextId = next_id++;
+ emit updated();
+ } else if (step == 2) {
+ // make items in the first store available
+ data.stores[0].avail = true;
+ emit storeUpdated(data.stores[0].contextId);
+ } else if (step == 3) {
+ // make the first store unavailable
+ data.stores[0].contextId = -1;
+ emit updated();
+ } else if (step == 4) {
+ // make the first store available
+ data.stores[0].contextId = next_id++;
+ emit updated();
+ } else if (step == 5) {
+ // make the second store unavailable
+ data.stores[1].contextId = -1;
+ emit updated();
+ } else if (step == 6) {
+ // make the first store unavailable
+ data.stores[0].contextId = -1;
+ emit updated();
+ } else if (step == 7) {
+ // do it all over again in 10 seconds
+ // (2 seconds before, 6 seconds here, 2 seconds after)
+ t.start(6000);
+ } else {
+ step = 0;
+ data.stores[0].avail = false;
+
+ // set interval to 2 seconds
+ t.start(2000);
+ return;
+ }
+
+ ++step;
+ }
};
//----------------------------------------------------------------------------
// TestProvider
//----------------------------------------------------------------------------
Provider::Context *TestProvider::createContext(const QString &type)
{
- if(type == "keystorelist")
- return new TestKeyStoreListContext(this);
- else
- return 0;
+ if (type == "keystorelist") {
+ return new TestKeyStoreListContext(this);
+ } else {
+ return 0;
+ }
}
//----------------------------------------------------------------------------
// TestPlugin
//----------------------------------------------------------------------------
class TestPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { return new TestProvider; }
+ virtual Provider *createProvider()
+ {
+ return new TestProvider;
+ }
};
#include "qca-test.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_test, TestPlugin);
#endif
diff --git a/plugins/qca-wincrypto/qca-wincrypto.cpp b/plugins/qca-wincrypto/qca-wincrypto.cpp
index 1aa87e17..b5281b13 100644
--- a/plugins/qca-wincrypto/qca-wincrypto.cpp
+++ b/plugins/qca-wincrypto/qca-wincrypto.cpp
@@ -1,120 +1,125 @@
/*
* Copyright (C) 2008 Michael Leupold <lemma@confuego.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <QtPlugin>
#include <qstringlist.h>
#ifdef Q_OS_WIN32
#include <wincrypt.h>
//-----------------------------------------------------------
class WinCryptoRandomContext : public QCA::RandomContext
{
public:
- WinCryptoRandomContext(QCA::Provider *p) : RandomContext(p)
- {
- }
-
- Context *clone() const
- {
- return new WinCryptoRandomContext(*this);
- }
-
- QCA::SecureArray nextBytes(int size)
- {
- QCA::SecureArray buf(size);
- HCRYPTPROV hProv;
-
- /* FIXME: currently loop while there's an error. */
- while (true)
- {
- // acquire the crypto context
- if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL,
- CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) continue;
-
- if (CryptGenRandom(hProv, static_cast<DWORD>(size), (BYTE*)buf.data())) {
- break;
- }
- }
-
- // release the crypto context
- CryptReleaseContext(hProv, 0);
-
- return buf;
- }
+ WinCryptoRandomContext(QCA::Provider *p) : RandomContext(p)
+ {
+ }
+
+ Context *clone() const
+ {
+ return new WinCryptoRandomContext(*this);
+ }
+
+ QCA::SecureArray nextBytes(int size)
+ {
+ QCA::SecureArray buf(size);
+ HCRYPTPROV hProv;
+
+ /* FIXME: currently loop while there's an error. */
+ while (true) {
+ // acquire the crypto context
+ if (!CryptAcquireContext(&hProv, NULL, NULL, PROV_RSA_FULL,
+ CRYPT_VERIFYCONTEXT | CRYPT_SILENT)) {
+ continue;
+ }
+
+ if (CryptGenRandom(hProv, static_cast<DWORD>(size), (BYTE *)buf.data())) {
+ break;
+ }
+ }
+
+ // release the crypto context
+ CryptReleaseContext(hProv, 0);
+
+ return buf;
+ }
};
//-----------------------------------------------------------
class WinCryptoProvider : public QCA::Provider
{
public:
- void init()
- {
- }
-
- ~WinCryptoProvider()
- {
- }
-
- int qcaVersion() const
- {
- return QCA_VERSION;
- }
-
- QString name() const
- {
- return "qca-wincrypto";
- }
-
- QStringList features() const
- {
- QStringList list;
- list += "random";
- return list;
- }
-
- Context *createContext(const QString &type)
- {
- if ( type == "random" )
- return new WinCryptoRandomContext(this);
- else
- return 0;
- }
+ void init()
+ {
+ }
+
+ ~WinCryptoProvider()
+ {
+ }
+
+ int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ QString name() const
+ {
+ return "qca-wincrypto";
+ }
+
+ QStringList features() const
+ {
+ QStringList list;
+ list += "random";
+ return list;
+ }
+
+ Context *createContext(const QString &type)
+ {
+ if (type == "random") {
+ return new WinCryptoRandomContext(this);
+ } else {
+ return 0;
+ }
+ }
};
//-----------------------------------------------------------
class WinCryptoPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual QCA::Provider *createProvider() { return new WinCryptoProvider; }
+ virtual QCA::Provider *createProvider()
+ {
+ return new WinCryptoProvider;
+ }
};
#if QT_VERSION < 0x050000
#include "qca-wincrypto.moc"
#endif
Q_EXPORT_PLUGIN2(qca_wincrypto, WinCryptoPlugin);
#endif // Q_OS_WIN32
diff --git a/plugins/qca-wingss/qca-wingss.cpp b/plugins/qca-wingss/qca-wingss.cpp
index fde55a3f..e6255d07 100644
--- a/plugins/qca-wingss/qca-wingss.cpp
+++ b/plugins/qca-wingss/qca-wingss.cpp
@@ -1,2305 +1,2252 @@
/*
* Copyright (C) 2008 Barracuda Networks, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <QtCrypto>
#include <qcaprovider.h>
#include <QtPlugin>
#include <QMutex>
#include <QLibrary>
#include <QTimer>
#ifndef FORWARD_ONLY
#include <windows.h>
#define SECURITY_WIN32
#include <Security.h>
#endif
using namespace QCA;
#define PROVIDER_NAME "qca-wingss"
#if !defined(FORWARD_ONLY)
// some defs possibly missing from MinGW
#ifndef SEC_E_MESSAGE_ALTERED
#define SEC_E_MESSAGE_ALTERED 0x8009030F
#endif
#ifndef SEC_E_CONTEXT_EXPIRED
#define SEC_E_CONTEXT_EXPIRED 0x80090317
#endif
#ifndef SEC_E_CRYPTO_SYSTEM_INVALID
#define SEC_E_CRYPTO_SYSTEM_INVALID 0x80090337
#endif
#ifndef SEC_E_OUT_OF_SEQUENCE
#define SEC_E_OUT_OF_SEQUENCE 0x80090310
#endif
#ifndef SEC_E_BUFFER_TOO_SMALL
#define SEC_E_BUFFER_TOO_SMALL 0x80090321
#endif
#ifndef SECURITY_ENTRYPOINTW
#define SECURITY_ENTRYPOINTW TEXT("InitSecurityInterfaceW")
#endif
#ifndef SECURITY_ENTRYPOINT_ANSIA
#define SECURITY_ENTRYPOINT_ANSIA "InitSecurityInterfaceA"
#endif
#ifndef SECPKG_FLAG_GSS_COMPATIBLE
#define SECPKG_FLAG_GSS_COMPATIBLE 0x00001000
#endif
#ifndef SECQOP_WRAP_NO_ENCRYPT
#define SECQOP_WRAP_NO_ENCRYPT 0x80000001
#endif
#ifndef ISC_RET_MUTUAL_AUTH
#define ISC_RET_MUTUAL_AUTH 0x00000002
#endif
#ifndef ISC_RET_SEQUENCE_DETECT
#define ISC_RET_SEQUENCE_DETECT 0x00000008
#endif
#ifndef ISC_RET_CONFIDENTIALITY
#define ISC_RET_CONFIDENTIALITY 0x00000010
#endif
#ifndef ISC_RET_INTEGRITY
#define ISC_RET_INTEGRITY 0x00010000
#endif
#ifdef Q_CC_MINGW
// for some reason, the MinGW definition of the W table has A functions in
// it, so we define a fixed version to use instead...
typedef struct _FIXED_SECURITY_FUNCTION_TABLEW {
- unsigned long dwVersion;
- ENUMERATE_SECURITY_PACKAGES_FN_W EnumerateSecurityPackagesW;
- QUERY_CREDENTIALS_ATTRIBUTES_FN_W QueryCredentialsAttributesW;
- ACQUIRE_CREDENTIALS_HANDLE_FN_W AcquireCredentialsHandleW;
- FREE_CREDENTIALS_HANDLE_FN FreeCredentialsHandle;
- void SEC_FAR* Reserved2;
- INITIALIZE_SECURITY_CONTEXT_FN_W InitializeSecurityContextW;
- ACCEPT_SECURITY_CONTEXT_FN AcceptSecurityContext;
- COMPLETE_AUTH_TOKEN_FN CompleteAuthToken;
- DELETE_SECURITY_CONTEXT_FN DeleteSecurityContext;
- APPLY_CONTROL_TOKEN_FN_W ApplyControlTokenW;
- QUERY_CONTEXT_ATTRIBUTES_FN_W QueryContextAttributesW;
- IMPERSONATE_SECURITY_CONTEXT_FN ImpersonateSecurityContext;
- REVERT_SECURITY_CONTEXT_FN RevertSecurityContext;
- MAKE_SIGNATURE_FN MakeSignature;
- VERIFY_SIGNATURE_FN VerifySignature;
- FREE_CONTEXT_BUFFER_FN FreeContextBuffer;
- QUERY_SECURITY_PACKAGE_INFO_FN_W QuerySecurityPackageInfoW;
- void SEC_FAR* Reserved3;
- void SEC_FAR* Reserved4;
- void SEC_FAR* Unknown1;
- void SEC_FAR* Unknown2;
- void SEC_FAR* Unknown3;
- void SEC_FAR* Unknown4;
- void SEC_FAR* Unknown5;
- ENCRYPT_MESSAGE_FN EncryptMessage;
- DECRYPT_MESSAGE_FN DecryptMessage;
+ unsigned long dwVersion;
+ ENUMERATE_SECURITY_PACKAGES_FN_W EnumerateSecurityPackagesW;
+ QUERY_CREDENTIALS_ATTRIBUTES_FN_W QueryCredentialsAttributesW;
+ ACQUIRE_CREDENTIALS_HANDLE_FN_W AcquireCredentialsHandleW;
+ FREE_CREDENTIALS_HANDLE_FN FreeCredentialsHandle;
+ void SEC_FAR *Reserved2;
+ INITIALIZE_SECURITY_CONTEXT_FN_W InitializeSecurityContextW;
+ ACCEPT_SECURITY_CONTEXT_FN AcceptSecurityContext;
+ COMPLETE_AUTH_TOKEN_FN CompleteAuthToken;
+ DELETE_SECURITY_CONTEXT_FN DeleteSecurityContext;
+ APPLY_CONTROL_TOKEN_FN_W ApplyControlTokenW;
+ QUERY_CONTEXT_ATTRIBUTES_FN_W QueryContextAttributesW;
+ IMPERSONATE_SECURITY_CONTEXT_FN ImpersonateSecurityContext;
+ REVERT_SECURITY_CONTEXT_FN RevertSecurityContext;
+ MAKE_SIGNATURE_FN MakeSignature;
+ VERIFY_SIGNATURE_FN VerifySignature;
+ FREE_CONTEXT_BUFFER_FN FreeContextBuffer;
+ QUERY_SECURITY_PACKAGE_INFO_FN_W QuerySecurityPackageInfoW;
+ void SEC_FAR *Reserved3;
+ void SEC_FAR *Reserved4;
+ void SEC_FAR *Unknown1;
+ void SEC_FAR *Unknown2;
+ void SEC_FAR *Unknown3;
+ void SEC_FAR *Unknown4;
+ void SEC_FAR *Unknown5;
+ ENCRYPT_MESSAGE_FN EncryptMessage;
+ DECRYPT_MESSAGE_FN DecryptMessage;
} FixedSecurityFunctionTableW, *PFixedSecurityFunctionTableW;
typedef FixedSecurityFunctionTableW MySecurityFunctionTableW;
typedef PFixedSecurityFunctionTableW PMySecurityFunctionTableW;
#else
typedef SecurityFunctionTableW MySecurityFunctionTableW;
typedef PSecurityFunctionTableW PMySecurityFunctionTableW;
#endif
#ifdef UNICODE
# define MySecurityFunctionTable MySecurityFunctionTableW
# define PMySecurityFunctionTable PMySecurityFunctionTableW
#else
# define MySecurityFunctionTable MySecurityFunctionTableA
# define PMySecurityFunctionTable PMySecurityFunctionTableA
#endif
#endif // !defined(FORWARD_ONLY)
-namespace wingssQCAPlugin {
+namespace wingssQCAPlugin
+{
//----------------------------------------------------------------------------
// SSPI helper API
//----------------------------------------------------------------------------
typedef void (*sspi_logger_func)(const QString &str);
class SspiPackage
{
public:
- QString name;
- quint32 caps;
- quint32 maxtok;
- quint16 version;
- quint16 rpcid;
- QString comment;
+ QString name;
+ quint32 caps;
+ quint32 maxtok;
+ quint16 version;
+ quint16 rpcid;
+ QString comment;
};
// logger can be set even when sspi is not loaded (this is needed so logging
// during sspi_load/unload can be captured). pass 0 to disable.
void sspi_set_logger(sspi_logger_func p);
void sspi_log(const QString &str);
bool sspi_load();
void sspi_unload();
// returns the available security packages. only the first call actually
// queries the sspi subsystem. subsequent calls return a cached result.
QList<SspiPackage> sspi_get_packagelist();
// refresh the package list cache. call sspi_get_packagelist afterwards to
// get the new list.
void sspi_refresh_packagelist();
// helper functions for logging
QString SECURITY_STATUS_toString(SECURITY_STATUS i);
QString ptr_toString(const void *p);
//----------------------------------------------------------------------------
// SSPI helper implementation
//----------------------------------------------------------------------------
Q_GLOBAL_STATIC(QMutex, sspi_mutex)
Q_GLOBAL_STATIC(QMutex, sspi_logger_mutex)
-union SecurityFunctionTableUnion
-{
- PMySecurityFunctionTableW W;
- PSecurityFunctionTableA A;
- void *ptr;
+union SecurityFunctionTableUnion {
+ PMySecurityFunctionTableW W;
+ PSecurityFunctionTableA A;
+ void *ptr;
};
static QLibrary *sspi_lib = 0;
static SecurityFunctionTableUnion sspi;
static sspi_logger_func sspi_logger;
static QList<SspiPackage> *sspi_packagelist = 0;
void sspi_log(const QString &str)
{
- QMutexLocker locker(sspi_logger_mutex());
+ QMutexLocker locker(sspi_logger_mutex());
- if(sspi_logger)
- sspi_logger(str);
+ if (sspi_logger) {
+ sspi_logger(str);
+ }
}
void sspi_set_logger(sspi_logger_func p)
{
- QMutexLocker locker(sspi_logger_mutex());
+ QMutexLocker locker(sspi_logger_mutex());
- sspi_logger = p;
+ sspi_logger = p;
}
#define CASE_SS_STRING(s) case s: return #s;
static const char *SECURITY_STATUS_lookup(SECURITY_STATUS i)
{
- switch(i)
- {
- CASE_SS_STRING(SEC_E_OK);
- CASE_SS_STRING(SEC_I_COMPLETE_AND_CONTINUE);
- CASE_SS_STRING(SEC_I_COMPLETE_NEEDED);
- CASE_SS_STRING(SEC_I_CONTINUE_NEEDED);
- CASE_SS_STRING(SEC_I_INCOMPLETE_CREDENTIALS);
- CASE_SS_STRING(SEC_E_UNSUPPORTED_FUNCTION);
- CASE_SS_STRING(SEC_E_INVALID_TOKEN);
- CASE_SS_STRING(SEC_E_MESSAGE_ALTERED);
- CASE_SS_STRING(SEC_E_INSUFFICIENT_MEMORY);
- CASE_SS_STRING(SEC_E_INTERNAL_ERROR);
- CASE_SS_STRING(SEC_E_INVALID_HANDLE);
- CASE_SS_STRING(SEC_E_LOGON_DENIED);
- CASE_SS_STRING(SEC_E_NO_AUTHENTICATING_AUTHORITY);
- CASE_SS_STRING(SEC_E_NO_CREDENTIALS);
- CASE_SS_STRING(SEC_E_TARGET_UNKNOWN);
- CASE_SS_STRING(SEC_E_WRONG_PRINCIPAL);
- CASE_SS_STRING(SEC_E_BUFFER_TOO_SMALL);
- CASE_SS_STRING(SEC_E_CONTEXT_EXPIRED);
- CASE_SS_STRING(SEC_E_CRYPTO_SYSTEM_INVALID);
- CASE_SS_STRING(SEC_E_QOP_NOT_SUPPORTED);
- CASE_SS_STRING(SEC_E_INCOMPLETE_MESSAGE);
- CASE_SS_STRING(SEC_E_OUT_OF_SEQUENCE);
- default: break;
- }
- return 0;
+ switch (i) {
+ CASE_SS_STRING(SEC_E_OK);
+ CASE_SS_STRING(SEC_I_COMPLETE_AND_CONTINUE);
+ CASE_SS_STRING(SEC_I_COMPLETE_NEEDED);
+ CASE_SS_STRING(SEC_I_CONTINUE_NEEDED);
+ CASE_SS_STRING(SEC_I_INCOMPLETE_CREDENTIALS);
+ CASE_SS_STRING(SEC_E_UNSUPPORTED_FUNCTION);
+ CASE_SS_STRING(SEC_E_INVALID_TOKEN);
+ CASE_SS_STRING(SEC_E_MESSAGE_ALTERED);
+ CASE_SS_STRING(SEC_E_INSUFFICIENT_MEMORY);
+ CASE_SS_STRING(SEC_E_INTERNAL_ERROR);
+ CASE_SS_STRING(SEC_E_INVALID_HANDLE);
+ CASE_SS_STRING(SEC_E_LOGON_DENIED);
+ CASE_SS_STRING(SEC_E_NO_AUTHENTICATING_AUTHORITY);
+ CASE_SS_STRING(SEC_E_NO_CREDENTIALS);
+ CASE_SS_STRING(SEC_E_TARGET_UNKNOWN);
+ CASE_SS_STRING(SEC_E_WRONG_PRINCIPAL);
+ CASE_SS_STRING(SEC_E_BUFFER_TOO_SMALL);
+ CASE_SS_STRING(SEC_E_CONTEXT_EXPIRED);
+ CASE_SS_STRING(SEC_E_CRYPTO_SYSTEM_INVALID);
+ CASE_SS_STRING(SEC_E_QOP_NOT_SUPPORTED);
+ CASE_SS_STRING(SEC_E_INCOMPLETE_MESSAGE);
+ CASE_SS_STRING(SEC_E_OUT_OF_SEQUENCE);
+ default: break;
+ }
+ return 0;
}
QString SECURITY_STATUS_toString(SECURITY_STATUS i)
{
- const char *str = SECURITY_STATUS_lookup(i);
- if(str)
- return QString(str);
- else
- return QString::number(i);
+ const char *str = SECURITY_STATUS_lookup(i);
+ if (str) {
+ return QString(str);
+ } else {
+ return QString::number(i);
+ }
}
QString ptr_toString(const void *p)
{
- return QString().sprintf("%p", p);
+ return QString().sprintf("%p", p);
}
bool sspi_load()
{
- QMutexLocker locker(sspi_mutex());
- if(sspi_lib)
- return true;
-
- sspi_lib = new QLibrary("secur32");
- if(!sspi_lib->load())
- {
- delete sspi_lib;
- sspi_lib = 0;
- return false;
- }
-
- union
- {
- INIT_SECURITY_INTERFACE_W W;
- INIT_SECURITY_INTERFACE_A A;
- void *ptr;
- } pInitSecurityInterface;
- pInitSecurityInterface.ptr = 0;
-
- QString securityEntrypoint;
+ QMutexLocker locker(sspi_mutex());
+ if (sspi_lib) {
+ return true;
+ }
+
+ sspi_lib = new QLibrary("secur32");
+ if (!sspi_lib->load()) {
+ delete sspi_lib;
+ sspi_lib = 0;
+ return false;
+ }
+
+ union {
+ INIT_SECURITY_INTERFACE_W W;
+ INIT_SECURITY_INTERFACE_A A;
+ void *ptr;
+ } pInitSecurityInterface;
+ pInitSecurityInterface.ptr = 0;
+
+ QString securityEntrypoint;
#if QT_VERSION >= 0x050000
- securityEntrypoint = QString::fromUtf16((const ushort *)SECURITY_ENTRYPOINTW);
- pInitSecurityInterface.W = (INIT_SECURITY_INTERFACE_W)(sspi_lib->resolve(securityEntrypoint.toLatin1().data()));
+ securityEntrypoint = QString::fromUtf16((const ushort *)SECURITY_ENTRYPOINTW);
+ pInitSecurityInterface.W = (INIT_SECURITY_INTERFACE_W)(sspi_lib->resolve(securityEntrypoint.toLatin1().data()));
#else
- QT_WA(
- securityEntrypoint = QString::fromUtf16((const ushort *)SECURITY_ENTRYPOINTW);
- pInitSecurityInterface.W = (INIT_SECURITY_INTERFACE_W)(sspi_lib->resolve(securityEntrypoint.toLatin1().data()));
- ,
- securityEntrypoint = QString::fromLatin1(SECURITY_ENTRYPOINT_ANSIA);
- pInitSecurityInterface.A = (INIT_SECURITY_INTERFACE_A)(sspi_lib->resolve(securityEntrypoint.toLatin1().data()));
- )
+ QT_WA(
+ securityEntrypoint = QString::fromUtf16((const ushort *)SECURITY_ENTRYPOINTW);
+ pInitSecurityInterface.W = (INIT_SECURITY_INTERFACE_W)(sspi_lib->resolve(securityEntrypoint.toLatin1().data()));
+ ,
+ securityEntrypoint = QString::fromLatin1(SECURITY_ENTRYPOINT_ANSIA);
+ pInitSecurityInterface.A = (INIT_SECURITY_INTERFACE_A)(sspi_lib->resolve(securityEntrypoint.toLatin1().data()));
+ )
#endif
- if(!pInitSecurityInterface.ptr)
- {
- sspi_lib->unload();
- delete sspi_lib;
- sspi_lib = 0;
- return false;
- }
-
- union
- {
- PMySecurityFunctionTableW W;
- PSecurityFunctionTableA A;
- void *ptr;
- } funcs;
- funcs.ptr = 0;
+ if (!pInitSecurityInterface.ptr) {
+ sspi_lib->unload();
+ delete sspi_lib;
+ sspi_lib = 0;
+ return false;
+ }
+
+ union {
+ PMySecurityFunctionTableW W;
+ PSecurityFunctionTableA A;
+ void *ptr;
+ } funcs;
+ funcs.ptr = 0;
#if QT_VERSION >= 0x050000
- funcs.W = (PMySecurityFunctionTableW)pInitSecurityInterface.W();
+ funcs.W = (PMySecurityFunctionTableW)pInitSecurityInterface.W();
#else
- QT_WA(
- funcs.W = (PMySecurityFunctionTableW)pInitSecurityInterface.W();
- ,
- funcs.A = pInitSecurityInterface.A();
- )
+ QT_WA(
+ funcs.W = (PMySecurityFunctionTableW)pInitSecurityInterface.W();
+ ,
+ funcs.A = pInitSecurityInterface.A();
+ )
#endif
- sspi_log(QString("%1() = %2\n").arg(securityEntrypoint, ptr_toString(funcs.ptr)));
- if(!funcs.ptr)
- {
- sspi_lib->unload();
- delete sspi_lib;
- sspi_lib = 0;
- return false;
- }
+ sspi_log(QString("%1() = %2\n").arg(securityEntrypoint, ptr_toString(funcs.ptr)));
+ if (!funcs.ptr) {
+ sspi_lib->unload();
+ delete sspi_lib;
+ sspi_lib = 0;
+ return false;
+ }
#if QT_VERSION >= 0x050000
- sspi.W = funcs.W;
+ sspi.W = funcs.W;
#else
- QT_WA(
- sspi.W = funcs.W;
- ,
- sspi.A = funcs.A;
- )
+ QT_WA(
+ sspi.W = funcs.W;
+ ,
+ sspi.A = funcs.A;
+ )
#endif
- return true;
+ return true;
}
void sspi_unload()
{
- QMutexLocker locker(sspi_mutex());
+ QMutexLocker locker(sspi_mutex());
- sspi_lib->unload();
- delete sspi_lib;
- sspi_lib = 0;
- sspi.ptr = 0;
+ sspi_lib->unload();
+ delete sspi_lib;
+ sspi_lib = 0;
+ sspi.ptr = 0;
}
static QList<SspiPackage> sspi_get_packagelist_direct()
{
- QList<SspiPackage> out;
+ QList<SspiPackage> out;
#if QT_VERSION >= 0x050000
- ULONG cPackages;
- SecPkgInfoW *pPackageInfo;
- SECURITY_STATUS ret = sspi.W->EnumerateSecurityPackagesW(&cPackages, &pPackageInfo);
- sspi_log(QString("EnumerateSecurityPackages() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret != SEC_E_OK)
- return out;
-
- for(int n = 0; n < (int)cPackages; ++n)
- {
- SecPkgInfoW *p = &pPackageInfo[n];
- SspiPackage i;
- i.name = QString::fromUtf16((const ushort *)p->Name);
- i.caps = p->fCapabilities;
- i.version = p->wVersion;
- i.rpcid = p->wRPCID;
- i.maxtok = p->cbMaxToken;
- i.comment = QString::fromUtf16((const ushort *)p->Comment);
- out += i;
- }
-
- ret = sspi.W->FreeContextBuffer(&pPackageInfo);
- sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ ULONG cPackages;
+ SecPkgInfoW *pPackageInfo;
+ SECURITY_STATUS ret = sspi.W->EnumerateSecurityPackagesW(&cPackages, &pPackageInfo);
+ sspi_log(QString("EnumerateSecurityPackages() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret != SEC_E_OK) {
+ return out;
+ }
+
+ for (int n = 0; n < (int)cPackages; ++n) {
+ SecPkgInfoW *p = &pPackageInfo[n];
+ SspiPackage i;
+ i.name = QString::fromUtf16((const ushort *)p->Name);
+ i.caps = p->fCapabilities;
+ i.version = p->wVersion;
+ i.rpcid = p->wRPCID;
+ i.maxtok = p->cbMaxToken;
+ i.comment = QString::fromUtf16((const ushort *)p->Comment);
+ out += i;
+ }
+
+ ret = sspi.W->FreeContextBuffer(&pPackageInfo);
+ sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
#else
- QT_WA(
- ULONG cPackages;
- SecPkgInfoW *pPackageInfo;
- SECURITY_STATUS ret = sspi.W->EnumerateSecurityPackagesW(&cPackages, &pPackageInfo);
- sspi_log(QString("EnumerateSecurityPackages() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret != SEC_E_OK)
- return out;
-
- for(int n = 0; n < (int)cPackages; ++n)
- {
- SecPkgInfoW *p = &pPackageInfo[n];
- SspiPackage i;
- i.name = QString::fromUtf16((const ushort *)p->Name);
- i.caps = p->fCapabilities;
- i.version = p->wVersion;
- i.rpcid = p->wRPCID;
- i.maxtok = p->cbMaxToken;
- i.comment = QString::fromUtf16((const ushort *)p->Comment);
- out += i;
- }
-
- ret = sspi.W->FreeContextBuffer(&pPackageInfo);
- sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- ,
- ULONG cPackages;
- SecPkgInfoA *pPackageInfo;
- SECURITY_STATUS ret = sspi.A->EnumerateSecurityPackagesA(&cPackages, &pPackageInfo);
- sspi_log(QString("EnumerateSecurityPackages() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret != SEC_E_OK)
- return out;
-
- for(int n = 0; n < (int)cPackages; ++n)
- {
- SecPkgInfoA *p = &pPackageInfo[n];
- SspiPackage i;
- i.name = QString::fromLocal8Bit(p->Name);
- i.caps = p->fCapabilities;
- i.version = p->wVersion;
- i.rpcid = p->wRPCID;
- i.maxtok = p->cbMaxToken;
- i.comment = QString::fromLocal8Bit(p->Comment);
- out += i;
- }
-
- ret = sspi.A->FreeContextBuffer(&pPackageInfo);
- sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- )
+ QT_WA(
+ ULONG cPackages;
+ SecPkgInfoW * pPackageInfo;
+ SECURITY_STATUS ret = sspi.W->EnumerateSecurityPackagesW(&cPackages, &pPackageInfo);
+ sspi_log(QString("EnumerateSecurityPackages() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret != SEC_E_OK)
+ return out;
+
+ for (int n = 0; n < (int)cPackages; ++n) {
+ SecPkgInfoW *p = &pPackageInfo[n];
+ SspiPackage i;
+ i.name = QString::fromUtf16((const ushort *)p->Name);
+ i.caps = p->fCapabilities;
+ i.version = p->wVersion;
+ i.rpcid = p->wRPCID;
+ i.maxtok = p->cbMaxToken;
+ i.comment = QString::fromUtf16((const ushort *)p->Comment);
+ out += i;
+ }
+
+ ret = sspi.W->FreeContextBuffer(&pPackageInfo);
+ sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ ,
+ ULONG cPackages;
+ SecPkgInfoA * pPackageInfo;
+ SECURITY_STATUS ret = sspi.A->EnumerateSecurityPackagesA(&cPackages, &pPackageInfo);
+ sspi_log(QString("EnumerateSecurityPackages() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret != SEC_E_OK)
+ return out;
+
+ for (int n = 0; n < (int)cPackages; ++n) {
+ SecPkgInfoA *p = &pPackageInfo[n];
+ SspiPackage i;
+ i.name = QString::fromLocal8Bit(p->Name);
+ i.caps = p->fCapabilities;
+ i.version = p->wVersion;
+ i.rpcid = p->wRPCID;
+ i.maxtok = p->cbMaxToken;
+ i.comment = QString::fromLocal8Bit(p->Comment);
+ out += i;
+ }
+
+ ret = sspi.A->FreeContextBuffer(&pPackageInfo);
+ sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ )
#endif
- return out;
+ return out;
}
static void sspi_refresh_packagelist_internal()
{
- if(sspi_packagelist)
- *sspi_packagelist = sspi_get_packagelist_direct();
- else
- sspi_packagelist = new QList<SspiPackage>(sspi_get_packagelist_direct());
+ if (sspi_packagelist) {
+ *sspi_packagelist = sspi_get_packagelist_direct();
+ } else {
+ sspi_packagelist = new QList<SspiPackage>(sspi_get_packagelist_direct());
+ }
}
QList<SspiPackage> sspi_get_packagelist()
{
- QMutexLocker locker(sspi_mutex());
+ QMutexLocker locker(sspi_mutex());
- if(!sspi_packagelist)
- sspi_refresh_packagelist_internal();
- return *sspi_packagelist;
+ if (!sspi_packagelist) {
+ sspi_refresh_packagelist_internal();
+ }
+ return *sspi_packagelist;
}
void sspi_refresh_packagelist()
{
- QMutexLocker locker(sspi_mutex());
+ QMutexLocker locker(sspi_mutex());
- sspi_refresh_packagelist_internal();
+ sspi_refresh_packagelist_internal();
}
template <typename T>
inline T cap_to_int(const T &t)
{
- if(sizeof(int) <= sizeof(T))
- return (int)((t > INT_MAX) ? INT_MAX : t);
- else
- return (int)t;
+ if (sizeof(int) <= sizeof(T)) {
+ return (int)((t > INT_MAX) ? INT_MAX : t);
+ } else {
+ return (int)t;
+ }
}
//----------------------------------------------------------------------------
// KerberosSession
//----------------------------------------------------------------------------
// this class thinly wraps SSPI to perform kerberos.
class KerberosSession
{
public:
- enum ReturnCode
- {
- Success,
- NeedMoreData, // for decrypt
- ErrorInvalidSystem,
- ErrorKerberosNotFound,
- ErrorAcquireCredentials,
- ErrorInitialize,
- ErrorQueryContext,
- ErrorEncrypt,
- ErrorDecrypt
- };
-
- SECURITY_STATUS lastErrorCode;
-
- quint32 maxtok;
-
- bool initialized;
- bool first_step;
- QByteArray first_out_token;
- bool authed;
-
- QString spn;
-
- CredHandle user_cred;
- TimeStamp user_cred_expiry;
-
- CtxtHandle ctx;
- ULONG ctx_attr_req;
- ULONG ctx_attr;
- bool have_sizes;
- SecPkgContext_Sizes ctx_sizes;
- SecPkgContext_StreamSizes ctx_streamSizes;
-
- KerberosSession() :
- initialized(false),
- have_sizes(false)
- {
- }
-
- ~KerberosSession()
- {
- if(initialized)
- {
- SECURITY_STATUS ret = sspi.W->DeleteSecurityContext(&ctx);
- sspi_log(QString("DeleteSecurityContext() = %1\n").arg(SECURITY_STATUS_toString(ret)));
-
- ret = sspi.W->FreeCredentialsHandle(&user_cred);
- sspi_log(QString("FreeCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- }
- }
-
- ReturnCode init(const QString &_spn)
- {
- // kerberos only works on unicode-based systems. we do this
- // check so we can lazily use the W api from here on out.
+ enum ReturnCode {
+ Success,
+ NeedMoreData, // for decrypt
+ ErrorInvalidSystem,
+ ErrorKerberosNotFound,
+ ErrorAcquireCredentials,
+ ErrorInitialize,
+ ErrorQueryContext,
+ ErrorEncrypt,
+ ErrorDecrypt
+ };
+
+ SECURITY_STATUS lastErrorCode;
+
+ quint32 maxtok;
+
+ bool initialized;
+ bool first_step;
+ QByteArray first_out_token;
+ bool authed;
+
+ QString spn;
+
+ CredHandle user_cred;
+ TimeStamp user_cred_expiry;
+
+ CtxtHandle ctx;
+ ULONG ctx_attr_req;
+ ULONG ctx_attr;
+ bool have_sizes;
+ SecPkgContext_Sizes ctx_sizes;
+ SecPkgContext_StreamSizes ctx_streamSizes;
+
+ KerberosSession() :
+ initialized(false),
+ have_sizes(false)
+ {
+ }
+
+ ~KerberosSession()
+ {
+ if (initialized) {
+ SECURITY_STATUS ret = sspi.W->DeleteSecurityContext(&ctx);
+ sspi_log(QString("DeleteSecurityContext() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+
+ ret = sspi.W->FreeCredentialsHandle(&user_cred);
+ sspi_log(QString("FreeCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ }
+ }
+
+ ReturnCode init(const QString &_spn)
+ {
+ // kerberos only works on unicode-based systems. we do this
+ // check so we can lazily use the W api from here on out.
#if QT_VERSION < 0x050000
- bool validSystem;
- QT_WA(
- validSystem = true;
- ,
- validSystem = false;
- )
- if(!validSystem)
- return ErrorInvalidSystem;
+ bool validSystem;
+ QT_WA(
+ validSystem = true;
+ ,
+ validSystem = false;
+ )
+ if (!validSystem) {
+ return ErrorInvalidSystem;
+ }
#endif
- // ensure kerberos is available
- bool found = false;
- quint32 _maxtok = 0;
- QList<SspiPackage> packages = sspi_get_packagelist();
- sspi_log("SSPI packages:\n");
- foreach(const SspiPackage &p, packages)
- {
- bool gss = false;
- if(p.caps & SECPKG_FLAG_GSS_COMPATIBLE)
- gss = true;
-
- if(p.name == "Kerberos" && gss)
- {
- found = true;
- _maxtok = p.maxtok;
- }
-
- QString gssstr = gss ? "yes" : "no";
- sspi_log(QString(" %1 (gss=%2, maxtok=%3)\n").arg(p.name, gssstr, QString::number(p.maxtok)));
- }
-
- if(!found)
- return ErrorKerberosNotFound;
-
- // get the logged-in user's credentials
- SECURITY_STATUS ret = sspi.W->AcquireCredentialsHandleW(
- (SEC_WCHAR *)0, // we want creds of logged-in user
- (SEC_WCHAR *)QString("Kerberos").utf16(),
- SECPKG_CRED_OUTBOUND,
- 0, // don't need a LUID
- 0, // default credentials for kerberos
- 0, // not used
- 0, // not used
- &user_cred,
- &user_cred_expiry);
- sspi_log(QString("AcquireCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret != SEC_E_OK)
- {
- lastErrorCode = ret;
- return ErrorAcquireCredentials;
- }
-
- maxtok = _maxtok;
- authed = false;
- spn = _spn;
-
- SecBuffer outbuf;
- outbuf.BufferType = SECBUFFER_TOKEN;
- outbuf.cbBuffer = 0;
- outbuf.pvBuffer = NULL;
-
- SecBufferDesc outbufdesc;
- outbufdesc.ulVersion = SECBUFFER_VERSION;
- outbufdesc.cBuffers = 1;
- outbufdesc.pBuffers = &outbuf;
-
- ctx_attr_req = 0;
-
- // not strictly required, but some SSPI calls seem to always
- // allocate memory, so for consistency we'll explicity
- // request to have it that way all the time
- ctx_attr_req |= ISC_REQ_ALLOCATE_MEMORY;
-
- // required by SASL GSSAPI RFC
- ctx_attr_req |= ISC_REQ_INTEGRITY;
-
- // required for security layer
- ctx_attr_req |= ISC_REQ_MUTUAL_AUTH;
- ctx_attr_req |= ISC_REQ_SEQUENCE_DETECT;
-
- // required for encryption
- ctx_attr_req |= ISC_REQ_CONFIDENTIALITY;
-
- // other options that may be of use, but we currently aren't
- // using:
- // ISC_REQ_DELEGATE
- // ISC_REQ_REPLAY_DETECT
-
- ret = sspi.W->InitializeSecurityContextW(
- &user_cred,
- 0, // NULL for the first call
- (SEC_WCHAR *)spn.utf16(),
- ctx_attr_req,
- 0,
- SECURITY_NETWORK_DREP,
- 0, // NULL for first call
- 0,
- &ctx,
- &outbufdesc,
- &ctx_attr,
- 0); // don't care about expiration
- sspi_log(QString("InitializeSecurityContext(*, 0, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret == SEC_E_OK || ret == SEC_I_CONTINUE_NEEDED)
- {
- if(outbuf.pvBuffer)
- {
- first_out_token.resize(outbuf.cbBuffer);
- memcpy(first_out_token.data(), outbuf.pvBuffer, outbuf.cbBuffer);
-
- SECURITY_STATUS fret = sspi.W->FreeContextBuffer(outbuf.pvBuffer);
- sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(fret)));
- }
-
- if(ret == SEC_E_OK)
- authed = true;
- }
- else
- {
- // ret was an error, or some unexpected value like
- // SEC_I_COMPLETE_NEEDED or
- // SEC_I_COMPLETE_AND_CONTINUE, which i believe are
- // not used for kerberos
-
- lastErrorCode = ret;
-
- ret = sspi.W->FreeCredentialsHandle(&user_cred);
- sspi_log(QString("FreeCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
-
- return ErrorInitialize;
- }
-
- initialized = true;
- first_step = true;
-
- return Success;
- }
-
- ReturnCode step(const QByteArray &in, QByteArray *out, bool *authenticated)
- {
- if(authed)
- {
- out->clear();
- *authenticated = true;
- return Success;
- }
-
- if(first_step)
- {
- // ignore 'in'
-
- *out = first_out_token;
- first_out_token.clear();
-
- first_step = false;
- }
- else
- {
- SecBuffer outbuf;
- outbuf.BufferType = SECBUFFER_TOKEN;
- outbuf.cbBuffer = 0;
- outbuf.pvBuffer = NULL;
-
- SecBufferDesc outbufdesc;
- outbufdesc.ulVersion = SECBUFFER_VERSION;
- outbufdesc.cBuffers = 1;
- outbufdesc.pBuffers = &outbuf;
-
- SecBuffer inbuf;
- inbuf.BufferType = SECBUFFER_TOKEN;
- inbuf.cbBuffer = in.size();
- inbuf.pvBuffer = (void *)in.data();
-
- SecBufferDesc inbufdesc;
- inbufdesc.ulVersion = SECBUFFER_VERSION;
- inbufdesc.cBuffers = 1;
- inbufdesc.pBuffers = &inbuf;
-
- SECURITY_STATUS ret = sspi.W->InitializeSecurityContextW(
- &user_cred,
- &ctx,
- (SEC_WCHAR *)spn.utf16(),
- ctx_attr_req,
- 0,
- SECURITY_NETWORK_DREP,
- &inbufdesc,
- 0,
- &ctx,
- &outbufdesc,
- &ctx_attr,
- 0); // don't care about expiration
- sspi_log(QString("InitializeSecurityContext(*, ctx, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret == SEC_E_OK || ret == SEC_I_CONTINUE_NEEDED)
- {
- if(outbuf.pvBuffer)
- {
- out->resize(outbuf.cbBuffer);
- memcpy(out->data(), outbuf.pvBuffer, outbuf.cbBuffer);
-
- SECURITY_STATUS fret = sspi.W->FreeContextBuffer(outbuf.pvBuffer);
- sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(fret)));
- }
- else
- out->clear();
-
- if(ret == SEC_E_OK)
- authed = true;
- }
- else
- {
- // ret was an error, or some unexpected value like
- // SEC_I_COMPLETE_NEEDED or
- // SEC_I_COMPLETE_AND_CONTINUE, which i believe are
- // not used for kerberos
-
- lastErrorCode = ret;
-
- ret = sspi.W->DeleteSecurityContext(&ctx);
- sspi_log(QString("DeleteSecurityContext() = %1\n").arg(SECURITY_STATUS_toString(ret)));
-
- ret = sspi.W->FreeCredentialsHandle(&user_cred);
- sspi_log(QString("FreeCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
-
- initialized = false;
- return ErrorInitialize;
- }
- }
-
- *authenticated = authed;
- return Success;
- }
-
- // private
- bool ensure_sizes_cached()
- {
- if(!have_sizes)
- {
- SECURITY_STATUS ret = sspi.W->QueryContextAttributesW(&ctx, SECPKG_ATTR_SIZES, &ctx_sizes);
- sspi_log(QString("QueryContextAttributes(ctx, SECPKG_ATTR_SIZES, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret != SEC_E_OK)
- {
- lastErrorCode = ret;
- return false;
- }
-
- // for some reason, querying the stream sizes returns
- // SEC_E_UNSUPPORTED_FUNCTION on my system, even
- // though the docs say it should work and putty
- // wingss also calls it.
-
- // all we really need is cbMaximumMessage, and since
- // we can't query for it, we'll hard code some
- // value. according to putty wingss, the max size
- // is essentially unbounded anyway, so this should
- // be safe to do.
- ctx_streamSizes.cbMaximumMessage = 8192;
-
- //ret = sspi.W->QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &ctx_streamSizes);
- //sspi_log(QString("QueryContextAttributes(ctx, SECPKG_ATTR_STREAM_SIZES, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
- //if(ret != SEC_E_OK)
- //{
- // lastErrorCode = ret;
- // return ErrorQueryContext;
- //}
-
- have_sizes = true;
- }
-
- return true;
- }
-
- ReturnCode get_max_encrypt_size(int *max)
- {
- if(!ensure_sizes_cached())
- return ErrorQueryContext;
-
- *max = cap_to_int<unsigned long>(ctx_streamSizes.cbMaximumMessage);
-
- return Success;
- }
-
- ReturnCode encode(const QByteArray &in, QByteArray *out, bool encrypt)
- {
- if(!ensure_sizes_cached())
- return ErrorQueryContext;
-
- QByteArray tokenbuf(ctx_sizes.cbSecurityTrailer, 0);
- QByteArray padbuf(ctx_sizes.cbBlockSize, 0);
-
- // we assume here, like putty wingss, that the output size is
- // less than or equal to the input size. honestly I don't
- // see how this is clear from the SSPI documentation, but
- // the code seems to work so we'll go with it...
- QByteArray databuf = in;
-
- SecBuffer buf[3];
- buf[0].BufferType = SECBUFFER_TOKEN;
- buf[0].cbBuffer = tokenbuf.size();
- buf[0].pvBuffer = tokenbuf.data();
- buf[1].BufferType = SECBUFFER_DATA;
- buf[1].cbBuffer = databuf.size();
- buf[1].pvBuffer = databuf.data();
- buf[2].BufferType = SECBUFFER_PADDING;
- buf[2].cbBuffer = padbuf.size();
- buf[2].pvBuffer = padbuf.data();
-
- SecBufferDesc bufdesc;
- bufdesc.ulVersion = SECBUFFER_VERSION;
- bufdesc.cBuffers = 3;
- bufdesc.pBuffers = buf;
-
- SECURITY_STATUS ret = sspi.W->EncryptMessage(&ctx, encrypt ? 0 : SECQOP_WRAP_NO_ENCRYPT, &bufdesc, 0);
- sspi_log(QString("EncryptMessage() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret != SEC_E_OK)
- {
- lastErrorCode = ret;
- return ErrorEncrypt;
- }
-
- QByteArray fullbuf;
- for(int i = 0; i < (int)bufdesc.cBuffers; ++i)
- fullbuf += QByteArray((const char *)bufdesc.pBuffers[i].pvBuffer, bufdesc.pBuffers[i].cbBuffer);
-
- *out = fullbuf;
- return Success;
- }
-
- ReturnCode decode(const QByteArray &in, QByteArray *out, bool *encrypted)
- {
- SecBuffer buf[2];
- buf[0].BufferType = SECBUFFER_DATA;
- buf[0].cbBuffer = 0;
- buf[0].pvBuffer = NULL;
- buf[1].BufferType = SECBUFFER_STREAM;
- buf[1].cbBuffer = in.size();
- buf[1].pvBuffer = (void *)in.data();
-
- SecBufferDesc bufdesc;
- bufdesc.ulVersion = SECBUFFER_VERSION;
- bufdesc.cBuffers = 2;
- bufdesc.pBuffers = buf;
-
- ULONG fQOP;
- SECURITY_STATUS ret = sspi.W->DecryptMessage(&ctx, &bufdesc, 0, &fQOP);
- sspi_log(QString("DecryptMessage() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- if(ret == SEC_E_INCOMPLETE_MESSAGE)
- {
- return NeedMoreData;
- }
- else if(ret != SEC_E_OK)
- {
- lastErrorCode = ret;
- return ErrorDecrypt;
- }
-
- if(buf[0].pvBuffer)
- {
- out->resize(buf[0].cbBuffer);
- memcpy(out->data(), buf[0].pvBuffer, buf[0].cbBuffer);
-
- SECURITY_STATUS ret = sspi.W->FreeContextBuffer(buf[0].pvBuffer);
- sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
- }
- else
- out->clear();
-
- if(fQOP & SECQOP_WRAP_NO_ENCRYPT)
- *encrypted = false;
- else
- *encrypted = true;
-
- return Success;
- }
+ // ensure kerberos is available
+ bool found = false;
+ quint32 _maxtok = 0;
+ QList<SspiPackage> packages = sspi_get_packagelist();
+ sspi_log("SSPI packages:\n");
+ foreach (const SspiPackage &p, packages) {
+ bool gss = false;
+ if (p.caps & SECPKG_FLAG_GSS_COMPATIBLE) {
+ gss = true;
+ }
+
+ if (p.name == "Kerberos" && gss) {
+ found = true;
+ _maxtok = p.maxtok;
+ }
+
+ QString gssstr = gss ? "yes" : "no";
+ sspi_log(QString(" %1 (gss=%2, maxtok=%3)\n").arg(p.name, gssstr, QString::number(p.maxtok)));
+ }
+
+ if (!found) {
+ return ErrorKerberosNotFound;
+ }
+
+ // get the logged-in user's credentials
+ SECURITY_STATUS ret = sspi.W->AcquireCredentialsHandleW(
+ (SEC_WCHAR *)0, // we want creds of logged-in user
+ (SEC_WCHAR *)QString("Kerberos").utf16(),
+ SECPKG_CRED_OUTBOUND,
+ 0, // don't need a LUID
+ 0, // default credentials for kerberos
+ 0, // not used
+ 0, // not used
+ &user_cred,
+ &user_cred_expiry);
+ sspi_log(QString("AcquireCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret != SEC_E_OK) {
+ lastErrorCode = ret;
+ return ErrorAcquireCredentials;
+ }
+
+ maxtok = _maxtok;
+ authed = false;
+ spn = _spn;
+
+ SecBuffer outbuf;
+ outbuf.BufferType = SECBUFFER_TOKEN;
+ outbuf.cbBuffer = 0;
+ outbuf.pvBuffer = NULL;
+
+ SecBufferDesc outbufdesc;
+ outbufdesc.ulVersion = SECBUFFER_VERSION;
+ outbufdesc.cBuffers = 1;
+ outbufdesc.pBuffers = &outbuf;
+
+ ctx_attr_req = 0;
+
+ // not strictly required, but some SSPI calls seem to always
+ // allocate memory, so for consistency we'll explicity
+ // request to have it that way all the time
+ ctx_attr_req |= ISC_REQ_ALLOCATE_MEMORY;
+
+ // required by SASL GSSAPI RFC
+ ctx_attr_req |= ISC_REQ_INTEGRITY;
+
+ // required for security layer
+ ctx_attr_req |= ISC_REQ_MUTUAL_AUTH;
+ ctx_attr_req |= ISC_REQ_SEQUENCE_DETECT;
+
+ // required for encryption
+ ctx_attr_req |= ISC_REQ_CONFIDENTIALITY;
+
+ // other options that may be of use, but we currently aren't
+ // using:
+ // ISC_REQ_DELEGATE
+ // ISC_REQ_REPLAY_DETECT
+
+ ret = sspi.W->InitializeSecurityContextW(
+ &user_cred,
+ 0, // NULL for the first call
+ (SEC_WCHAR *)spn.utf16(),
+ ctx_attr_req,
+ 0,
+ SECURITY_NETWORK_DREP,
+ 0, // NULL for first call
+ 0,
+ &ctx,
+ &outbufdesc,
+ &ctx_attr,
+ 0); // don't care about expiration
+ sspi_log(QString("InitializeSecurityContext(*, 0, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret == SEC_E_OK || ret == SEC_I_CONTINUE_NEEDED) {
+ if (outbuf.pvBuffer) {
+ first_out_token.resize(outbuf.cbBuffer);
+ memcpy(first_out_token.data(), outbuf.pvBuffer, outbuf.cbBuffer);
+
+ SECURITY_STATUS fret = sspi.W->FreeContextBuffer(outbuf.pvBuffer);
+ sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(fret)));
+ }
+
+ if (ret == SEC_E_OK) {
+ authed = true;
+ }
+ } else {
+ // ret was an error, or some unexpected value like
+ // SEC_I_COMPLETE_NEEDED or
+ // SEC_I_COMPLETE_AND_CONTINUE, which i believe are
+ // not used for kerberos
+
+ lastErrorCode = ret;
+
+ ret = sspi.W->FreeCredentialsHandle(&user_cred);
+ sspi_log(QString("FreeCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+
+ return ErrorInitialize;
+ }
+
+ initialized = true;
+ first_step = true;
+
+ return Success;
+ }
+
+ ReturnCode step(const QByteArray &in, QByteArray *out, bool *authenticated)
+ {
+ if (authed) {
+ out->clear();
+ *authenticated = true;
+ return Success;
+ }
+
+ if (first_step) {
+ // ignore 'in'
+
+ *out = first_out_token;
+ first_out_token.clear();
+
+ first_step = false;
+ } else {
+ SecBuffer outbuf;
+ outbuf.BufferType = SECBUFFER_TOKEN;
+ outbuf.cbBuffer = 0;
+ outbuf.pvBuffer = NULL;
+
+ SecBufferDesc outbufdesc;
+ outbufdesc.ulVersion = SECBUFFER_VERSION;
+ outbufdesc.cBuffers = 1;
+ outbufdesc.pBuffers = &outbuf;
+
+ SecBuffer inbuf;
+ inbuf.BufferType = SECBUFFER_TOKEN;
+ inbuf.cbBuffer = in.size();
+ inbuf.pvBuffer = (void *)in.data();
+
+ SecBufferDesc inbufdesc;
+ inbufdesc.ulVersion = SECBUFFER_VERSION;
+ inbufdesc.cBuffers = 1;
+ inbufdesc.pBuffers = &inbuf;
+
+ SECURITY_STATUS ret = sspi.W->InitializeSecurityContextW(
+ &user_cred,
+ &ctx,
+ (SEC_WCHAR *)spn.utf16(),
+ ctx_attr_req,
+ 0,
+ SECURITY_NETWORK_DREP,
+ &inbufdesc,
+ 0,
+ &ctx,
+ &outbufdesc,
+ &ctx_attr,
+ 0); // don't care about expiration
+ sspi_log(QString("InitializeSecurityContext(*, ctx, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret == SEC_E_OK || ret == SEC_I_CONTINUE_NEEDED) {
+ if (outbuf.pvBuffer) {
+ out->resize(outbuf.cbBuffer);
+ memcpy(out->data(), outbuf.pvBuffer, outbuf.cbBuffer);
+
+ SECURITY_STATUS fret = sspi.W->FreeContextBuffer(outbuf.pvBuffer);
+ sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(fret)));
+ } else {
+ out->clear();
+ }
+
+ if (ret == SEC_E_OK) {
+ authed = true;
+ }
+ } else {
+ // ret was an error, or some unexpected value like
+ // SEC_I_COMPLETE_NEEDED or
+ // SEC_I_COMPLETE_AND_CONTINUE, which i believe are
+ // not used for kerberos
+
+ lastErrorCode = ret;
+
+ ret = sspi.W->DeleteSecurityContext(&ctx);
+ sspi_log(QString("DeleteSecurityContext() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+
+ ret = sspi.W->FreeCredentialsHandle(&user_cred);
+ sspi_log(QString("FreeCredentialsHandle() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+
+ initialized = false;
+ return ErrorInitialize;
+ }
+ }
+
+ *authenticated = authed;
+ return Success;
+ }
+
+ // private
+ bool ensure_sizes_cached()
+ {
+ if (!have_sizes) {
+ SECURITY_STATUS ret = sspi.W->QueryContextAttributesW(&ctx, SECPKG_ATTR_SIZES, &ctx_sizes);
+ sspi_log(QString("QueryContextAttributes(ctx, SECPKG_ATTR_SIZES, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret != SEC_E_OK) {
+ lastErrorCode = ret;
+ return false;
+ }
+
+ // for some reason, querying the stream sizes returns
+ // SEC_E_UNSUPPORTED_FUNCTION on my system, even
+ // though the docs say it should work and putty
+ // wingss also calls it.
+
+ // all we really need is cbMaximumMessage, and since
+ // we can't query for it, we'll hard code some
+ // value. according to putty wingss, the max size
+ // is essentially unbounded anyway, so this should
+ // be safe to do.
+ ctx_streamSizes.cbMaximumMessage = 8192;
+
+ //ret = sspi.W->QueryContextAttributesW(&ctx, SECPKG_ATTR_STREAM_SIZES, &ctx_streamSizes);
+ //sspi_log(QString("QueryContextAttributes(ctx, SECPKG_ATTR_STREAM_SIZES, ...) = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ //if(ret != SEC_E_OK)
+ //{
+ // lastErrorCode = ret;
+ // return ErrorQueryContext;
+ //}
+
+ have_sizes = true;
+ }
+
+ return true;
+ }
+
+ ReturnCode get_max_encrypt_size(int *max)
+ {
+ if (!ensure_sizes_cached()) {
+ return ErrorQueryContext;
+ }
+
+ *max = cap_to_int<unsigned long>(ctx_streamSizes.cbMaximumMessage);
+
+ return Success;
+ }
+
+ ReturnCode encode(const QByteArray &in, QByteArray *out, bool encrypt)
+ {
+ if (!ensure_sizes_cached()) {
+ return ErrorQueryContext;
+ }
+
+ QByteArray tokenbuf(ctx_sizes.cbSecurityTrailer, 0);
+ QByteArray padbuf(ctx_sizes.cbBlockSize, 0);
+
+ // we assume here, like putty wingss, that the output size is
+ // less than or equal to the input size. honestly I don't
+ // see how this is clear from the SSPI documentation, but
+ // the code seems to work so we'll go with it...
+ QByteArray databuf = in;
+
+ SecBuffer buf[3];
+ buf[0].BufferType = SECBUFFER_TOKEN;
+ buf[0].cbBuffer = tokenbuf.size();
+ buf[0].pvBuffer = tokenbuf.data();
+ buf[1].BufferType = SECBUFFER_DATA;
+ buf[1].cbBuffer = databuf.size();
+ buf[1].pvBuffer = databuf.data();
+ buf[2].BufferType = SECBUFFER_PADDING;
+ buf[2].cbBuffer = padbuf.size();
+ buf[2].pvBuffer = padbuf.data();
+
+ SecBufferDesc bufdesc;
+ bufdesc.ulVersion = SECBUFFER_VERSION;
+ bufdesc.cBuffers = 3;
+ bufdesc.pBuffers = buf;
+
+ SECURITY_STATUS ret = sspi.W->EncryptMessage(&ctx, encrypt ? 0 : SECQOP_WRAP_NO_ENCRYPT, &bufdesc, 0);
+ sspi_log(QString("EncryptMessage() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret != SEC_E_OK) {
+ lastErrorCode = ret;
+ return ErrorEncrypt;
+ }
+
+ QByteArray fullbuf;
+ for (int i = 0; i < (int)bufdesc.cBuffers; ++i) {
+ fullbuf += QByteArray((const char *)bufdesc.pBuffers[i].pvBuffer, bufdesc.pBuffers[i].cbBuffer);
+ }
+
+ *out = fullbuf;
+ return Success;
+ }
+
+ ReturnCode decode(const QByteArray &in, QByteArray *out, bool *encrypted)
+ {
+ SecBuffer buf[2];
+ buf[0].BufferType = SECBUFFER_DATA;
+ buf[0].cbBuffer = 0;
+ buf[0].pvBuffer = NULL;
+ buf[1].BufferType = SECBUFFER_STREAM;
+ buf[1].cbBuffer = in.size();
+ buf[1].pvBuffer = (void *)in.data();
+
+ SecBufferDesc bufdesc;
+ bufdesc.ulVersion = SECBUFFER_VERSION;
+ bufdesc.cBuffers = 2;
+ bufdesc.pBuffers = buf;
+
+ ULONG fQOP;
+ SECURITY_STATUS ret = sspi.W->DecryptMessage(&ctx, &bufdesc, 0, &fQOP);
+ sspi_log(QString("DecryptMessage() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ if (ret == SEC_E_INCOMPLETE_MESSAGE) {
+ return NeedMoreData;
+ } else if (ret != SEC_E_OK) {
+ lastErrorCode = ret;
+ return ErrorDecrypt;
+ }
+
+ if (buf[0].pvBuffer) {
+ out->resize(buf[0].cbBuffer);
+ memcpy(out->data(), buf[0].pvBuffer, buf[0].cbBuffer);
+
+ SECURITY_STATUS ret = sspi.W->FreeContextBuffer(buf[0].pvBuffer);
+ sspi_log(QString("FreeContextBuffer() = %1\n").arg(SECURITY_STATUS_toString(ret)));
+ } else {
+ out->clear();
+ }
+
+ if (fQOP & SECQOP_WRAP_NO_ENCRYPT) {
+ *encrypted = false;
+ } else {
+ *encrypted = true;
+ }
+
+ return Success;
+ }
};
//----------------------------------------------------------------------------
// SaslGssapiSession
//----------------------------------------------------------------------------
// this class wraps KerberosSession to perform SASL GSSAPI. it hides away
// any SSPI details, and is thus very simple to use.
class SaslGssapiSession
{
private:
- int secflags;
- KerberosSession sess;
- int mode; // 0 = kerberos tokens, 1 = app packets
- bool authed;
- QByteArray inbuf;
+ int secflags;
+ KerberosSession sess;
+ int mode; // 0 = kerberos tokens, 1 = app packets
+ bool authed;
+ QByteArray inbuf;
- int max_enc_size; // most we can encrypt to them
- int max_dec_size; // most we are expected to decrypt from them
+ int max_enc_size; // most we can encrypt to them
+ int max_dec_size; // most we are expected to decrypt from them
public:
- enum SecurityFlags
- {
- // only one of these should be set
- RequireAtLeastInt = 0x0001,
- RequireConf = 0x0002
- };
-
- enum ReturnCode
- {
- Success,
- ErrorInit,
- ErrorKerberosStep,
- ErrorAppTokenDecode,
- ErrorAppTokenIsEncrypted,
- ErrorAppTokenWrongSize,
- ErrorAppTokenInvalid,
- ErrorAppTokenEncode,
- ErrorLayerTooWeak,
- ErrorEncode,
- ErrorDecode,
- ErrorDecodeTooLarge,
- ErrorDecodeNotEncrypted
- };
-
- // set this before auth, if you want
- QString authzid;
-
- // read-only
- bool do_layer, do_conf;
-
- SaslGssapiSession()
- {
- }
-
- ReturnCode init(const QString &proto, const QString &fqdn, int _secflags)
- {
- secflags = _secflags;
- mode = 0; // kerberos tokens
- authed = false;
-
- do_layer = false;
- do_conf = false;
-
- if(sess.init(proto + '/' + fqdn) != KerberosSession::Success)
- return ErrorInit;
-
- return Success;
- }
-
- ReturnCode step(const QByteArray &in, QByteArray *out, bool *authenticated)
- {
- if(authed)
- {
- out->clear();
- *authenticated = true;
- return Success;
- }
-
- if(mode == 0) // kerberos tokens
- {
- bool kerb_authed;
- if(sess.step(in, out, &kerb_authed) != KerberosSession::Success)
- return ErrorKerberosStep;
-
- if(kerb_authed)
- mode = 1; // switch to app packets
-
- *authenticated = false;
- }
- else if(mode == 1)
- {
- bool layerPossible = false;
- bool encryptionPossible = false;
- if(sess.ctx_attr & ISC_RET_INTEGRITY &&
- sess.ctx_attr & ISC_RET_MUTUAL_AUTH &&
- sess.ctx_attr & ISC_RET_SEQUENCE_DETECT)
- {
- layerPossible = true;
-
- if(sess.ctx_attr & ISC_RET_CONFIDENTIALITY)
- encryptionPossible = true;
- }
-
- if(layerPossible)
- {
- if(encryptionPossible)
- sspi_log("Kerberos application data protection supported (with encryption)\n");
- else
- sspi_log("Kerberos application data protection supported (without encryption)\n");
- }
- else
- sspi_log("No Kerberos application data protection supported\n");
-
- QByteArray decbuf;
- bool encrypted;
- if(sess.decode(in, &decbuf, &encrypted) != KerberosSession::Success)
- {
- sspi_log("Error decoding application token\n");
- return ErrorAppTokenDecode;
- }
-
- // this packet is supposed to be not encrypted
- if(encrypted)
- {
- sspi_log("Error, application token is encrypted\n");
- return ErrorAppTokenIsEncrypted;
- }
-
- // packet must be exactly 4 bytes
- if(decbuf.size() != 4)
- {
- sspi_log("Error, application token is the wrong size\n");
- return ErrorAppTokenWrongSize;
- }
-
- QString str;
- str.sprintf("%02x%02x%02x%02x",
- (unsigned int)decbuf[0],
- (unsigned int)decbuf[1],
- (unsigned int)decbuf[2],
- (unsigned int)decbuf[3]);
- sspi_log(QString("Received application token: [%1]\n").arg(str));
-
- unsigned char layermask = decbuf[0];
- quint32 maxsize = 0;
- maxsize += (unsigned char)decbuf[1];
- maxsize <<= 8;
- maxsize += (unsigned char)decbuf[2];
- maxsize <<= 8;
- maxsize += (unsigned char)decbuf[3];
-
- // if 'None' is all that is supported, then maxsize
- // must be zero
- if(layermask == 1 && maxsize > 0)
- {
- sspi_log("Error, supports no security layer but the max buffer size is not zero\n");
- return ErrorAppTokenInvalid;
- }
-
- // convert maxsize to a signed int, by capping it
- int _max_enc_size = cap_to_int<quint32>(maxsize);
-
- // parse out layermask
- bool saslLayerNone = false;
- bool saslLayerInt = false;
- bool saslLayerConf = false;
- QStringList saslLayerModes;
- if(layermask & 1)
- {
- saslLayerNone = true;
- saslLayerModes += "None";
- }
- if(layermask & 2)
- {
- saslLayerInt = true;
- saslLayerModes += "Int";
- }
- if(layermask & 4)
- {
- saslLayerConf = true;
- saslLayerModes += "Conf";
- }
-
- sspi_log(QString("Security layer modes supported: %1\n").arg(saslLayerModes.join(", ")));
- sspi_log(QString("Security layer max packet size: %1\n").arg(maxsize));
-
- // create outbound application token
- QByteArray obuf(4, 0); // initially 4 bytes
-
- // set one of use_conf or use_int, but not both
- bool use_conf = false;
- bool use_int = false;
- if(encryptionPossible && saslLayerConf)
- use_conf = true;
- else if(layerPossible && saslLayerInt)
- use_int = true;
- else if(!saslLayerNone)
- {
- sspi_log("Error, no compatible layer mode supported, not even 'None'\n");
- return ErrorLayerTooWeak;
- }
-
- if((secflags & RequireConf) && !use_conf)
- {
- sspi_log("Error, 'Conf' required but not supported\n");
- return ErrorLayerTooWeak;
- }
-
- if((secflags & RequireAtLeastInt) && !use_conf && !use_int)
- {
- sspi_log("Error, 'Conf' or 'Int' required but not supported\n");
- return ErrorLayerTooWeak;
- }
-
- if(use_conf)
- {
- sspi_log("Using 'Conf' layer\n");
- obuf[0] = 4;
- }
- else if(use_int)
- {
- sspi_log("Using 'Int' layer\n");
- obuf[0] = 2;
- }
- else
- {
- sspi_log("Using 'None' layer\n");
- obuf[0] = 1;
- }
-
- // as far as i can tell, there is no max decrypt size
- // with sspi. so we'll just pick some number.
- // a small one is good, to prevent excessive input
- // buffering.
- // in other parts of the code, it is assumed this
- // value is less than INT_MAX
- int _max_dec_size = 8192; // same as cyrus
-
- // max size must be zero if no security layer is used
- if(!use_conf && !use_int)
- _max_dec_size = 0;
-
- obuf[1] = (unsigned char)((_max_dec_size >> 16) & 0xff);
- obuf[2] = (unsigned char)((_max_dec_size >> 8) & 0xff);
- obuf[3] = (unsigned char)((_max_dec_size) & 0xff);
-
- if(!authzid.isEmpty())
- obuf += authzid.toUtf8();
-
- str.clear();
- for(int n = 0; n < obuf.size(); ++n)
- str += QString().sprintf("%02x", (unsigned int)obuf[n]);
- sspi_log(QString("Sending application token: [%1]\n").arg(str));
-
- if(sess.encode(obuf, out, false) != KerberosSession::Success)
- {
- sspi_log("Error encoding application token\n");
- return ErrorAppTokenEncode;
- }
-
- if(use_conf || use_int)
- do_layer = true;
- if(use_conf)
- do_conf = true;
-
- max_enc_size = _max_enc_size;
- max_dec_size = _max_dec_size;
-
- *authenticated = true;
- }
-
- return Success;
- }
-
- ReturnCode encode(const QByteArray &in, QByteArray *out)
- {
- if(!do_layer)
- {
- *out = in;
- return Success;
- }
-
- int local_encrypt_max;
- if(sess.get_max_encrypt_size(&local_encrypt_max) != KerberosSession::Success)
- return ErrorEncode;
-
- // send no more per-packet than what our local system will
- // encrypt AND no more than what the peer will accept.
- int chunk_max = qMin(local_encrypt_max, max_enc_size);
- if(chunk_max < 8)
- {
- sspi_log("Error, chunk_max is ridiculously small\n");
- return ErrorEncode;
- }
-
- QByteArray total_out;
-
- // break up into packets, if input exceeds max size
- int encoded = 0;
- while(encoded < in.size())
- {
- int left = in.size() - encoded;
- int chunk_size = qMin(left, chunk_max);
- QByteArray kerb_in = QByteArray::fromRawData(in.data() + encoded, chunk_size);
- QByteArray kerb_out;
- if(sess.encode(kerb_in, &kerb_out, do_conf) != KerberosSession::Success)
- return ErrorEncode;
-
- QByteArray sasl_out(kerb_out.size() + 4, 0);
-
- // SASL (not GSS!) uses a 4 byte length prefix
- quint32 len = kerb_out.size();
- sasl_out[0] = (unsigned char)((len >> 24) & 0xff);
- sasl_out[1] = (unsigned char)((len >> 16) & 0xff);
- sasl_out[2] = (unsigned char)((len >> 8) & 0xff);
- sasl_out[3] = (unsigned char)((len) & 0xff);
-
- memcpy(sasl_out.data() + 4, kerb_out.data(), kerb_out.size());
-
- encoded += kerb_in.size();
- total_out += sasl_out;
- }
-
- *out = total_out;
- return Success;
- }
-
- ReturnCode decode(const QByteArray &in, QByteArray *out)
- {
- if(!do_layer)
- {
- *out = in;
- return Success;
- }
-
- // buffer the input
- inbuf += in;
-
- QByteArray total_out;
-
- // the buffer might contain many packets. decode as many
- // as possible
- while(1)
- {
- if(inbuf.size() < 4)
- {
- // need more data
- break;
- }
-
- // SASL (not GSS!) uses a 4 byte length prefix
- quint32 ulen = 0;
- ulen += (unsigned char)inbuf[0];
- ulen <<= 8;
- ulen += (unsigned char)inbuf[1];
- ulen <<= 8;
- ulen += (unsigned char)inbuf[2];
- ulen <<= 8;
- ulen += (unsigned char)inbuf[3];
-
- // this capping is safe, because we throw error if the value
- // is too large, and an acceptable value will always be
- // lower than the maximum integer size.
- int len = cap_to_int<quint32>(ulen);
- if(len > max_dec_size)
- {
- // this means the peer ignored our max buffer size.
- // very evil, or we're under attack.
- sspi_log("Error, decode size too large\n");
- return ErrorDecodeTooLarge;
- }
-
- if(inbuf.size() - 4 < len)
- {
- // need more data
- break;
- }
-
- // take the packet from the inbuf
- QByteArray kerb_in = inbuf.mid(4, len);
- memmove(inbuf.data(), inbuf.data() + len + 4, inbuf.size() - len - 4);
- inbuf.resize(inbuf.size() - len - 4);
-
- // count incomplete packets as errors, since they are sasl framed
- QByteArray kerb_out;
- bool encrypted;
- if(sess.decode(kerb_in, &kerb_out, &encrypted) != KerberosSession::Success)
- return ErrorDecode;
-
- if(do_conf && !encrypted)
- {
- sspi_log("Error, received unencrypted packet in 'Conf' mode\n");
- return ErrorDecodeNotEncrypted;
- }
-
- total_out += kerb_out;
- }
-
- *out = total_out;
- return Success;
- }
+ enum SecurityFlags {
+ // only one of these should be set
+ RequireAtLeastInt = 0x0001,
+ RequireConf = 0x0002
+ };
+
+ enum ReturnCode {
+ Success,
+ ErrorInit,
+ ErrorKerberosStep,
+ ErrorAppTokenDecode,
+ ErrorAppTokenIsEncrypted,
+ ErrorAppTokenWrongSize,
+ ErrorAppTokenInvalid,
+ ErrorAppTokenEncode,
+ ErrorLayerTooWeak,
+ ErrorEncode,
+ ErrorDecode,
+ ErrorDecodeTooLarge,
+ ErrorDecodeNotEncrypted
+ };
+
+ // set this before auth, if you want
+ QString authzid;
+
+ // read-only
+ bool do_layer, do_conf;
+
+ SaslGssapiSession()
+ {
+ }
+
+ ReturnCode init(const QString &proto, const QString &fqdn, int _secflags)
+ {
+ secflags = _secflags;
+ mode = 0; // kerberos tokens
+ authed = false;
+
+ do_layer = false;
+ do_conf = false;
+
+ if (sess.init(proto + '/' + fqdn) != KerberosSession::Success) {
+ return ErrorInit;
+ }
+
+ return Success;
+ }
+
+ ReturnCode step(const QByteArray &in, QByteArray *out, bool *authenticated)
+ {
+ if (authed) {
+ out->clear();
+ *authenticated = true;
+ return Success;
+ }
+
+ if (mode == 0) { // kerberos tokens
+ bool kerb_authed;
+ if (sess.step(in, out, &kerb_authed) != KerberosSession::Success) {
+ return ErrorKerberosStep;
+ }
+
+ if (kerb_authed) {
+ mode = 1; // switch to app packets
+ }
+
+ *authenticated = false;
+ } else if (mode == 1) {
+ bool layerPossible = false;
+ bool encryptionPossible = false;
+ if (sess.ctx_attr & ISC_RET_INTEGRITY &&
+ sess.ctx_attr & ISC_RET_MUTUAL_AUTH &&
+ sess.ctx_attr & ISC_RET_SEQUENCE_DETECT) {
+ layerPossible = true;
+
+ if (sess.ctx_attr & ISC_RET_CONFIDENTIALITY) {
+ encryptionPossible = true;
+ }
+ }
+
+ if (layerPossible) {
+ if (encryptionPossible) {
+ sspi_log("Kerberos application data protection supported (with encryption)\n");
+ } else {
+ sspi_log("Kerberos application data protection supported (without encryption)\n");
+ }
+ } else {
+ sspi_log("No Kerberos application data protection supported\n");
+ }
+
+ QByteArray decbuf;
+ bool encrypted;
+ if (sess.decode(in, &decbuf, &encrypted) != KerberosSession::Success) {
+ sspi_log("Error decoding application token\n");
+ return ErrorAppTokenDecode;
+ }
+
+ // this packet is supposed to be not encrypted
+ if (encrypted) {
+ sspi_log("Error, application token is encrypted\n");
+ return ErrorAppTokenIsEncrypted;
+ }
+
+ // packet must be exactly 4 bytes
+ if (decbuf.size() != 4) {
+ sspi_log("Error, application token is the wrong size\n");
+ return ErrorAppTokenWrongSize;
+ }
+
+ QString str;
+ str.sprintf("%02x%02x%02x%02x",
+ (unsigned int)decbuf[0],
+ (unsigned int)decbuf[1],
+ (unsigned int)decbuf[2],
+ (unsigned int)decbuf[3]);
+ sspi_log(QString("Received application token: [%1]\n").arg(str));
+
+ unsigned char layermask = decbuf[0];
+ quint32 maxsize = 0;
+ maxsize += (unsigned char)decbuf[1];
+ maxsize <<= 8;
+ maxsize += (unsigned char)decbuf[2];
+ maxsize <<= 8;
+ maxsize += (unsigned char)decbuf[3];
+
+ // if 'None' is all that is supported, then maxsize
+ // must be zero
+ if (layermask == 1 && maxsize > 0) {
+ sspi_log("Error, supports no security layer but the max buffer size is not zero\n");
+ return ErrorAppTokenInvalid;
+ }
+
+ // convert maxsize to a signed int, by capping it
+ int _max_enc_size = cap_to_int<quint32>(maxsize);
+
+ // parse out layermask
+ bool saslLayerNone = false;
+ bool saslLayerInt = false;
+ bool saslLayerConf = false;
+ QStringList saslLayerModes;
+ if (layermask & 1) {
+ saslLayerNone = true;
+ saslLayerModes += "None";
+ }
+ if (layermask & 2) {
+ saslLayerInt = true;
+ saslLayerModes += "Int";
+ }
+ if (layermask & 4) {
+ saslLayerConf = true;
+ saslLayerModes += "Conf";
+ }
+
+ sspi_log(QString("Security layer modes supported: %1\n").arg(saslLayerModes.join(", ")));
+ sspi_log(QString("Security layer max packet size: %1\n").arg(maxsize));
+
+ // create outbound application token
+ QByteArray obuf(4, 0); // initially 4 bytes
+
+ // set one of use_conf or use_int, but not both
+ bool use_conf = false;
+ bool use_int = false;
+ if (encryptionPossible && saslLayerConf) {
+ use_conf = true;
+ } else if (layerPossible && saslLayerInt) {
+ use_int = true;
+ } else if (!saslLayerNone) {
+ sspi_log("Error, no compatible layer mode supported, not even 'None'\n");
+ return ErrorLayerTooWeak;
+ }
+
+ if ((secflags & RequireConf) && !use_conf) {
+ sspi_log("Error, 'Conf' required but not supported\n");
+ return ErrorLayerTooWeak;
+ }
+
+ if ((secflags & RequireAtLeastInt) && !use_conf && !use_int) {
+ sspi_log("Error, 'Conf' or 'Int' required but not supported\n");
+ return ErrorLayerTooWeak;
+ }
+
+ if (use_conf) {
+ sspi_log("Using 'Conf' layer\n");
+ obuf[0] = 4;
+ } else if (use_int) {
+ sspi_log("Using 'Int' layer\n");
+ obuf[0] = 2;
+ } else {
+ sspi_log("Using 'None' layer\n");
+ obuf[0] = 1;
+ }
+
+ // as far as i can tell, there is no max decrypt size
+ // with sspi. so we'll just pick some number.
+ // a small one is good, to prevent excessive input
+ // buffering.
+ // in other parts of the code, it is assumed this
+ // value is less than INT_MAX
+ int _max_dec_size = 8192; // same as cyrus
+
+ // max size must be zero if no security layer is used
+ if (!use_conf && !use_int) {
+ _max_dec_size = 0;
+ }
+
+ obuf[1] = (unsigned char)((_max_dec_size >> 16) & 0xff);
+ obuf[2] = (unsigned char)((_max_dec_size >> 8) & 0xff);
+ obuf[3] = (unsigned char)((_max_dec_size) & 0xff);
+
+ if (!authzid.isEmpty()) {
+ obuf += authzid.toUtf8();
+ }
+
+ str.clear();
+ for (int n = 0; n < obuf.size(); ++n) {
+ str += QString().sprintf("%02x", (unsigned int)obuf[n]);
+ }
+ sspi_log(QString("Sending application token: [%1]\n").arg(str));
+
+ if (sess.encode(obuf, out, false) != KerberosSession::Success) {
+ sspi_log("Error encoding application token\n");
+ return ErrorAppTokenEncode;
+ }
+
+ if (use_conf || use_int) {
+ do_layer = true;
+ }
+ if (use_conf) {
+ do_conf = true;
+ }
+
+ max_enc_size = _max_enc_size;
+ max_dec_size = _max_dec_size;
+
+ *authenticated = true;
+ }
+
+ return Success;
+ }
+
+ ReturnCode encode(const QByteArray &in, QByteArray *out)
+ {
+ if (!do_layer) {
+ *out = in;
+ return Success;
+ }
+
+ int local_encrypt_max;
+ if (sess.get_max_encrypt_size(&local_encrypt_max) != KerberosSession::Success) {
+ return ErrorEncode;
+ }
+
+ // send no more per-packet than what our local system will
+ // encrypt AND no more than what the peer will accept.
+ int chunk_max = qMin(local_encrypt_max, max_enc_size);
+ if (chunk_max < 8) {
+ sspi_log("Error, chunk_max is ridiculously small\n");
+ return ErrorEncode;
+ }
+
+ QByteArray total_out;
+
+ // break up into packets, if input exceeds max size
+ int encoded = 0;
+ while (encoded < in.size()) {
+ int left = in.size() - encoded;
+ int chunk_size = qMin(left, chunk_max);
+ QByteArray kerb_in = QByteArray::fromRawData(in.data() + encoded, chunk_size);
+ QByteArray kerb_out;
+ if (sess.encode(kerb_in, &kerb_out, do_conf) != KerberosSession::Success) {
+ return ErrorEncode;
+ }
+
+ QByteArray sasl_out(kerb_out.size() + 4, 0);
+
+ // SASL (not GSS!) uses a 4 byte length prefix
+ quint32 len = kerb_out.size();
+ sasl_out[0] = (unsigned char)((len >> 24) & 0xff);
+ sasl_out[1] = (unsigned char)((len >> 16) & 0xff);
+ sasl_out[2] = (unsigned char)((len >> 8) & 0xff);
+ sasl_out[3] = (unsigned char)((len) & 0xff);
+
+ memcpy(sasl_out.data() + 4, kerb_out.data(), kerb_out.size());
+
+ encoded += kerb_in.size();
+ total_out += sasl_out;
+ }
+
+ *out = total_out;
+ return Success;
+ }
+
+ ReturnCode decode(const QByteArray &in, QByteArray *out)
+ {
+ if (!do_layer) {
+ *out = in;
+ return Success;
+ }
+
+ // buffer the input
+ inbuf += in;
+
+ QByteArray total_out;
+
+ // the buffer might contain many packets. decode as many
+ // as possible
+ while (1) {
+ if (inbuf.size() < 4) {
+ // need more data
+ break;
+ }
+
+ // SASL (not GSS!) uses a 4 byte length prefix
+ quint32 ulen = 0;
+ ulen += (unsigned char)inbuf[0];
+ ulen <<= 8;
+ ulen += (unsigned char)inbuf[1];
+ ulen <<= 8;
+ ulen += (unsigned char)inbuf[2];
+ ulen <<= 8;
+ ulen += (unsigned char)inbuf[3];
+
+ // this capping is safe, because we throw error if the value
+ // is too large, and an acceptable value will always be
+ // lower than the maximum integer size.
+ int len = cap_to_int<quint32>(ulen);
+ if (len > max_dec_size) {
+ // this means the peer ignored our max buffer size.
+ // very evil, or we're under attack.
+ sspi_log("Error, decode size too large\n");
+ return ErrorDecodeTooLarge;
+ }
+
+ if (inbuf.size() - 4 < len) {
+ // need more data
+ break;
+ }
+
+ // take the packet from the inbuf
+ QByteArray kerb_in = inbuf.mid(4, len);
+ memmove(inbuf.data(), inbuf.data() + len + 4, inbuf.size() - len - 4);
+ inbuf.resize(inbuf.size() - len - 4);
+
+ // count incomplete packets as errors, since they are sasl framed
+ QByteArray kerb_out;
+ bool encrypted;
+ if (sess.decode(kerb_in, &kerb_out, &encrypted) != KerberosSession::Success) {
+ return ErrorDecode;
+ }
+
+ if (do_conf && !encrypted) {
+ sspi_log("Error, received unencrypted packet in 'Conf' mode\n");
+ return ErrorDecodeNotEncrypted;
+ }
+
+ total_out += kerb_out;
+ }
+
+ *out = total_out;
+ return Success;
+ }
};
//----------------------------------------------------------------------------
// SaslWinGss
//----------------------------------------------------------------------------
class SaslWinGss : public SASLContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- SaslGssapiSession *sess;
- bool authed;
- Result _result;
- SASL::AuthCondition _authCondition;
- QByteArray _step_to_net;
- QByteArray _to_net, _to_app;
- int enc;
- SafeTimer resultsReadyTrigger;
-
- QString opt_service, opt_host, opt_ext_id;
- int opt_ext_ssf;
- int opt_flags;
- int opt_minssf, opt_maxssf;
-
- QString opt_authzid;
-
- SaslWinGss(Provider *p) :
- SASLContext(p),
- sess(0),
- resultsReadyTrigger(this)
- {
- connect(&resultsReadyTrigger, SIGNAL(timeout()), SIGNAL(resultsReady()));
- resultsReadyTrigger.setSingleShot(true);
- }
-
- Provider::Context *clone() const
- {
- return 0;
- }
-
- virtual void reset()
- {
- delete sess;
- sess = 0;
- authed = false;
- _step_to_net.clear();
- _to_net.clear();
- _to_app.clear();
- resultsReadyTrigger.stop();
-
- opt_service.clear();
- opt_host.clear();
- opt_ext_id.clear();
- opt_authzid.clear();
- }
-
- virtual void setup(const QString &service, const QString &host, const HostPort *local, const HostPort *remote, const QString &ext_id, int ext_ssf)
- {
- // unused by this provider
- Q_UNUSED(local);
- Q_UNUSED(remote);
-
- opt_service = service;
- opt_host = host;
- opt_ext_id = ext_id;
- opt_ext_ssf = ext_ssf;
- }
-
- virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF)
- {
- opt_flags = (int)f;
- opt_minssf = minSSF;
- opt_maxssf = maxSSF;
- }
-
- virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst)
- {
- // we only support GSSAPI
- if(!mechlist.contains("GSSAPI"))
- {
- _result = Error;
- _authCondition = SASL::NoMechanism;
- resultsReadyTrigger.start();
- return;
- }
-
- // GSSAPI (or this provider) doesn't meet these requirements
- if(opt_flags & SASL::RequireForwardSecrecy
- || opt_flags & SASL::RequirePassCredentials
- || !allowClientSendFirst)
- {
- _result = Error;
- _authCondition = SASL::NoMechanism;
- resultsReadyTrigger.start();
- return;
- }
-
- sess = new SaslGssapiSession;
- sess->authzid = opt_authzid;
-
- int secflags = 0;
- if(opt_minssf > 1)
- secflags |= SaslGssapiSession::RequireConf;
- else if(opt_minssf == 1)
- secflags |= SaslGssapiSession::RequireAtLeastInt;
-
- SaslGssapiSession::ReturnCode ret = sess->init(opt_service, opt_host, secflags);
- if(ret != SaslGssapiSession::Success)
- {
- _result = Error;
- _authCondition = SASL::AuthFail;
- resultsReadyTrigger.start();
- return;
- }
-
- ret = sess->step(QByteArray(), &_step_to_net, &authed);
- if(ret != SaslGssapiSession::Success)
- {
- _result = Error;
- _authCondition = SASL::AuthFail;
- resultsReadyTrigger.start();
- return;
- }
-
- if(authed)
- _result = Success;
- else
- _result = Continue;
-
- resultsReadyTrigger.start();
- }
-
- virtual void startServer(const QString &realm, bool disableServerSendLast)
- {
- // server mode unsupported at this time
- Q_UNUSED(realm);
- Q_UNUSED(disableServerSendLast);
-
- _result = Error;
- _authCondition = SASL::AuthFail;
- resultsReadyTrigger.start();
- }
-
- virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit)
- {
- // server mode unsupported at this time
- Q_UNUSED(mech);
- Q_UNUSED(clientInit);
- }
-
- virtual void nextStep(const QByteArray &from_net)
- {
- SaslGssapiSession::ReturnCode ret = sess->step(from_net, &_step_to_net, &authed);
- if(ret != SaslGssapiSession::Success)
- {
- _result = Error;
- _authCondition = SASL::AuthFail;
- resultsReadyTrigger.start();
- return;
- }
-
- if(authed)
- _result = Success;
- else
- _result = Continue;
-
- resultsReadyTrigger.start();
- }
-
- virtual void tryAgain()
- {
- // we never ask for params, so this function should never be
- // called
- }
-
- virtual void update(const QByteArray &from_net, const QByteArray &from_app)
- {
- SaslGssapiSession::ReturnCode ret;
- QByteArray a;
-
- if(!from_net.isEmpty())
- {
- ret = sess->decode(from_net, &a);
- if(ret != SaslGssapiSession::Success)
- {
- _result = Error;
- resultsReadyTrigger.start();
- return;
- }
-
- _to_app += a;
- }
-
- if(!from_app.isEmpty())
- {
- ret = sess->encode(from_app, &a);
- if(ret != SaslGssapiSession::Success)
- {
- _result = Error;
- resultsReadyTrigger.start();
- return;
- }
-
- _to_net += a;
- enc += from_app.size();
- }
-
- _result = Success;
- resultsReadyTrigger.start();
- }
-
- virtual bool waitForResultsReady(int msecs)
- {
- // all results are ready instantly
- Q_UNUSED(msecs);
- resultsReadyTrigger.stop();
- return true;
- }
-
- virtual Result result() const
- {
- return _result;
- }
-
- virtual QStringList mechlist() const
- {
- // server mode unsupported at this time
- return QStringList();
- }
-
- virtual QString mech() const
- {
- // only mech we support :)
- return "GSSAPI";
- }
-
- virtual bool haveClientInit() const
- {
- // GSSAPI always has a client init response
- return true;
- }
-
- virtual QByteArray stepData() const
- {
- return _step_to_net;
- }
-
- virtual QByteArray to_net()
- {
- QByteArray a = _to_net;
- _to_net.clear();
- enc = 0;
- return a;
- }
-
- virtual int encoded() const
- {
- return enc;
- }
-
- virtual QByteArray to_app()
- {
- QByteArray a = _to_app;
- _to_app.clear();
- return a;
- }
-
- virtual int ssf() const
- {
- if(!sess->do_layer)
- return 0;
-
- if(sess->do_conf)
- {
- // TODO: calculate this value somehow? for now we'll
- // just hard code it to 56, which is basically what
- // cyrus does.
- return 56;
- }
- else
- return 1;
- }
-
- virtual SASL::AuthCondition authCondition() const
- {
- return _authCondition;
- }
-
- virtual SASL::Params clientParams() const
- {
- // we never ask for params
- return SASL::Params();
- }
-
- virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm)
- {
- // unused by this provider
- Q_UNUSED(user);
- Q_UNUSED(pass);
- Q_UNUSED(realm);
-
- if(authzid)
- {
- opt_authzid = *authzid;
- if(sess)
- sess->authzid = opt_authzid;
- }
- else
- {
- opt_authzid.clear();
- if(sess)
- sess->authzid.clear();
- }
- }
-
- virtual QStringList realmlist() const
- {
- // unused by this provider
- return QStringList();
- }
-
- virtual QString username() const
- {
- // server mode unsupported at this time
- return QString();
- }
-
- virtual QString authzid() const
- {
- // server mode unsupported at this time
- return QString();
- }
+ SaslGssapiSession *sess;
+ bool authed;
+ Result _result;
+ SASL::AuthCondition _authCondition;
+ QByteArray _step_to_net;
+ QByteArray _to_net, _to_app;
+ int enc;
+ SafeTimer resultsReadyTrigger;
+
+ QString opt_service, opt_host, opt_ext_id;
+ int opt_ext_ssf;
+ int opt_flags;
+ int opt_minssf, opt_maxssf;
+
+ QString opt_authzid;
+
+ SaslWinGss(Provider *p) :
+ SASLContext(p),
+ sess(0),
+ resultsReadyTrigger(this)
+ {
+ connect(&resultsReadyTrigger, SIGNAL(timeout()), SIGNAL(resultsReady()));
+ resultsReadyTrigger.setSingleShot(true);
+ }
+
+ Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual void reset()
+ {
+ delete sess;
+ sess = 0;
+ authed = false;
+ _step_to_net.clear();
+ _to_net.clear();
+ _to_app.clear();
+ resultsReadyTrigger.stop();
+
+ opt_service.clear();
+ opt_host.clear();
+ opt_ext_id.clear();
+ opt_authzid.clear();
+ }
+
+ virtual void setup(const QString &service, const QString &host, const HostPort *local, const HostPort *remote, const QString &ext_id, int ext_ssf)
+ {
+ // unused by this provider
+ Q_UNUSED(local);
+ Q_UNUSED(remote);
+
+ opt_service = service;
+ opt_host = host;
+ opt_ext_id = ext_id;
+ opt_ext_ssf = ext_ssf;
+ }
+
+ virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF)
+ {
+ opt_flags = (int)f;
+ opt_minssf = minSSF;
+ opt_maxssf = maxSSF;
+ }
+
+ virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst)
+ {
+ // we only support GSSAPI
+ if (!mechlist.contains("GSSAPI")) {
+ _result = Error;
+ _authCondition = SASL::NoMechanism;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ // GSSAPI (or this provider) doesn't meet these requirements
+ if (opt_flags & SASL::RequireForwardSecrecy
+ || opt_flags & SASL::RequirePassCredentials
+ || !allowClientSendFirst) {
+ _result = Error;
+ _authCondition = SASL::NoMechanism;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ sess = new SaslGssapiSession;
+ sess->authzid = opt_authzid;
+
+ int secflags = 0;
+ if (opt_minssf > 1) {
+ secflags |= SaslGssapiSession::RequireConf;
+ } else if (opt_minssf == 1) {
+ secflags |= SaslGssapiSession::RequireAtLeastInt;
+ }
+
+ SaslGssapiSession::ReturnCode ret = sess->init(opt_service, opt_host, secflags);
+ if (ret != SaslGssapiSession::Success) {
+ _result = Error;
+ _authCondition = SASL::AuthFail;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ ret = sess->step(QByteArray(), &_step_to_net, &authed);
+ if (ret != SaslGssapiSession::Success) {
+ _result = Error;
+ _authCondition = SASL::AuthFail;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ if (authed) {
+ _result = Success;
+ } else {
+ _result = Continue;
+ }
+
+ resultsReadyTrigger.start();
+ }
+
+ virtual void startServer(const QString &realm, bool disableServerSendLast)
+ {
+ // server mode unsupported at this time
+ Q_UNUSED(realm);
+ Q_UNUSED(disableServerSendLast);
+
+ _result = Error;
+ _authCondition = SASL::AuthFail;
+ resultsReadyTrigger.start();
+ }
+
+ virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit)
+ {
+ // server mode unsupported at this time
+ Q_UNUSED(mech);
+ Q_UNUSED(clientInit);
+ }
+
+ virtual void nextStep(const QByteArray &from_net)
+ {
+ SaslGssapiSession::ReturnCode ret = sess->step(from_net, &_step_to_net, &authed);
+ if (ret != SaslGssapiSession::Success) {
+ _result = Error;
+ _authCondition = SASL::AuthFail;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ if (authed) {
+ _result = Success;
+ } else {
+ _result = Continue;
+ }
+
+ resultsReadyTrigger.start();
+ }
+
+ virtual void tryAgain()
+ {
+ // we never ask for params, so this function should never be
+ // called
+ }
+
+ virtual void update(const QByteArray &from_net, const QByteArray &from_app)
+ {
+ SaslGssapiSession::ReturnCode ret;
+ QByteArray a;
+
+ if (!from_net.isEmpty()) {
+ ret = sess->decode(from_net, &a);
+ if (ret != SaslGssapiSession::Success) {
+ _result = Error;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ _to_app += a;
+ }
+
+ if (!from_app.isEmpty()) {
+ ret = sess->encode(from_app, &a);
+ if (ret != SaslGssapiSession::Success) {
+ _result = Error;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ _to_net += a;
+ enc += from_app.size();
+ }
+
+ _result = Success;
+ resultsReadyTrigger.start();
+ }
+
+ virtual bool waitForResultsReady(int msecs)
+ {
+ // all results are ready instantly
+ Q_UNUSED(msecs);
+ resultsReadyTrigger.stop();
+ return true;
+ }
+
+ virtual Result result() const
+ {
+ return _result;
+ }
+
+ virtual QStringList mechlist() const
+ {
+ // server mode unsupported at this time
+ return QStringList();
+ }
+
+ virtual QString mech() const
+ {
+ // only mech we support :)
+ return "GSSAPI";
+ }
+
+ virtual bool haveClientInit() const
+ {
+ // GSSAPI always has a client init response
+ return true;
+ }
+
+ virtual QByteArray stepData() const
+ {
+ return _step_to_net;
+ }
+
+ virtual QByteArray to_net()
+ {
+ QByteArray a = _to_net;
+ _to_net.clear();
+ enc = 0;
+ return a;
+ }
+
+ virtual int encoded() const
+ {
+ return enc;
+ }
+
+ virtual QByteArray to_app()
+ {
+ QByteArray a = _to_app;
+ _to_app.clear();
+ return a;
+ }
+
+ virtual int ssf() const
+ {
+ if (!sess->do_layer) {
+ return 0;
+ }
+
+ if (sess->do_conf) {
+ // TODO: calculate this value somehow? for now we'll
+ // just hard code it to 56, which is basically what
+ // cyrus does.
+ return 56;
+ } else {
+ return 1;
+ }
+ }
+
+ virtual SASL::AuthCondition authCondition() const
+ {
+ return _authCondition;
+ }
+
+ virtual SASL::Params clientParams() const
+ {
+ // we never ask for params
+ return SASL::Params();
+ }
+
+ virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm)
+ {
+ // unused by this provider
+ Q_UNUSED(user);
+ Q_UNUSED(pass);
+ Q_UNUSED(realm);
+
+ if (authzid) {
+ opt_authzid = *authzid;
+ if (sess) {
+ sess->authzid = opt_authzid;
+ }
+ } else {
+ opt_authzid.clear();
+ if (sess) {
+ sess->authzid.clear();
+ }
+ }
+ }
+
+ virtual QStringList realmlist() const
+ {
+ // unused by this provider
+ return QStringList();
+ }
+
+ virtual QString username() const
+ {
+ // server mode unsupported at this time
+ return QString();
+ }
+
+ virtual QString authzid() const
+ {
+ // server mode unsupported at this time
+ return QString();
+ }
};
#endif // !defined(FORWARD_ONLY)
//----------------------------------------------------------------------------
// MetaSasl
//----------------------------------------------------------------------------
#ifndef FORWARD_ONLY
class wingssProvider;
static bool wingssProvider_have_sspi(wingssProvider *provider);
#endif
class MetaSasl : public SASLContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- SASLContext *s;
-
- Result _result;
- SASL::AuthCondition _authCondition;
- SafeTimer resultsReadyTrigger;
- Synchronizer sync;
- bool waiting;
-
- QString opt_service, opt_host;
- bool have_opt_local, have_opt_remote;
- HostPort opt_local, opt_remote;
- QString opt_ext_id;
- int opt_ext_ssf;
- SASL::AuthFlags opt_flags;
- int opt_minssf, opt_maxssf;
-
- bool have_opt_user, have_opt_authzid, have_opt_pass, have_opt_realm;
- QString opt_user, opt_authzid, opt_realm;
- SecureArray opt_pass;
-
- class SaslProvider
- {
- public:
- SASLContext *sasl;
- bool ready;
- QStringList mechlist;
-
- SaslProvider() :
- sasl(0),
- ready(false)
- {
- }
- };
-
- QList<SaslProvider> saslProviders;
- bool serverInit_active;
- Result serverInit_result;
- QStringList serverInit_mechlist;
-
- MetaSasl(Provider *p) :
- SASLContext(p),
- resultsReadyTrigger(this),
- sync(this),
- waiting(false),
- serverInit_active(false)
- {
- s = 0;
-
- have_opt_user = false;
- have_opt_authzid = false;
- have_opt_pass = false;
- have_opt_realm = false;
-
- connect(&resultsReadyTrigger, SIGNAL(timeout()), SIGNAL(resultsReady()));
- resultsReadyTrigger.setSingleShot(true);
- }
-
- ~MetaSasl()
- {
- delete s;
- }
-
- virtual Provider::Context *clone() const
- {
- return 0;
- }
-
- void clearSaslProviders()
- {
- foreach(const SaslProvider &sp, saslProviders)
- delete sp.sasl;
-
- saslProviders.clear();
- }
-
- virtual void reset()
- {
- delete s;
- s = 0;
-
- resultsReadyTrigger.stop();
-
- opt_service.clear();
- opt_host.clear();
- opt_ext_id.clear();
- opt_user.clear();
- opt_authzid.clear();
- opt_realm.clear();
- opt_pass.clear();
-
- have_opt_user = false;
- have_opt_authzid = false;
- have_opt_pass = false;
- have_opt_realm = false;
-
- clearSaslProviders();
- serverInit_active = false;
- serverInit_mechlist.clear();
- }
-
- virtual void setup(const QString &service, const QString &host, const HostPort *local, const HostPort *remote, const QString &ext_id, int ext_ssf)
- {
- opt_service = service;
- opt_host = host;
- have_opt_local = false;
- have_opt_remote = false;
- if(local)
- {
- have_opt_local = true;
- opt_local = *local;
- }
- if(remote)
- {
- have_opt_remote = true;
- opt_remote = *remote;
- }
- opt_ext_id = ext_id;
- opt_ext_ssf = ext_ssf;
- }
-
- virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF)
- {
- opt_flags = f;
- opt_minssf = minSSF;
- opt_maxssf = maxSSF;
- }
-
- virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst)
- {
+ SASLContext *s;
+
+ Result _result;
+ SASL::AuthCondition _authCondition;
+ SafeTimer resultsReadyTrigger;
+ Synchronizer sync;
+ bool waiting;
+
+ QString opt_service, opt_host;
+ bool have_opt_local, have_opt_remote;
+ HostPort opt_local, opt_remote;
+ QString opt_ext_id;
+ int opt_ext_ssf;
+ SASL::AuthFlags opt_flags;
+ int opt_minssf, opt_maxssf;
+
+ bool have_opt_user, have_opt_authzid, have_opt_pass, have_opt_realm;
+ QString opt_user, opt_authzid, opt_realm;
+ SecureArray opt_pass;
+
+ class SaslProvider
+ {
+ public:
+ SASLContext *sasl;
+ bool ready;
+ QStringList mechlist;
+
+ SaslProvider() :
+ sasl(0),
+ ready(false)
+ {
+ }
+ };
+
+ QList<SaslProvider> saslProviders;
+ bool serverInit_active;
+ Result serverInit_result;
+ QStringList serverInit_mechlist;
+
+ MetaSasl(Provider *p) :
+ SASLContext(p),
+ resultsReadyTrigger(this),
+ sync(this),
+ waiting(false),
+ serverInit_active(false)
+ {
+ s = 0;
+
+ have_opt_user = false;
+ have_opt_authzid = false;
+ have_opt_pass = false;
+ have_opt_realm = false;
+
+ connect(&resultsReadyTrigger, SIGNAL(timeout()), SIGNAL(resultsReady()));
+ resultsReadyTrigger.setSingleShot(true);
+ }
+
+ ~MetaSasl()
+ {
+ delete s;
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ void clearSaslProviders()
+ {
+ foreach (const SaslProvider &sp, saslProviders) {
+ delete sp.sasl;
+ }
+
+ saslProviders.clear();
+ }
+
+ virtual void reset()
+ {
+ delete s;
+ s = 0;
+
+ resultsReadyTrigger.stop();
+
+ opt_service.clear();
+ opt_host.clear();
+ opt_ext_id.clear();
+ opt_user.clear();
+ opt_authzid.clear();
+ opt_realm.clear();
+ opt_pass.clear();
+
+ have_opt_user = false;
+ have_opt_authzid = false;
+ have_opt_pass = false;
+ have_opt_realm = false;
+
+ clearSaslProviders();
+ serverInit_active = false;
+ serverInit_mechlist.clear();
+ }
+
+ virtual void setup(const QString &service, const QString &host, const HostPort *local, const HostPort *remote, const QString &ext_id, int ext_ssf)
+ {
+ opt_service = service;
+ opt_host = host;
+ have_opt_local = false;
+ have_opt_remote = false;
+ if (local) {
+ have_opt_local = true;
+ opt_local = *local;
+ }
+ if (remote) {
+ have_opt_remote = true;
+ opt_remote = *remote;
+ }
+ opt_ext_id = ext_id;
+ opt_ext_ssf = ext_ssf;
+ }
+
+ virtual void setConstraints(SASL::AuthFlags f, int minSSF, int maxSSF)
+ {
+ opt_flags = f;
+ opt_minssf = minSSF;
+ opt_maxssf = maxSSF;
+ }
+
+ virtual void startClient(const QStringList &mechlist, bool allowClientSendFirst)
+ {
#ifndef FORWARD_ONLY
- if(mechlist.contains("GSSAPI") && wingssProvider_have_sspi((wingssProvider *)provider()))
- {
- s = new SaslWinGss(provider());
- }
- else
- {
+ if (mechlist.contains("GSSAPI") && wingssProvider_have_sspi((wingssProvider *)provider())) {
+ s = new SaslWinGss(provider());
+ } else {
#endif
- // collect providers supporting sasl, in priority order.
- // (note: providers() is in priority order already)
- ProviderList list;
- foreach(Provider *p, providers())
- {
- QString name = p->name();
-
- // skip ourself
- if(name == PROVIDER_NAME)
- continue;
-
- if(p->features().contains("sasl"))
- {
- // FIXME: improve qca so this isn't needed
- SASL tmp_object_to_cause_plugin_init(0, name);
-
- // add to the list
- list += p;
- }
- }
-
- if(!list.isEmpty())
- {
- // use the first
- s = static_cast<SASLContext *>(list.first()->createContext("sasl"));
- }
+ // collect providers supporting sasl, in priority order.
+ // (note: providers() is in priority order already)
+ ProviderList list;
+ foreach (Provider *p, providers()) {
+ QString name = p->name();
+
+ // skip ourself
+ if (name == PROVIDER_NAME) {
+ continue;
+ }
+
+ if (p->features().contains("sasl")) {
+ // FIXME: improve qca so this isn't needed
+ SASL tmp_object_to_cause_plugin_init(0, name);
+
+ // add to the list
+ list += p;
+ }
+ }
+
+ if (!list.isEmpty()) {
+ // use the first
+ s = static_cast<SASLContext *>(list.first()->createContext("sasl"));
+ }
#ifndef FORWARD_ONLY
- }
+ }
#endif
- if(!s)
- {
- // no usable provider? throw error
- _result = Error;
- _authCondition = SASL::NoMechanism;
- resultsReadyTrigger.start();
- return;
- }
-
- // proper parenting
- s->setParent(this);
-
- const HostPort *pLocal = 0;
- const HostPort *pRemote = 0;
- if(have_opt_local)
- pLocal = &opt_local;
- if(have_opt_remote)
- pRemote = &opt_remote;
- s->setup(opt_service, opt_host, pLocal, pRemote, opt_ext_id, opt_ext_ssf);
- s->setConstraints(opt_flags, opt_minssf, opt_maxssf);
-
- const QString *pUser = 0;
- const QString *pAuthzid = 0;
- const SecureArray *pPass = 0;
- const QString *pRealm = 0;
- if(have_opt_user)
- pUser = &opt_user;
- if(have_opt_authzid)
- pAuthzid = &opt_authzid;
- if(have_opt_pass)
- pPass = &opt_pass;
- if(have_opt_realm)
- pRealm = &opt_realm;
- s->setClientParams(pUser, pAuthzid, pPass, pRealm);
- connect(s, SIGNAL(resultsReady()), SLOT(s_resultsReady()));
-
- QString str = QString("MetaSasl: client using %1 with %2 mechs").arg(s->provider()->name(), QString::number(mechlist.count()));
- QCA_logTextMessage(str, Logger::Debug);
- s->startClient(mechlist, allowClientSendFirst);
- }
-
- virtual void startServer(const QString &realm, bool disableServerSendLast)
- {
- // collect mechs of all providers, by starting all of them
- serverInit_active = true;
-
- ProviderList list;
- foreach(Provider *p, providers())
- {
- QString name = p->name();
-
- // skip ourself
- if(name == PROVIDER_NAME)
- continue;
-
- if(p->features().contains("sasl"))
- {
- // FIXME: improve qca so this isn't needed
- SASL tmp_object_to_cause_plugin_init(0, name);
-
- // add to the list
- list += p;
- }
- }
-
- foreach(Provider *p, list)
- {
- SaslProvider sp;
-
- sp.sasl = static_cast<SASLContext *>(p->createContext("sasl"));
-
- // proper parenting
- sp.sasl->setParent(this);
-
- const HostPort *pLocal = 0;
- const HostPort *pRemote = 0;
- if(have_opt_local)
- pLocal = &opt_local;
- if(have_opt_remote)
- pRemote = &opt_remote;
- sp.sasl->setup(opt_service, opt_host, pLocal, pRemote, opt_ext_id, opt_ext_ssf);
- sp.sasl->setConstraints(opt_flags, opt_minssf, opt_maxssf);
- connect(sp.sasl, SIGNAL(resultsReady()), SLOT(serverInit_resultsReady()));
-
- saslProviders += sp;
-
- sp.sasl->startServer(realm, disableServerSendLast);
- }
- }
-
- virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit)
- {
- // choose a provider based on the mech
- int at = choose_provider(mech);
-
- // extract it and clean up the rest
- SASLContext *sasl = saslProviders[at].sasl;
- sasl->disconnect(this);
- saslProviders.removeAt(at);
- clearSaslProviders();
- serverInit_active = false;
-
- // use the chosen provider
- s = sasl;
- connect(s, SIGNAL(resultsReady()), SLOT(s_resultsReady()));
- s->serverFirstStep(mech, clientInit);
- }
-
- virtual void nextStep(const QByteArray &from_net)
- {
- s->nextStep(from_net);
- }
-
- virtual void tryAgain()
- {
- s->tryAgain();
- }
-
- virtual void update(const QByteArray &from_net, const QByteArray &from_app)
- {
- s->update(from_net, from_app);
- }
-
- virtual bool waitForResultsReady(int msecs)
- {
- if(serverInit_active)
- {
- waiting = true;
- bool ret = sync.waitForCondition(msecs);
- waiting = false;
- return ret;
- }
- else if(s)
- return s->waitForResultsReady(msecs);
- else
- return true;
- }
-
- virtual Result result() const
- {
- if(serverInit_active)
- return serverInit_result;
- else if(s)
- return s->result();
- else
- return _result;
- }
-
- virtual QStringList mechlist() const
- {
- return serverInit_mechlist;
- }
-
- virtual QString mech() const
- {
- if(s)
- return s->mech();
- else
- return QString();
- }
-
- virtual bool haveClientInit() const
- {
- return s->haveClientInit();
- }
-
- virtual QByteArray stepData() const
- {
- return s->stepData();
- }
-
- virtual QByteArray to_net()
- {
- return s->to_net();
- }
-
- virtual int encoded() const
- {
- return s->encoded();
- }
-
- virtual QByteArray to_app()
- {
- return s->to_app();
- }
-
- virtual int ssf() const
- {
- return s->ssf();
- }
-
- virtual SASL::AuthCondition authCondition() const
- {
- if(s)
- return s->authCondition();
- else
- return _authCondition;
- }
-
- virtual SASL::Params clientParams() const
- {
- return s->clientParams();
- }
-
- virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm)
- {
- if(!s)
- {
- if(user)
- {
- have_opt_user = true;
- opt_user = *user;
- }
- if(authzid)
- {
- have_opt_authzid = true;
- opt_authzid = *authzid;
- }
- if(pass)
- {
- have_opt_pass = true;
- opt_pass = *pass;
- }
- if(realm)
- {
- have_opt_realm = true;
- opt_realm = *realm;
- }
- }
- else
- {
- s->setClientParams(user, authzid, pass, realm);
- }
- }
-
- virtual QStringList realmlist() const
- {
- return s->realmlist();
- }
-
- virtual QString username() const
- {
- return s->username();
- }
-
- virtual QString authzid() const
- {
- return s->authzid();
- }
+ if (!s) {
+ // no usable provider? throw error
+ _result = Error;
+ _authCondition = SASL::NoMechanism;
+ resultsReadyTrigger.start();
+ return;
+ }
+
+ // proper parenting
+ s->setParent(this);
+
+ const HostPort *pLocal = 0;
+ const HostPort *pRemote = 0;
+ if (have_opt_local) {
+ pLocal = &opt_local;
+ }
+ if (have_opt_remote) {
+ pRemote = &opt_remote;
+ }
+ s->setup(opt_service, opt_host, pLocal, pRemote, opt_ext_id, opt_ext_ssf);
+ s->setConstraints(opt_flags, opt_minssf, opt_maxssf);
+
+ const QString *pUser = 0;
+ const QString *pAuthzid = 0;
+ const SecureArray *pPass = 0;
+ const QString *pRealm = 0;
+ if (have_opt_user) {
+ pUser = &opt_user;
+ }
+ if (have_opt_authzid) {
+ pAuthzid = &opt_authzid;
+ }
+ if (have_opt_pass) {
+ pPass = &opt_pass;
+ }
+ if (have_opt_realm) {
+ pRealm = &opt_realm;
+ }
+ s->setClientParams(pUser, pAuthzid, pPass, pRealm);
+ connect(s, SIGNAL(resultsReady()), SLOT(s_resultsReady()));
+
+ QString str = QString("MetaSasl: client using %1 with %2 mechs").arg(s->provider()->name(), QString::number(mechlist.count()));
+ QCA_logTextMessage(str, Logger::Debug);
+ s->startClient(mechlist, allowClientSendFirst);
+ }
+
+ virtual void startServer(const QString &realm, bool disableServerSendLast)
+ {
+ // collect mechs of all providers, by starting all of them
+ serverInit_active = true;
+
+ ProviderList list;
+ foreach (Provider *p, providers()) {
+ QString name = p->name();
+
+ // skip ourself
+ if (name == PROVIDER_NAME) {
+ continue;
+ }
+
+ if (p->features().contains("sasl")) {
+ // FIXME: improve qca so this isn't needed
+ SASL tmp_object_to_cause_plugin_init(0, name);
+
+ // add to the list
+ list += p;
+ }
+ }
+
+ foreach (Provider *p, list) {
+ SaslProvider sp;
+
+ sp.sasl = static_cast<SASLContext *>(p->createContext("sasl"));
+
+ // proper parenting
+ sp.sasl->setParent(this);
+
+ const HostPort *pLocal = 0;
+ const HostPort *pRemote = 0;
+ if (have_opt_local) {
+ pLocal = &opt_local;
+ }
+ if (have_opt_remote) {
+ pRemote = &opt_remote;
+ }
+ sp.sasl->setup(opt_service, opt_host, pLocal, pRemote, opt_ext_id, opt_ext_ssf);
+ sp.sasl->setConstraints(opt_flags, opt_minssf, opt_maxssf);
+ connect(sp.sasl, SIGNAL(resultsReady()), SLOT(serverInit_resultsReady()));
+
+ saslProviders += sp;
+
+ sp.sasl->startServer(realm, disableServerSendLast);
+ }
+ }
+
+ virtual void serverFirstStep(const QString &mech, const QByteArray *clientInit)
+ {
+ // choose a provider based on the mech
+ int at = choose_provider(mech);
+
+ // extract it and clean up the rest
+ SASLContext *sasl = saslProviders[at].sasl;
+ sasl->disconnect(this);
+ saslProviders.removeAt(at);
+ clearSaslProviders();
+ serverInit_active = false;
+
+ // use the chosen provider
+ s = sasl;
+ connect(s, SIGNAL(resultsReady()), SLOT(s_resultsReady()));
+ s->serverFirstStep(mech, clientInit);
+ }
+
+ virtual void nextStep(const QByteArray &from_net)
+ {
+ s->nextStep(from_net);
+ }
+
+ virtual void tryAgain()
+ {
+ s->tryAgain();
+ }
+
+ virtual void update(const QByteArray &from_net, const QByteArray &from_app)
+ {
+ s->update(from_net, from_app);
+ }
+
+ virtual bool waitForResultsReady(int msecs)
+ {
+ if (serverInit_active) {
+ waiting = true;
+ bool ret = sync.waitForCondition(msecs);
+ waiting = false;
+ return ret;
+ } else if (s) {
+ return s->waitForResultsReady(msecs);
+ } else {
+ return true;
+ }
+ }
+
+ virtual Result result() const
+ {
+ if (serverInit_active) {
+ return serverInit_result;
+ } else if (s) {
+ return s->result();
+ } else {
+ return _result;
+ }
+ }
+
+ virtual QStringList mechlist() const
+ {
+ return serverInit_mechlist;
+ }
+
+ virtual QString mech() const
+ {
+ if (s) {
+ return s->mech();
+ } else {
+ return QString();
+ }
+ }
+
+ virtual bool haveClientInit() const
+ {
+ return s->haveClientInit();
+ }
+
+ virtual QByteArray stepData() const
+ {
+ return s->stepData();
+ }
+
+ virtual QByteArray to_net()
+ {
+ return s->to_net();
+ }
+
+ virtual int encoded() const
+ {
+ return s->encoded();
+ }
+
+ virtual QByteArray to_app()
+ {
+ return s->to_app();
+ }
+
+ virtual int ssf() const
+ {
+ return s->ssf();
+ }
+
+ virtual SASL::AuthCondition authCondition() const
+ {
+ if (s) {
+ return s->authCondition();
+ } else {
+ return _authCondition;
+ }
+ }
+
+ virtual SASL::Params clientParams() const
+ {
+ return s->clientParams();
+ }
+
+ virtual void setClientParams(const QString *user, const QString *authzid, const SecureArray *pass, const QString *realm)
+ {
+ if (!s) {
+ if (user) {
+ have_opt_user = true;
+ opt_user = *user;
+ }
+ if (authzid) {
+ have_opt_authzid = true;
+ opt_authzid = *authzid;
+ }
+ if (pass) {
+ have_opt_pass = true;
+ opt_pass = *pass;
+ }
+ if (realm) {
+ have_opt_realm = true;
+ opt_realm = *realm;
+ }
+ } else {
+ s->setClientParams(user, authzid, pass, realm);
+ }
+ }
+
+ virtual QStringList realmlist() const
+ {
+ return s->realmlist();
+ }
+
+ virtual QString username() const
+ {
+ return s->username();
+ }
+
+ virtual QString authzid() const
+ {
+ return s->authzid();
+ }
private slots:
- void s_resultsReady()
- {
- emit resultsReady();
- }
-
- void serverInit_resultsReady()
- {
- SASLContext *sasl = (SASLContext *)sender();
-
- int at = -1;
- for(int n = 0; n < saslProviders.count(); ++n)
- {
- if(saslProviders[n].sasl == sasl)
- {
- at = n;
- break;
- }
- }
- if(at == -1)
- return;
-
- if(sasl->result() == Success)
- {
- saslProviders[at].ready = true;
- saslProviders[at].mechlist = sasl->mechlist();
-
- bool allReady = true;
- for(int n = 0; n < saslProviders.count(); ++n)
- {
- if(!saslProviders[n].ready)
- {
- allReady = false;
- break;
- }
- }
-
- if(allReady)
- {
- // indicate success
- serverInit_result = Success;
- serverInit_mechlist = combine_mechlists();
-
- if(waiting)
- sync.conditionMet();
- else
- emit resultsReady();
- }
- }
- else
- {
- delete sasl;
- saslProviders.removeAt(at);
-
- if(saslProviders.isEmpty())
- {
- // indicate error
- serverInit_result = Error;
- _authCondition = SASL::NoMechanism;
-
- if(waiting)
- sync.conditionMet();
- else
- emit resultsReady();
- }
- }
- }
+ void s_resultsReady()
+ {
+ emit resultsReady();
+ }
+
+ void serverInit_resultsReady()
+ {
+ SASLContext *sasl = (SASLContext *)sender();
+
+ int at = -1;
+ for (int n = 0; n < saslProviders.count(); ++n) {
+ if (saslProviders[n].sasl == sasl) {
+ at = n;
+ break;
+ }
+ }
+ if (at == -1) {
+ return;
+ }
+
+ if (sasl->result() == Success) {
+ saslProviders[at].ready = true;
+ saslProviders[at].mechlist = sasl->mechlist();
+
+ bool allReady = true;
+ for (int n = 0; n < saslProviders.count(); ++n) {
+ if (!saslProviders[n].ready) {
+ allReady = false;
+ break;
+ }
+ }
+
+ if (allReady) {
+ // indicate success
+ serverInit_result = Success;
+ serverInit_mechlist = combine_mechlists();
+
+ if (waiting) {
+ sync.conditionMet();
+ } else {
+ emit resultsReady();
+ }
+ }
+ } else {
+ delete sasl;
+ saslProviders.removeAt(at);
+
+ if (saslProviders.isEmpty()) {
+ // indicate error
+ serverInit_result = Error;
+ _authCondition = SASL::NoMechanism;
+
+ if (waiting) {
+ sync.conditionMet();
+ } else {
+ emit resultsReady();
+ }
+ }
+ }
+ }
private:
- QStringList combine_mechlists()
- {
- QStringList out;
-
- // FIXME: consider prioritizing certain mechs?
- foreach(const SaslProvider &sp, saslProviders)
- {
- foreach(const QString &mech, sp.mechlist)
- {
- if(!out.contains(mech))
- out += mech;
- }
- }
-
- return out;
- }
-
- int choose_provider(const QString &mech)
- {
- int at = -1;
-
- // find a provider for this mech
- for(int n = 0; n < saslProviders.count(); ++n)
- {
- const SaslProvider &sp = saslProviders[n];
- if(sp.mechlist.contains(mech))
- {
- at = n;
- break;
- }
- }
-
- // no provider offered this mech? then just go with the
- // first provider
- if(at == -1)
- at = 0;
-
- return at;
- }
+ QStringList combine_mechlists()
+ {
+ QStringList out;
+
+ // FIXME: consider prioritizing certain mechs?
+ foreach (const SaslProvider &sp, saslProviders) {
+ foreach (const QString &mech, sp.mechlist) {
+ if (!out.contains(mech)) {
+ out += mech;
+ }
+ }
+ }
+
+ return out;
+ }
+
+ int choose_provider(const QString &mech)
+ {
+ int at = -1;
+
+ // find a provider for this mech
+ for (int n = 0; n < saslProviders.count(); ++n) {
+ const SaslProvider &sp = saslProviders[n];
+ if (sp.mechlist.contains(mech)) {
+ at = n;
+ break;
+ }
+ }
+
+ // no provider offered this mech? then just go with the
+ // first provider
+ if (at == -1) {
+ at = 0;
+ }
+
+ return at;
+ }
};
class wingssProvider : public Provider
{
public:
- mutable QMutex m;
- mutable bool forced_priority;
- bool have_sspi;
-
- wingssProvider() :
- forced_priority(false),
- have_sspi(false)
- {
- }
-
- virtual void init()
- {
+ mutable QMutex m;
+ mutable bool forced_priority;
+ bool have_sspi;
+
+ wingssProvider() :
+ forced_priority(false),
+ have_sspi(false)
+ {
+ }
+
+ virtual void init()
+ {
#ifndef FORWARD_ONLY
- sspi_set_logger(do_log);
- have_sspi = sspi_load();
+ sspi_set_logger(do_log);
+ have_sspi = sspi_load();
#endif
- }
+ }
- ~wingssProvider()
- {
+ ~wingssProvider()
+ {
#ifndef FORWARD_ONLY
- if(have_sspi)
- sspi_unload();
+ if (have_sspi) {
+ sspi_unload();
+ }
#endif
- }
-
- virtual int qcaVersion() const
- {
- return QCA_VERSION;
- }
-
- virtual QString name() const
- {
- return PROVIDER_NAME;
- }
-
- virtual QStringList features() const
- {
- // due to context manipulation, this plugin is only designed
- // for qca 2.0 at this time, and not a possible 2.1, etc.
- if((qcaVersion() & 0xffff00) > 0x020000)
- return QStringList();
-
- m.lock();
- // FIXME: we need to prioritize this plugin to be higher
- // than other plugins by default. unfortunately there's
- // no clean way to do this. we can't change our priority
- // until we are slotted into the qca provider system. the
- // constructor, qcaVersion, and name functions are all
- // guaranteed to be called, but unfortunately they are
- // only guaranteed to be called before the slotting. the
- // features function is essentially guaranteed to be called
- // after the slotting though, since QCA::isSupported()
- // trips it, and any proper QCA app will call isSupported.
- if(!forced_priority)
- {
- forced_priority = true;
- setProviderPriority(PROVIDER_NAME, 0);
- }
- m.unlock();
-
- QStringList list;
- list += "sasl";
- return list;
- }
-
- virtual Context *createContext(const QString &type)
- {
- if(type == "sasl")
- return new MetaSasl(this);
- else
- return 0;
- }
+ }
+
+ virtual int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ virtual QString name() const
+ {
+ return PROVIDER_NAME;
+ }
+
+ virtual QStringList features() const
+ {
+ // due to context manipulation, this plugin is only designed
+ // for qca 2.0 at this time, and not a possible 2.1, etc.
+ if ((qcaVersion() & 0xffff00) > 0x020000) {
+ return QStringList();
+ }
+
+ m.lock();
+ // FIXME: we need to prioritize this plugin to be higher
+ // than other plugins by default. unfortunately there's
+ // no clean way to do this. we can't change our priority
+ // until we are slotted into the qca provider system. the
+ // constructor, qcaVersion, and name functions are all
+ // guaranteed to be called, but unfortunately they are
+ // only guaranteed to be called before the slotting. the
+ // features function is essentially guaranteed to be called
+ // after the slotting though, since QCA::isSupported()
+ // trips it, and any proper QCA app will call isSupported.
+ if (!forced_priority) {
+ forced_priority = true;
+ setProviderPriority(PROVIDER_NAME, 0);
+ }
+ m.unlock();
+
+ QStringList list;
+ list += "sasl";
+ return list;
+ }
+
+ virtual Context *createContext(const QString &type)
+ {
+ if (type == "sasl") {
+ return new MetaSasl(this);
+ } else {
+ return 0;
+ }
+ }
#ifndef FORWARD_ONLY
- static void do_log(const QString &str)
- {
- QCA_logTextMessage(str, Logger::Debug);
- }
+ static void do_log(const QString &str)
+ {
+ QCA_logTextMessage(str, Logger::Debug);
+ }
#endif
};
#ifndef FORWARD_ONLY
bool wingssProvider_have_sspi(wingssProvider *provider)
{
- return provider->have_sspi;
+ return provider->have_sspi;
}
#endif
}
using namespace wingssQCAPlugin;
//----------------------------------------------------------------------------
// wingssPlugin
//----------------------------------------------------------------------------
class wingssPlugin : public QObject, public QCAPlugin
{
- Q_OBJECT
+ Q_OBJECT
#if QT_VERSION >= 0x050000
- Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
+ Q_PLUGIN_METADATA(IID "com.affinix.qca.Plugin/1.0")
#endif
- Q_INTERFACES(QCAPlugin)
+ Q_INTERFACES(QCAPlugin)
public:
- virtual Provider *createProvider() { return new wingssProvider; }
+ virtual Provider *createProvider()
+ {
+ return new wingssProvider;
+ }
};
#include "qca-wingss.moc"
#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(qca_wingss, wingssPlugin)
#endif
diff --git a/src/qca_basic.cpp b/src/qca_basic.cpp
index 395ae8b0..ea0f5027 100644
--- a/src/qca_basic.cpp
+++ b/src/qca_basic.cpp
@@ -1,625 +1,635 @@
/*
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004,2005,2007 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_basic.h"
#include "qcaprovider.h"
#include <QMutexLocker>
#include <QtGlobal>
-namespace QCA {
+namespace QCA
+{
// from qca_core.cpp
QMutex *global_random_mutex();
Random *global_random();
Provider::Context *getContext(const QString &type, Provider *p);
// from qca_publickey.cpp
ProviderList allProviders();
Provider *providerForName(const QString &name);
static void mergeList(QStringList *a, const QStringList &b)
{
- foreach(const QString &s, b)
- {
- if(!a->contains(s))
- a->append(s);
- }
+ foreach (const QString &s, b) {
+ if (!a->contains(s)) {
+ a->append(s);
+ }
+ }
}
static QStringList get_hash_types(Provider *p)
{
- QStringList out;
- InfoContext *c = static_cast<InfoContext *>(getContext("info", p));
- if(!c)
- return out;
- out = c->supportedHashTypes();
- delete c;
- return out;
+ QStringList out;
+ InfoContext *c = static_cast<InfoContext *>(getContext("info", p));
+ if (!c) {
+ return out;
+ }
+ out = c->supportedHashTypes();
+ delete c;
+ return out;
}
static QStringList get_cipher_types(Provider *p)
{
- QStringList out;
- InfoContext *c = static_cast<InfoContext *>(getContext("info", p));
- if(!c)
- return out;
- out = c->supportedCipherTypes();
- delete c;
- return out;
+ QStringList out;
+ InfoContext *c = static_cast<InfoContext *>(getContext("info", p));
+ if (!c) {
+ return out;
+ }
+ out = c->supportedCipherTypes();
+ delete c;
+ return out;
}
static QStringList get_mac_types(Provider *p)
{
- QStringList out;
- InfoContext *c = static_cast<InfoContext *>(getContext("info", p));
- if(!c)
- return out;
- out = c->supportedMACTypes();
- delete c;
- return out;
-}
-
-static QStringList get_types(QStringList (*get_func)(Provider *p), const QString &provider)
-{
- QStringList out;
- if(!provider.isEmpty())
- {
- Provider *p = providerForName(provider);
- if(p)
- out = get_func(p);
- }
- else
- {
- ProviderList pl = allProviders();
- foreach(Provider *p, pl)
- mergeList(&out, get_func(p));
- }
- return out;
+ QStringList out;
+ InfoContext *c = static_cast<InfoContext *>(getContext("info", p));
+ if (!c) {
+ return out;
+ }
+ out = c->supportedMACTypes();
+ delete c;
+ return out;
+}
+
+static QStringList get_types(QStringList(*get_func)(Provider *p), const QString &provider)
+{
+ QStringList out;
+ if (!provider.isEmpty()) {
+ Provider *p = providerForName(provider);
+ if (p) {
+ out = get_func(p);
+ }
+ } else {
+ ProviderList pl = allProviders();
+ foreach (Provider *p, pl) {
+ mergeList(&out, get_func(p));
+ }
+ }
+ return out;
}
static QStringList supportedHashTypes(const QString &provider)
{
- return get_types(get_hash_types, provider);
+ return get_types(get_hash_types, provider);
}
static QStringList supportedCipherTypes(const QString &provider)
{
- return get_types(get_cipher_types, provider);
+ return get_types(get_cipher_types, provider);
}
static QStringList supportedMACTypes(const QString &provider)
{
- return get_types(get_mac_types, provider);
+ return get_types(get_mac_types, provider);
}
//----------------------------------------------------------------------------
// Random
//----------------------------------------------------------------------------
Random::Random(const QString &provider)
-:Algorithm("random", provider)
+ : Algorithm("random", provider)
{
}
Random::Random(const Random &from)
-:Algorithm(from)
+ : Algorithm(from)
{
}
Random::~Random()
{
}
-Random & Random::operator=(const Random &from)
+Random &Random::operator=(const Random &from)
{
- Algorithm::operator=(from);
- return *this;
+ Algorithm::operator=(from);
+ return *this;
}
uchar Random::nextByte()
{
- return (uchar)(nextBytes(1)[0]);
+ return (uchar)(nextBytes(1)[0]);
}
SecureArray Random::nextBytes(int size)
{
- return static_cast<RandomContext *>(context())->nextBytes(size);
+ return static_cast<RandomContext *>(context())->nextBytes(size);
}
uchar Random::randomChar()
{
- QMutexLocker locker(global_random_mutex());
- return global_random()->nextByte();
+ QMutexLocker locker(global_random_mutex());
+ return global_random()->nextByte();
}
int Random::randomInt()
{
- QMutexLocker locker(global_random_mutex());
- SecureArray a = global_random()->nextBytes(sizeof(int));
- int x;
- memcpy(&x, a.data(), a.size());
- return x;
+ QMutexLocker locker(global_random_mutex());
+ SecureArray a = global_random()->nextBytes(sizeof(int));
+ int x;
+ memcpy(&x, a.data(), a.size());
+ return x;
}
SecureArray Random::randomArray(int size)
{
- QMutexLocker locker(global_random_mutex());
- return global_random()->nextBytes(size);
+ QMutexLocker locker(global_random_mutex());
+ return global_random()->nextBytes(size);
}
//----------------------------------------------------------------------------
// Hash
//----------------------------------------------------------------------------
Hash::Hash(const QString &type, const QString &provider)
-:Algorithm(type, provider)
+ : Algorithm(type, provider)
{
}
Hash::Hash(const Hash &from)
-:Algorithm(from), BufferedComputation(from)
+ : Algorithm(from), BufferedComputation(from)
{
}
Hash::~Hash()
{
}
-Hash & Hash::operator=(const Hash &from)
+Hash &Hash::operator=(const Hash &from)
{
- Algorithm::operator=(from);
- return *this;
+ Algorithm::operator=(from);
+ return *this;
}
QStringList Hash::supportedTypes(const QString &provider)
{
- return supportedHashTypes(provider);
+ return supportedHashTypes(provider);
}
QString Hash::type() const
{
- // algorithm type is the same as the hash type
- return Algorithm::type();
+ // algorithm type is the same as the hash type
+ return Algorithm::type();
}
void Hash::clear()
{
- static_cast<HashContext *>(context())->clear();
+ static_cast<HashContext *>(context())->clear();
}
void Hash::update(const MemoryRegion &a)
{
- static_cast<HashContext *>(context())->update(a);
+ static_cast<HashContext *>(context())->update(a);
}
void Hash::update(const QByteArray &a)
{
- update(MemoryRegion(a));
+ update(MemoryRegion(a));
}
void Hash::update(const char *data, int len)
{
- if(len < 0)
- len = qstrlen(data);
- if(len == 0)
- return;
+ if (len < 0) {
+ len = qstrlen(data);
+ }
+ if (len == 0) {
+ return;
+ }
- update(MemoryRegion(QByteArray::fromRawData(data, len)));
+ update(MemoryRegion(QByteArray::fromRawData(data, len)));
}
// Reworked from KMD5, from KDE's kdelibs
void Hash::update(QIODevice *file)
{
- char buffer[1024];
- int len;
+ char buffer[1024];
+ int len;
- while ((len=file->read(reinterpret_cast<char*>(buffer), sizeof(buffer))) > 0)
- update(buffer, len);
+ while ((len = file->read(reinterpret_cast<char *>(buffer), sizeof(buffer))) > 0) {
+ update(buffer, len);
+ }
}
MemoryRegion Hash::final()
{
- return static_cast<HashContext *>(context())->final();
+ return static_cast<HashContext *>(context())->final();
}
MemoryRegion Hash::hash(const MemoryRegion &a)
{
- return process(a);
+ return process(a);
}
QString Hash::hashToString(const MemoryRegion &a)
{
- return arrayToHex(hash(a).toByteArray());
+ return arrayToHex(hash(a).toByteArray());
}
//----------------------------------------------------------------------------
// Cipher
//----------------------------------------------------------------------------
class Cipher::Private
{
public:
- QString type;
- Cipher::Mode mode;
- Cipher::Padding pad;
- Direction dir;
- SymmetricKey key;
- InitializationVector iv;
- AuthTag tag;
-
- bool ok, done;
+ QString type;
+ Cipher::Mode mode;
+ Cipher::Padding pad;
+ Direction dir;
+ SymmetricKey key;
+ InitializationVector iv;
+ AuthTag tag;
+
+ bool ok, done;
};
Cipher::Cipher(const QString &type, Mode mode, Padding pad,
- Direction dir, const SymmetricKey &key,
- const InitializationVector &iv,
- const QString &provider)
-:Algorithm(withAlgorithms(type, mode, pad), provider)
+ Direction dir, const SymmetricKey &key,
+ const InitializationVector &iv,
+ const QString &provider)
+ : Algorithm(withAlgorithms(type, mode, pad), provider)
{
- d = new Private;
- d->type = type;
- d->mode = mode;
- d->pad = pad;
- if(!key.isEmpty())
- setup(dir, key, iv);
+ d = new Private;
+ d->type = type;
+ d->mode = mode;
+ d->pad = pad;
+ if (!key.isEmpty()) {
+ setup(dir, key, iv);
+ }
}
Cipher::Cipher(const QString &type, Cipher::Mode mode, Cipher::Padding pad, Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag, const QString &provider)
- : Algorithm(withAlgorithms(type, mode, pad), provider)
+ : Algorithm(withAlgorithms(type, mode, pad), provider)
{
- d = new Private;
- d->type = type;
- d->mode = mode;
- d->pad = pad;
- d->tag = tag;
- if(!key.isEmpty())
- setup(dir, key, iv, tag);
+ d = new Private;
+ d->type = type;
+ d->mode = mode;
+ d->pad = pad;
+ d->tag = tag;
+ if (!key.isEmpty()) {
+ setup(dir, key, iv, tag);
+ }
}
-
Cipher::Cipher(const Cipher &from)
-:Algorithm(from), Filter(from)
+ : Algorithm(from), Filter(from)
{
- d = new Private(*from.d);
+ d = new Private(*from.d);
}
Cipher::~Cipher()
{
- delete d;
+ delete d;
}
-Cipher & Cipher::operator=(const Cipher &from)
+Cipher &Cipher::operator=(const Cipher &from)
{
- Algorithm::operator=(from);
- *d = *from.d;
- return *this;
+ Algorithm::operator=(from);
+ *d = *from.d;
+ return *this;
}
QStringList Cipher::supportedTypes(const QString &provider)
{
- return supportedCipherTypes(provider);
+ return supportedCipherTypes(provider);
}
QString Cipher::type() const
{
- return d->type;
+ return d->type;
}
Cipher::Mode Cipher::mode() const
{
- return d->mode;
+ return d->mode;
}
Cipher::Padding Cipher::padding() const
{
- return d->pad;
+ return d->pad;
}
Direction Cipher::direction() const
{
- return d->dir;
+ return d->dir;
}
KeyLength Cipher::keyLength() const
{
- return static_cast<const CipherContext *>(context())->keyLength();
+ return static_cast<const CipherContext *>(context())->keyLength();
}
bool Cipher::validKeyLength(int n) const
{
- KeyLength len = keyLength();
- return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0));
+ KeyLength len = keyLength();
+ return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0));
}
int Cipher::blockSize() const
{
- return static_cast<const CipherContext *>(context())->blockSize();
+ return static_cast<const CipherContext *>(context())->blockSize();
}
AuthTag Cipher::tag() const
{
- return static_cast<const CipherContext *>(context())->tag();
+ return static_cast<const CipherContext *>(context())->tag();
}
void Cipher::clear()
{
- d->done = false;
- static_cast<CipherContext *>(context())->setup(d->dir, d->key, d->iv, d->tag);
+ d->done = false;
+ static_cast<CipherContext *>(context())->setup(d->dir, d->key, d->iv, d->tag);
}
MemoryRegion Cipher::update(const MemoryRegion &a)
{
- SecureArray out;
- if(d->done)
- return out;
- d->ok = static_cast<CipherContext *>(context())->update(a, &out);
- return out;
+ SecureArray out;
+ if (d->done) {
+ return out;
+ }
+ d->ok = static_cast<CipherContext *>(context())->update(a, &out);
+ return out;
}
MemoryRegion Cipher::final()
{
- SecureArray out;
- if(d->done)
- return out;
- d->done = true;
- d->ok = static_cast<CipherContext *>(context())->final(&out);
- return out;
+ SecureArray out;
+ if (d->done) {
+ return out;
+ }
+ d->done = true;
+ d->ok = static_cast<CipherContext *>(context())->final(&out);
+ return out;
}
bool Cipher::ok() const
{
- return d->ok;
+ return d->ok;
}
void Cipher::setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv)
{
- setup(dir, key, iv, AuthTag());
+ setup(dir, key, iv, AuthTag());
}
void Cipher::setup(Direction dir, const SymmetricKey &key, const InitializationVector &iv, const AuthTag &tag)
{
- d->dir = dir;
- d->key = key;
- d->iv = iv;
- d->tag = tag;
- clear();
+ d->dir = dir;
+ d->key = key;
+ d->iv = iv;
+ d->tag = tag;
+ clear();
}
QString Cipher::withAlgorithms(const QString &cipherType, Mode modeType, Padding paddingType)
{
- QString mode;
- switch(modeType) {
- case CBC:
- mode = "cbc";
- break;
- case CFB:
- mode = "cfb";
- break;
- case OFB:
- mode = "ofb";
- break;
- case ECB:
- mode = "ecb";
- break;
- case CTR:
- mode = "ctr";
- break;
- case GCM:
- mode = "gcm";
- break;
- case CCM:
- mode = "ccm";
- break;
- default:
- Q_ASSERT(0);
- }
-
- // do the default
- if(paddingType == DefaultPadding)
- {
- // logic from Botan
- if(modeType == CBC)
- paddingType = PKCS7;
- else
- paddingType = NoPadding;
- }
-
- QString pad;
- if(paddingType == NoPadding)
- pad = "";
- else
- pad = "pkcs7";
-
- QString result = cipherType + '-' + mode;
- if(!pad.isEmpty())
- result += QString("-") + pad;
-
- return result;
+ QString mode;
+ switch (modeType) {
+ case CBC:
+ mode = "cbc";
+ break;
+ case CFB:
+ mode = "cfb";
+ break;
+ case OFB:
+ mode = "ofb";
+ break;
+ case ECB:
+ mode = "ecb";
+ break;
+ case CTR:
+ mode = "ctr";
+ break;
+ case GCM:
+ mode = "gcm";
+ break;
+ case CCM:
+ mode = "ccm";
+ break;
+ default:
+ Q_ASSERT(0);
+ }
+
+ // do the default
+ if (paddingType == DefaultPadding) {
+ // logic from Botan
+ if (modeType == CBC) {
+ paddingType = PKCS7;
+ } else {
+ paddingType = NoPadding;
+ }
+ }
+
+ QString pad;
+ if (paddingType == NoPadding) {
+ pad = "";
+ } else {
+ pad = "pkcs7";
+ }
+
+ QString result = cipherType + '-' + mode;
+ if (!pad.isEmpty()) {
+ result += QString("-") + pad;
+ }
+
+ return result;
}
//----------------------------------------------------------------------------
// MessageAuthenticationCode
//----------------------------------------------------------------------------
class MessageAuthenticationCode::Private
{
public:
- SymmetricKey key;
+ SymmetricKey key;
- bool done;
- MemoryRegion buf;
+ bool done;
+ MemoryRegion buf;
};
-
MessageAuthenticationCode::MessageAuthenticationCode(const QString &type,
- const SymmetricKey &key,
- const QString &provider)
-:Algorithm(type, provider)
+ const SymmetricKey &key,
+ const QString &provider)
+ : Algorithm(type, provider)
{
- d = new Private;
- setup(key);
+ d = new Private;
+ setup(key);
}
MessageAuthenticationCode::MessageAuthenticationCode(const MessageAuthenticationCode &from)
-:Algorithm(from), BufferedComputation(from)
+ : Algorithm(from), BufferedComputation(from)
{
- d = new Private(*from.d);
+ d = new Private(*from.d);
}
MessageAuthenticationCode::~MessageAuthenticationCode()
{
- delete d;
+ delete d;
}
-MessageAuthenticationCode & MessageAuthenticationCode::operator=(const MessageAuthenticationCode &from)
+MessageAuthenticationCode &MessageAuthenticationCode::operator=(const MessageAuthenticationCode &from)
{
- Algorithm::operator=(from);
- *d = *from.d;
- return *this;
+ Algorithm::operator=(from);
+ *d = *from.d;
+ return *this;
}
QStringList MessageAuthenticationCode::supportedTypes(const QString &provider)
{
- return supportedMACTypes(provider);
+ return supportedMACTypes(provider);
}
QString MessageAuthenticationCode::type() const
{
- // algorithm type is the same as the mac type
- return Algorithm::type();
+ // algorithm type is the same as the mac type
+ return Algorithm::type();
}
KeyLength MessageAuthenticationCode::keyLength() const
{
- return static_cast<const MACContext *>(context())->keyLength();
+ return static_cast<const MACContext *>(context())->keyLength();
}
bool MessageAuthenticationCode::validKeyLength(int n) const
{
- KeyLength len = keyLength();
- return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0));
+ KeyLength len = keyLength();
+ return ((n >= len.minimum()) && (n <= len.maximum()) && (n % len.multiple() == 0));
}
void MessageAuthenticationCode::clear()
{
- d->done = false;
- static_cast<MACContext *>(context())->setup(d->key);
+ d->done = false;
+ static_cast<MACContext *>(context())->setup(d->key);
}
void MessageAuthenticationCode::update(const MemoryRegion &a)
{
- if(d->done)
- return;
- static_cast<MACContext *>(context())->update(a);
+ if (d->done) {
+ return;
+ }
+ static_cast<MACContext *>(context())->update(a);
}
MemoryRegion MessageAuthenticationCode::final()
{
- if(!d->done)
- {
- d->done = true;
- static_cast<MACContext *>(context())->final(&d->buf);
- }
- return d->buf;
+ if (!d->done) {
+ d->done = true;
+ static_cast<MACContext *>(context())->final(&d->buf);
+ }
+ return d->buf;
}
void MessageAuthenticationCode::setup(const SymmetricKey &key)
{
- d->key = key;
- clear();
+ d->key = key;
+ clear();
}
//----------------------------------------------------------------------------
// Key Derivation Function
//----------------------------------------------------------------------------
KeyDerivationFunction::KeyDerivationFunction(const QString &type, const QString &provider)
-:Algorithm(type, provider)
+ : Algorithm(type, provider)
{
}
KeyDerivationFunction::KeyDerivationFunction(const KeyDerivationFunction &from)
-:Algorithm(from)
+ : Algorithm(from)
{
}
KeyDerivationFunction::~KeyDerivationFunction()
{
}
-KeyDerivationFunction & KeyDerivationFunction::operator=(const KeyDerivationFunction &from)
+KeyDerivationFunction &KeyDerivationFunction::operator=(const KeyDerivationFunction &from)
{
- Algorithm::operator=(from);
- return *this;
+ Algorithm::operator=(from);
+ return *this;
}
SymmetricKey KeyDerivationFunction::makeKey(const SecureArray &secret, const InitializationVector &salt, unsigned int keyLength, unsigned int iterationCount)
{
- return static_cast<KDFContext *>(context())->makeKey(secret, salt, keyLength, iterationCount);
+ return static_cast<KDFContext *>(context())->makeKey(secret, salt, keyLength, iterationCount);
}
SymmetricKey KeyDerivationFunction::makeKey(const SecureArray &secret,
- const InitializationVector &salt,
- unsigned int keyLength,
- int msecInterval,
- unsigned int *iterationCount)
+ const InitializationVector &salt,
+ unsigned int keyLength,
+ int msecInterval,
+ unsigned int *iterationCount)
{
- return static_cast<KDFContext *>(context())->makeKey(secret,
- salt,
- keyLength,
- msecInterval,
- iterationCount);
+ return static_cast<KDFContext *>(context())->makeKey(secret,
+ salt,
+ keyLength,
+ msecInterval,
+ iterationCount);
}
QString KeyDerivationFunction::withAlgorithm(const QString &kdfType, const QString &algType)
{
- return (kdfType + '(' + algType + ')');
+ return (kdfType + '(' + algType + ')');
}
//----------------------------------------------------------------------------
// HKDF
//----------------------------------------------------------------------------
HKDF::HKDF(const QString &algorithm, const QString &provider)
-: Algorithm(QStringLiteral("hkdf(") + algorithm + ')', provider)
+ : Algorithm(QStringLiteral("hkdf(") + algorithm + ')', provider)
{
}
HKDF::HKDF(const HKDF &from)
-: Algorithm(from)
+ : Algorithm(from)
{
}
HKDF::~HKDF()
{
}
-HKDF & HKDF::operator=(const HKDF &from)
+HKDF &HKDF::operator=(const HKDF &from)
{
- Algorithm::operator=(from);
- return *this;
+ Algorithm::operator=(from);
+ return *this;
}
SymmetricKey HKDF::makeKey(const SecureArray &secret, const InitializationVector &salt, const InitializationVector &info, unsigned int keyLength)
{
- return static_cast<HKDFContext *>(context())->makeKey(secret,
- salt,
- info,
- keyLength);
+ return static_cast<HKDFContext *>(context())->makeKey(secret,
+ salt,
+ info,
+ keyLength);
}
}
diff --git a/src/qca_cert.cpp b/src/qca_cert.cpp
index eb5393fd..c09f176d 100644
--- a/src/qca_cert.cpp
+++ b/src/qca_cert.cpp
@@ -1,2987 +1,2998 @@
/*
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_cert.h"
#include "qca_publickey.h"
#include "qcaprovider.h"
#include <QTextStream>
#include <QFile>
#include <QUrl>
#include <stdlib.h>
-namespace QCA {
+namespace QCA
+{
Provider::Context *getContext(const QString &type, const QString &provider);
Provider::Context *getContext(const QString &type, Provider *p);
// from qca_publickey.cpp
bool stringToFile(const QString &fileName, const QString &content);
bool stringFromFile(const QString &fileName, QString *s);
bool arrayToFile(const QString &fileName, const QByteArray &content);
bool arrayFromFile(const QString &fileName, QByteArray *a);
bool ask_passphrase(const QString &fname, void *ptr, SecureArray *answer);
ProviderList allProviders();
Provider *providerForName(const QString &name);
bool use_asker_fallback(ConvertResult r);
// last 3 arguments must be valid, and chain must be empty
static bool get_pkcs12_der(const QByteArray &der, const QString &fileName, void *ptr, const SecureArray &passphrase, ConvertResult *result, const QString &provider, QString *name, CertificateChain *chain, PrivateKey *key)
{
- QString _name;
- QList<CertContext*> list;
- PKeyContext *kc = 0;
-
- PKCS12Context *pix = static_cast<PKCS12Context *>(getContext("pkcs12", provider));
- ConvertResult r = pix->fromPKCS12(der, passphrase, &_name, &list, &kc);
-
- // error converting without passphrase? maybe a passphrase is needed
- if(use_asker_fallback(r) && passphrase.isEmpty())
- {
- SecureArray pass;
- if(ask_passphrase(fileName, ptr, &pass))
- r = pix->fromPKCS12(der, pass, &_name, &list, &kc);
- }
- delete pix;
-
- if(result)
- *result = r;
-
- if(r == ConvertGood)
- {
- *name = _name;
- for(int n = 0; n < list.count(); ++n)
- {
- Certificate cert;
- cert.change(list[n]);
- chain->append(cert);
- }
- key->change(kc);
- return true;
- }
- return false;
+ QString _name;
+ QList<CertContext *> list;
+ PKeyContext *kc = 0;
+
+ PKCS12Context *pix = static_cast<PKCS12Context *>(getContext("pkcs12", provider));
+ ConvertResult r = pix->fromPKCS12(der, passphrase, &_name, &list, &kc);
+
+ // error converting without passphrase? maybe a passphrase is needed
+ if (use_asker_fallback(r) && passphrase.isEmpty()) {
+ SecureArray pass;
+ if (ask_passphrase(fileName, ptr, &pass)) {
+ r = pix->fromPKCS12(der, pass, &_name, &list, &kc);
+ }
+ }
+ delete pix;
+
+ if (result) {
+ *result = r;
+ }
+
+ if (r == ConvertGood) {
+ *name = _name;
+ for (int n = 0; n < list.count(); ++n) {
+ Certificate cert;
+ cert.change(list[n]);
+ chain->append(cert);
+ }
+ key->change(kc);
+ return true;
+ }
+ return false;
}
static CertificateInfo orderedToMap(const CertificateInfoOrdered &info)
{
- CertificateInfo out;
+ CertificateInfo out;
- // first, do all but EmailLegacy
- for(int n = 0; n < info.count(); ++n)
- {
- const CertificateInfoPair &i = info[n];
- if(i.type().known() != EmailLegacy)
- out.insert(i.type(), i.value());
- }
+ // first, do all but EmailLegacy
+ for (int n = 0; n < info.count(); ++n) {
+ const CertificateInfoPair &i = info[n];
+ if (i.type().known() != EmailLegacy) {
+ out.insert(i.type(), i.value());
+ }
+ }
- // lastly, apply EmailLegacy
- for(int n = 0; n < info.count(); ++n)
- {
- const CertificateInfoPair &i = info[n];
- if(i.type().known() == EmailLegacy)
- {
- // de-dup
- QList<QString> emails = out.values(Email);
- if(!emails.contains(i.value()))
- out.insert(Email, i.value());
- }
- }
+ // lastly, apply EmailLegacy
+ for (int n = 0; n < info.count(); ++n) {
+ const CertificateInfoPair &i = info[n];
+ if (i.type().known() == EmailLegacy) {
+ // de-dup
+ QList<QString> emails = out.values(Email);
+ if (!emails.contains(i.value())) {
+ out.insert(Email, i.value());
+ }
+ }
+ }
- return out;
+ return out;
}
static void moveMapValues(CertificateInfo *from, CertificateInfoOrdered *to, const CertificateInfoType &type)
{
- QList<QString> values = from->values(type);
- from->remove(type);
+ QList<QString> values = from->values(type);
+ from->remove(type);
- // multimap values are stored in reverse. we'll insert backwards in
- // order to right them.
- for(int n = values.count() - 1; n >= 0; --n)
- to->append(CertificateInfoPair(type, values[n]));
+ // multimap values are stored in reverse. we'll insert backwards in
+ // order to right them.
+ for (int n = values.count() - 1; n >= 0; --n) {
+ to->append(CertificateInfoPair(type, values[n]));
+ }
}
static CertificateInfoOrdered mapToOrdered(const CertificateInfo &info)
{
- CertificateInfo in = info;
- CertificateInfoOrdered out;
+ CertificateInfo in = info;
+ CertificateInfoOrdered out;
- // have a specific order for some types
- moveMapValues(&in, &out, CommonName);
- moveMapValues(&in, &out, Country);
- moveMapValues(&in, &out, Locality);
- moveMapValues(&in, &out, State);
- moveMapValues(&in, &out, Organization);
- moveMapValues(&in, &out, OrganizationalUnit);
- moveMapValues(&in, &out, Email);
- moveMapValues(&in, &out, URI);
- moveMapValues(&in, &out, DNS);
- moveMapValues(&in, &out, IPAddress);
- moveMapValues(&in, &out, XMPP);
+ // have a specific order for some types
+ moveMapValues(&in, &out, CommonName);
+ moveMapValues(&in, &out, Country);
+ moveMapValues(&in, &out, Locality);
+ moveMapValues(&in, &out, State);
+ moveMapValues(&in, &out, Organization);
+ moveMapValues(&in, &out, OrganizationalUnit);
+ moveMapValues(&in, &out, Email);
+ moveMapValues(&in, &out, URI);
+ moveMapValues(&in, &out, DNS);
+ moveMapValues(&in, &out, IPAddress);
+ moveMapValues(&in, &out, XMPP);
- // get remaining types
- QList<CertificateInfoType> typesLeft = in.keys();
+ // get remaining types
+ QList<CertificateInfoType> typesLeft = in.keys();
- // dedup
- QList<CertificateInfoType> types;
- for(int n = 0; n < typesLeft.count(); ++n)
- {
- if(!types.contains(typesLeft[n]))
- types += typesLeft[n];
- }
+ // dedup
+ QList<CertificateInfoType> types;
+ for (int n = 0; n < typesLeft.count(); ++n) {
+ if (!types.contains(typesLeft[n])) {
+ types += typesLeft[n];
+ }
+ }
- // insert the rest of the types in the order we got them (map order)
- for(int n = 0; n < types.count(); ++n)
- moveMapValues(&in, &out, types[n]);
+ // insert the rest of the types in the order we got them (map order)
+ for (int n = 0; n < types.count(); ++n) {
+ moveMapValues(&in, &out, types[n]);
+ }
- Q_ASSERT(in.isEmpty());
+ Q_ASSERT(in.isEmpty());
- return out;
+ return out;
}
//----------------------------------------------------------------------------
// Global
//----------------------------------------------------------------------------
static const char CommonName_id[] = "2.5.4.3";
static const char Email_id[] = "GeneralName.rfc822Name";
static const char EmailLegacy_id[] = "1.2.840.113549.1.9.1";
static const char Organization_id[] = "2.5.4.10";
static const char OrganizationalUnit_id[] = "2.5.4.11";
static const char Locality_id[] = "2.5.4.7";
static const char IncorporationLocality_id[] = "1.3.6.1.4.1.311.60.2.1.1";
static const char State_id[] = "2.5.4.8";
static const char IncorporationState_id[] = "1.3.6.1.4.1.311.60.2.1.2";
static const char Country_id[] = "2.5.4.6";
static const char IncorporationCountry_id[] = "1.3.6.1.4.1.311.60.2.1.3";
static const char URI_id[] = "GeneralName.uniformResourceIdentifier";
static const char DNS_id[] = "GeneralName.dNSName";
static const char IPAddress_id[] = "GeneralName.iPAddress";
static const char XMPP_id[] = "1.3.6.1.5.5.7.8.5";
static const char DigitalSignature_id[] = "KeyUsage.digitalSignature";
static const char NonRepudiation_id[] = "KeyUsage.nonRepudiation";
static const char KeyEncipherment_id[] = "KeyUsage.keyEncipherment";
static const char DataEncipherment_id[] = "KeyUsage.dataEncipherment";
static const char KeyAgreement_id[] = "KeyUsage.keyAgreement";
static const char KeyCertificateSign_id[] = "KeyUsage.keyCertSign";
static const char CRLSign_id[] = "KeyUsage.crlSign";
static const char EncipherOnly_id[] = "KeyUsage.encipherOnly";
static const char DecipherOnly_id[] = "KeyUsage.decipherOnly";
static const char ServerAuth_id[] = "1.3.6.1.5.5.7.3.1";
static const char ClientAuth_id[] = "1.3.6.1.5.5.7.3.2";
static const char CodeSigning_id[] = "1.3.6.1.5.5.7.3.3";
static const char EmailProtection_id[] = "1.3.6.1.5.5.7.3.4";
static const char IPSecEndSystem_id[] = "1.3.6.1.5.5.7.3.5";
static const char IPSecTunnel_id[] = "1.3.6.1.5.5.7.3.6";
static const char IPSecUser_id[] = "1.3.6.1.5.5.7.3.7";
static const char TimeStamping_id[] = "1.3.6.1.5.5.7.3.8";
static const char OCSPSigning_id[] = "1.3.6.1.5.5.7.3.9";
static QString knownToId(CertificateInfoTypeKnown k)
{
- const char *out = 0;
- switch(k)
- {
- case CommonName: out = CommonName_id; break;
- case Email: out = Email_id; break;
- case EmailLegacy: out = EmailLegacy_id; break;
- case Organization: out = Organization_id; break;
- case OrganizationalUnit: out = OrganizationalUnit_id; break;
- case Locality: out = Locality_id; break;
- case IncorporationLocality: out = IncorporationLocality_id; break;
- case State: out = State_id; break;
- case IncorporationState: out = IncorporationState_id; break;
- case Country: out = Country_id; break;
- case IncorporationCountry: out = IncorporationCountry_id; break;
- case URI: out = URI_id; break;
- case DNS: out = DNS_id; break;
- case IPAddress: out = IPAddress_id; break;
- case XMPP: out = XMPP_id; break;
- }
- Q_ASSERT(out);
- if(!out)
- abort();
- return QString(out);
+ const char *out = 0;
+ switch (k) {
+ case CommonName: out = CommonName_id; break;
+ case Email: out = Email_id; break;
+ case EmailLegacy: out = EmailLegacy_id; break;
+ case Organization: out = Organization_id; break;
+ case OrganizationalUnit: out = OrganizationalUnit_id; break;
+ case Locality: out = Locality_id; break;
+ case IncorporationLocality: out = IncorporationLocality_id; break;
+ case State: out = State_id; break;
+ case IncorporationState: out = IncorporationState_id; break;
+ case Country: out = Country_id; break;
+ case IncorporationCountry: out = IncorporationCountry_id; break;
+ case URI: out = URI_id; break;
+ case DNS: out = DNS_id; break;
+ case IPAddress: out = IPAddress_id; break;
+ case XMPP: out = XMPP_id; break;
+ }
+ Q_ASSERT(out);
+ if (!out) {
+ abort();
+ }
+ return QString(out);
}
static int idToKnown(const QString &id)
{
- if(id == CommonName_id)
- return CommonName;
- else if(id == Email_id)
- return Email;
- else if(id == EmailLegacy_id)
- return EmailLegacy;
- else if(id == Organization_id)
- return Organization;
- else if(id == OrganizationalUnit_id)
- return OrganizationalUnit;
- else if(id == Locality_id)
- return Locality;
- else if(id == IncorporationLocality_id)
- return IncorporationLocality;
- else if(id == State_id)
- return State;
- else if(id == IncorporationState_id)
- return IncorporationState;
- else if(id == Country_id)
- return Country;
- else if(id == IncorporationCountry_id)
- return IncorporationCountry;
- else if(id == URI_id)
- return URI;
- else if(id == DNS_id)
- return DNS;
- else if(id == IPAddress_id)
- return IPAddress;
- else if(id == XMPP_id)
- return XMPP;
- else
- return -1;
+ if (id == CommonName_id) {
+ return CommonName;
+ } else if (id == Email_id) {
+ return Email;
+ } else if (id == EmailLegacy_id) {
+ return EmailLegacy;
+ } else if (id == Organization_id) {
+ return Organization;
+ } else if (id == OrganizationalUnit_id) {
+ return OrganizationalUnit;
+ } else if (id == Locality_id) {
+ return Locality;
+ } else if (id == IncorporationLocality_id) {
+ return IncorporationLocality;
+ } else if (id == State_id) {
+ return State;
+ } else if (id == IncorporationState_id) {
+ return IncorporationState;
+ } else if (id == Country_id) {
+ return Country;
+ } else if (id == IncorporationCountry_id) {
+ return IncorporationCountry;
+ } else if (id == URI_id) {
+ return URI;
+ } else if (id == DNS_id) {
+ return DNS;
+ } else if (id == IPAddress_id) {
+ return IPAddress;
+ } else if (id == XMPP_id) {
+ return XMPP;
+ } else {
+ return -1;
+ }
}
static CertificateInfoType::Section knownToSection(CertificateInfoTypeKnown k)
{
- switch(k)
- {
- case CommonName:
- case EmailLegacy:
- case Organization:
- case OrganizationalUnit:
- case Locality:
- case IncorporationLocality:
- case State:
- case IncorporationState:
- case Country:
- case IncorporationCountry:
- return CertificateInfoType::DN;
- default:
- break;
- }
- return CertificateInfoType::AlternativeName;
+ switch (k) {
+ case CommonName:
+ case EmailLegacy:
+ case Organization:
+ case OrganizationalUnit:
+ case Locality:
+ case IncorporationLocality:
+ case State:
+ case IncorporationState:
+ case Country:
+ case IncorporationCountry:
+ return CertificateInfoType::DN;
+ default:
+ break;
+ }
+ return CertificateInfoType::AlternativeName;
}
static const char *knownToShortName(CertificateInfoTypeKnown k)
{
- switch(k)
- {
- case CommonName: return "CN";
- case Locality: return "L";
- case State: return "ST";
- case Organization: return "O";
- case OrganizationalUnit: return "OU";
- case Country: return "C";
- case EmailLegacy: return "emailAddress";
- default: break;
- }
- return 0;
+ switch (k) {
+ case CommonName: return "CN";
+ case Locality: return "L";
+ case State: return "ST";
+ case Organization: return "O";
+ case OrganizationalUnit: return "OU";
+ case Country: return "C";
+ case EmailLegacy: return "emailAddress";
+ default: break;
+ }
+ return 0;
}
static QString constraintKnownToId(ConstraintTypeKnown k)
{
- const char *out = 0;
- switch(k)
- {
- case DigitalSignature: out = DigitalSignature_id; break;
- case NonRepudiation: out = NonRepudiation_id; break;
- case KeyEncipherment: out = KeyEncipherment_id; break;
- case DataEncipherment: out = DataEncipherment_id; break;
- case KeyAgreement: out = KeyAgreement_id; break;
- case KeyCertificateSign: out = KeyCertificateSign_id; break;
- case CRLSign: out = CRLSign_id; break;
- case EncipherOnly: out = EncipherOnly_id; break;
- case DecipherOnly: out = DecipherOnly_id; break;
- case ServerAuth: out = ServerAuth_id; break;
- case ClientAuth: out = ClientAuth_id; break;
- case CodeSigning: out = CodeSigning_id; break;
- case EmailProtection: out = EmailProtection_id; break;
- case IPSecEndSystem: out = IPSecEndSystem_id; break;
- case IPSecTunnel: out = IPSecTunnel_id; break;
- case IPSecUser: out = IPSecUser_id; break;
- case TimeStamping: out = TimeStamping_id; break;
- case OCSPSigning: out = OCSPSigning_id; break;
- }
- Q_ASSERT(out);
- if(!out)
- abort();
- return QString(out);
+ const char *out = 0;
+ switch (k) {
+ case DigitalSignature: out = DigitalSignature_id; break;
+ case NonRepudiation: out = NonRepudiation_id; break;
+ case KeyEncipherment: out = KeyEncipherment_id; break;
+ case DataEncipherment: out = DataEncipherment_id; break;
+ case KeyAgreement: out = KeyAgreement_id; break;
+ case KeyCertificateSign: out = KeyCertificateSign_id; break;
+ case CRLSign: out = CRLSign_id; break;
+ case EncipherOnly: out = EncipherOnly_id; break;
+ case DecipherOnly: out = DecipherOnly_id; break;
+ case ServerAuth: out = ServerAuth_id; break;
+ case ClientAuth: out = ClientAuth_id; break;
+ case CodeSigning: out = CodeSigning_id; break;
+ case EmailProtection: out = EmailProtection_id; break;
+ case IPSecEndSystem: out = IPSecEndSystem_id; break;
+ case IPSecTunnel: out = IPSecTunnel_id; break;
+ case IPSecUser: out = IPSecUser_id; break;
+ case TimeStamping: out = TimeStamping_id; break;
+ case OCSPSigning: out = OCSPSigning_id; break;
+ }
+ Q_ASSERT(out);
+ if (!out) {
+ abort();
+ }
+ return QString(out);
}
static int constraintIdToKnown(const QString &id)
{
- if(id == DigitalSignature_id)
- return DigitalSignature;
- else if(id == NonRepudiation_id)
- return NonRepudiation;
- else if(id == KeyEncipherment_id)
- return KeyEncipherment;
- else if(id == DataEncipherment_id)
- return DataEncipherment;
- else if(id == KeyAgreement_id)
- return KeyAgreement;
- else if(id == KeyCertificateSign_id)
- return KeyCertificateSign;
- else if(id == CRLSign_id)
- return CRLSign;
- else if(id == EncipherOnly_id)
- return EncipherOnly;
- else if(id == DecipherOnly_id)
- return DecipherOnly;
- else if(id == ServerAuth_id)
- return ServerAuth;
- else if(id == ClientAuth_id)
- return ClientAuth;
- else if(id == CodeSigning_id)
- return CodeSigning;
- else if(id == EmailProtection_id)
- return EmailProtection;
- else if(id == IPSecEndSystem_id)
- return IPSecEndSystem;
- else if(id == IPSecTunnel_id)
- return IPSecTunnel;
- else if(id == IPSecUser_id)
- return IPSecUser;
- else if(id == TimeStamping_id)
- return TimeStamping;
- else if(id == OCSPSigning_id)
- return OCSPSigning;
- else
- return -1;
+ if (id == DigitalSignature_id) {
+ return DigitalSignature;
+ } else if (id == NonRepudiation_id) {
+ return NonRepudiation;
+ } else if (id == KeyEncipherment_id) {
+ return KeyEncipherment;
+ } else if (id == DataEncipherment_id) {
+ return DataEncipherment;
+ } else if (id == KeyAgreement_id) {
+ return KeyAgreement;
+ } else if (id == KeyCertificateSign_id) {
+ return KeyCertificateSign;
+ } else if (id == CRLSign_id) {
+ return CRLSign;
+ } else if (id == EncipherOnly_id) {
+ return EncipherOnly;
+ } else if (id == DecipherOnly_id) {
+ return DecipherOnly;
+ } else if (id == ServerAuth_id) {
+ return ServerAuth;
+ } else if (id == ClientAuth_id) {
+ return ClientAuth;
+ } else if (id == CodeSigning_id) {
+ return CodeSigning;
+ } else if (id == EmailProtection_id) {
+ return EmailProtection;
+ } else if (id == IPSecEndSystem_id) {
+ return IPSecEndSystem;
+ } else if (id == IPSecTunnel_id) {
+ return IPSecTunnel;
+ } else if (id == IPSecUser_id) {
+ return IPSecUser;
+ } else if (id == TimeStamping_id) {
+ return TimeStamping;
+ } else if (id == OCSPSigning_id) {
+ return OCSPSigning;
+ } else {
+ return -1;
+ }
}
static ConstraintType::Section constraintKnownToSection(ConstraintTypeKnown k)
{
- switch(k)
- {
- case DigitalSignature:
- case NonRepudiation:
- case KeyEncipherment:
- case DataEncipherment:
- case KeyAgreement:
- case KeyCertificateSign:
- case CRLSign:
- case EncipherOnly:
- case DecipherOnly:
- return ConstraintType::KeyUsage;
- default:
- break;
- }
- return ConstraintType::ExtendedKeyUsage;
+ switch (k) {
+ case DigitalSignature:
+ case NonRepudiation:
+ case KeyEncipherment:
+ case DataEncipherment:
+ case KeyAgreement:
+ case KeyCertificateSign:
+ case CRLSign:
+ case EncipherOnly:
+ case DecipherOnly:
+ return ConstraintType::KeyUsage;
+ default:
+ break;
+ }
+ return ConstraintType::ExtendedKeyUsage;
}
static QString dnLabel(const CertificateInfoType &type)
{
- const char *str = knownToShortName(type.known());
- if(str)
- return str;
+ const char *str = knownToShortName(type.known());
+ if (str) {
+ return str;
+ }
- QString id = type.id();
- // is it an oid?
- if(id[0].isDigit())
- return QString("OID.") + id;
+ QString id = type.id();
+ // is it an oid?
+ if (id[0].isDigit()) {
+ return QString("OID.") + id;
+ }
- return QString("qca.") + id;
+ return QString("qca.") + id;
}
QString orderedToDNString(const CertificateInfoOrdered &in)
{
- QStringList parts;
- foreach(const CertificateInfoPair &i, in)
- {
- if(i.type().section() != CertificateInfoType::DN)
- continue;
+ QStringList parts;
+ foreach (const CertificateInfoPair &i, in) {
+ if (i.type().section() != CertificateInfoType::DN) {
+ continue;
+ }
- QString name = dnLabel(i.type());
- parts += name + '=' + i.value();
- }
- return parts.join(", ");
+ QString name = dnLabel(i.type());
+ parts += name + '=' + i.value();
+ }
+ return parts.join(", ");
}
CertificateInfoOrdered orderedDNOnly(const CertificateInfoOrdered &in)
{
- CertificateInfoOrdered out;
- for(int n = 0; n < in.count(); ++n)
- {
- if(in[n].type().section() == CertificateInfoType::DN)
- out += in[n];
- }
- return out;
+ CertificateInfoOrdered out;
+ for (int n = 0; n < in.count(); ++n) {
+ if (in[n].type().section() == CertificateInfoType::DN) {
+ out += in[n];
+ }
+ }
+ return out;
}
static QString baseCertName(const CertificateInfo &info)
{
- QString str = info.value(CommonName);
- if(str.isEmpty())
- {
- str = info.value(Organization);
- if(str.isEmpty())
- str = "Unnamed";
- }
- return str;
+ QString str = info.value(CommonName);
+ if (str.isEmpty()) {
+ str = info.value(Organization);
+ if (str.isEmpty()) {
+ str = "Unnamed";
+ }
+ }
+ return str;
}
static QList<int> findSameName(const QString &name, const QStringList &list)
{
- QList<int> out;
- for(int n = 0; n < list.count(); ++n)
- {
- if(list[n] == name)
- out += n;
- }
- return out;
+ QList<int> out;
+ for (int n = 0; n < list.count(); ++n) {
+ if (list[n] == name) {
+ out += n;
+ }
+ }
+ return out;
}
static QString uniqueSubjectValue(const CertificateInfoType &type, const QList<int> items, const QList<Certificate> &certs, int i)
{
- QStringList vals = certs[items[i]].subjectInfo().values(type);
- if(!vals.isEmpty())
- {
- foreach(int n, items)
- {
- if(n == items[i])
- continue;
+ QStringList vals = certs[items[i]].subjectInfo().values(type);
+ if (!vals.isEmpty()) {
+ foreach (int n, items) {
+ if (n == items[i]) {
+ continue;
+ }
- QStringList other_vals = certs[n].subjectInfo().values(type);
- for(int k = 0; k < vals.count(); ++k)
- {
- if(other_vals.contains(vals[k]))
- {
- vals.removeAt(k);
- break;
- }
- }
+ QStringList other_vals = certs[n].subjectInfo().values(type);
+ for (int k = 0; k < vals.count(); ++k) {
+ if (other_vals.contains(vals[k])) {
+ vals.removeAt(k);
+ break;
+ }
+ }
- if(vals.isEmpty())
- break;
- }
+ if (vals.isEmpty()) {
+ break;
+ }
+ }
- if(!vals.isEmpty())
- return vals[0];
- }
+ if (!vals.isEmpty()) {
+ return vals[0];
+ }
+ }
- return QString();
+ return QString();
}
static QString uniqueIssuerName(const QList<int> items, const QList<Certificate> &certs, int i)
{
- QString val = baseCertName(certs[items[i]].issuerInfo());
+ QString val = baseCertName(certs[items[i]].issuerInfo());
- bool found = false;
- foreach(int n, items)
- {
- if(n == items[i])
- continue;
+ bool found = false;
+ foreach (int n, items) {
+ if (n == items[i]) {
+ continue;
+ }
- QString other_val = baseCertName(certs[n].issuerInfo());
- if(other_val == val)
- {
- found = true;
- break;
- }
- }
+ QString other_val = baseCertName(certs[n].issuerInfo());
+ if (other_val == val) {
+ found = true;
+ break;
+ }
+ }
- if(!found)
- return val;
+ if (!found) {
+ return val;
+ }
- return QString();
+ return QString();
}
static const char *constraintToString(const ConstraintType &type)
{
- switch(type.known())
- {
- case DigitalSignature: return "DigitalSignature";
- case NonRepudiation: return "NonRepudiation";
- case KeyEncipherment: return "KeyEncipherment";
- case DataEncipherment: return "DataEncipherment";
- case KeyAgreement: return "KeyAgreement";
- case KeyCertificateSign: return "KeyCertificateSign";
- case CRLSign: return "CRLSign";
- case EncipherOnly: return "EncipherOnly";
- case DecipherOnly: return "DecipherOnly";
- case ServerAuth: return "ServerAuth";
- case ClientAuth: return "ClientAuth";
- case CodeSigning: return "CodeSigning";
- case EmailProtection: return "EmailProtection";
- case IPSecEndSystem: return "IPSecEndSystem";
- case IPSecTunnel: return "IPSecTunnel";
- case IPSecUser: return "IPSecUser";
- case TimeStamping: return "TimeStamping";
- case OCSPSigning: return "OCSPSigning";
- }
- return 0;
+ switch (type.known()) {
+ case DigitalSignature: return "DigitalSignature";
+ case NonRepudiation: return "NonRepudiation";
+ case KeyEncipherment: return "KeyEncipherment";
+ case DataEncipherment: return "DataEncipherment";
+ case KeyAgreement: return "KeyAgreement";
+ case KeyCertificateSign: return "KeyCertificateSign";
+ case CRLSign: return "CRLSign";
+ case EncipherOnly: return "EncipherOnly";
+ case DecipherOnly: return "DecipherOnly";
+ case ServerAuth: return "ServerAuth";
+ case ClientAuth: return "ClientAuth";
+ case CodeSigning: return "CodeSigning";
+ case EmailProtection: return "EmailProtection";
+ case IPSecEndSystem: return "IPSecEndSystem";
+ case IPSecTunnel: return "IPSecTunnel";
+ case IPSecUser: return "IPSecUser";
+ case TimeStamping: return "TimeStamping";
+ case OCSPSigning: return "OCSPSigning";
+ }
+ return 0;
}
static QString uniqueConstraintValue(const ConstraintType &type, const QList<int> items, const QList<Certificate> &certs, int i)
{
- ConstraintType val = type;
- if(certs[items[i]].constraints().contains(type))
- {
- bool found = false;
- foreach(int n, items)
- {
- if(n == items[i])
- continue;
+ ConstraintType val = type;
+ if (certs[items[i]].constraints().contains(type)) {
+ bool found = false;
+ foreach (int n, items) {
+ if (n == items[i]) {
+ continue;
+ }
- Constraints other_vals = certs[n].constraints();
- if(other_vals.contains(val))
- {
- found = true;
- break;
- }
- }
+ Constraints other_vals = certs[n].constraints();
+ if (other_vals.contains(val)) {
+ found = true;
+ break;
+ }
+ }
- if(!found)
- return QString(constraintToString(val));
- }
+ if (!found) {
+ return QString(constraintToString(val));
+ }
+ }
- return QString();
+ return QString();
}
static QString makeUniqueName(const QList<int> &items, const QStringList &list, const QList<Certificate> &certs, int i)
{
- QString str, name;
-
- // different organization?
- str = uniqueSubjectValue(Organization, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" of ") + str;
- goto end;
- }
-
- // different organizational unit?
- str = uniqueSubjectValue(OrganizationalUnit, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" of ") + str;
- goto end;
- }
-
- // different email address?
- str = uniqueSubjectValue(Email, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" <") + str + '>';
- goto end;
- }
-
- // different xmpp addresses?
- str = uniqueSubjectValue(XMPP, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" <xmpp:") + str + '>';
- goto end;
- }
-
- // different issuers?
- str = uniqueIssuerName(items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" by ") + str;
- goto end;
- }
-
- // different usages?
-
- // DigitalSignature
- str = uniqueConstraintValue(DigitalSignature, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" for ") + str;
- goto end;
- }
-
- // ClientAuth
- str = uniqueConstraintValue(ClientAuth, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" for ") + str;
- goto end;
- }
-
- // EmailProtection
- str = uniqueConstraintValue(EmailProtection, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" for ") + str;
- goto end;
- }
-
- // DataEncipherment
- str = uniqueConstraintValue(DataEncipherment, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" for ") + str;
- goto end;
- }
-
- // EncipherOnly
- str = uniqueConstraintValue(EncipherOnly, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" for ") + str;
- goto end;
- }
-
- // DecipherOnly
- str = uniqueConstraintValue(DecipherOnly, items, certs, i);
- if(!str.isEmpty())
- {
- name = list[items[i]] + QString(" for ") + str;
- goto end;
- }
-
- // if there's nothing easily unique, then do a DN string
- name = certs[items[i]].subjectInfoOrdered().toString();
+ QString str, name;
+
+ // different organization?
+ str = uniqueSubjectValue(Organization, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" of ") + str;
+ goto end;
+ }
+
+ // different organizational unit?
+ str = uniqueSubjectValue(OrganizationalUnit, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" of ") + str;
+ goto end;
+ }
+
+ // different email address?
+ str = uniqueSubjectValue(Email, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" <") + str + '>';
+ goto end;
+ }
+
+ // different xmpp addresses?
+ str = uniqueSubjectValue(XMPP, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" <xmpp:") + str + '>';
+ goto end;
+ }
+
+ // different issuers?
+ str = uniqueIssuerName(items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" by ") + str;
+ goto end;
+ }
+
+ // different usages?
+
+ // DigitalSignature
+ str = uniqueConstraintValue(DigitalSignature, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" for ") + str;
+ goto end;
+ }
+
+ // ClientAuth
+ str = uniqueConstraintValue(ClientAuth, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" for ") + str;
+ goto end;
+ }
+
+ // EmailProtection
+ str = uniqueConstraintValue(EmailProtection, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" for ") + str;
+ goto end;
+ }
+
+ // DataEncipherment
+ str = uniqueConstraintValue(DataEncipherment, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" for ") + str;
+ goto end;
+ }
+
+ // EncipherOnly
+ str = uniqueConstraintValue(EncipherOnly, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" for ") + str;
+ goto end;
+ }
+
+ // DecipherOnly
+ str = uniqueConstraintValue(DecipherOnly, items, certs, i);
+ if (!str.isEmpty()) {
+ name = list[items[i]] + QString(" for ") + str;
+ goto end;
+ }
+
+ // if there's nothing easily unique, then do a DN string
+ name = certs[items[i]].subjectInfoOrdered().toString();
end:
- return name;
+ return name;
}
QStringList makeFriendlyNames(const QList<Certificate> &list)
{
- QStringList names;
-
- // give a base name to all certs first
- foreach(const Certificate &cert, list)
- names += baseCertName(cert.subjectInfo());
-
- // come up with a collision list
- QList< QList<int> > itemCollisions;
- foreach(const QString &name, names)
- {
- // anyone else using this name?
- QList<int> items = findSameName(name, names);
- if(items.count() > 1)
- {
- // don't save duplicate collisions
- bool haveAlready = false;
- foreach(const QList<int> &other, itemCollisions)
- {
- foreach(int n, items)
- {
- if(other.contains(n))
- {
- haveAlready = true;
- break;
- }
- }
-
- if(haveAlready)
- break;
- }
-
- if(haveAlready)
- continue;
-
- itemCollisions += items;
- }
- }
-
- // resolve collisions by providing extra details
- foreach(const QList<int> &items, itemCollisions)
- {
- //printf("%d items are using [%s]\n", items.count(), qPrintable(names[items[0]]));
-
- for(int n = 0; n < items.count(); ++n)
- {
- names[items[n]] = makeUniqueName(items, names, list, n);
- //printf(" %d: reassigning: [%s]\n", items[n], qPrintable(names[items[n]]));
- }
- }
-
- return names;
+ QStringList names;
+
+ // give a base name to all certs first
+ foreach (const Certificate &cert, list) {
+ names += baseCertName(cert.subjectInfo());
+ }
+
+ // come up with a collision list
+ QList< QList<int> > itemCollisions;
+ foreach (const QString &name, names) {
+ // anyone else using this name?
+ QList<int> items = findSameName(name, names);
+ if (items.count() > 1) {
+ // don't save duplicate collisions
+ bool haveAlready = false;
+ foreach (const QList<int> &other, itemCollisions) {
+ foreach (int n, items) {
+ if (other.contains(n)) {
+ haveAlready = true;
+ break;
+ }
+ }
+
+ if (haveAlready) {
+ break;
+ }
+ }
+
+ if (haveAlready) {
+ continue;
+ }
+
+ itemCollisions += items;
+ }
+ }
+
+ // resolve collisions by providing extra details
+ foreach (const QList<int> &items, itemCollisions) {
+ //printf("%d items are using [%s]\n", items.count(), qPrintable(names[items[0]]));
+
+ for (int n = 0; n < items.count(); ++n) {
+ names[items[n]] = makeUniqueName(items, names, list, n);
+ //printf(" %d: reassigning: [%s]\n", items[n], qPrintable(names[items[n]]));
+ }
+ }
+
+ return names;
}
//----------------------------------------------------------------------------
// CertificateInfoType
//----------------------------------------------------------------------------
class CertificateInfoType::Private : public QSharedData
{
public:
- CertificateInfoType::Section section;
- int known;
- QString id;
-
- Private() :
- section(CertificateInfoType::DN),
- known(-1)
- {
- }
+ CertificateInfoType::Section section;
+ int known;
+ QString id;
+
+ Private() :
+ section(CertificateInfoType::DN),
+ known(-1)
+ {
+ }
};
CertificateInfoType::CertificateInfoType()
-:d(new Private)
+ : d(new Private)
{
}
CertificateInfoType::CertificateInfoType(CertificateInfoTypeKnown known)
-:d(new Private)
+ : d(new Private)
{
- d->section = knownToSection(known);
- d->known = known;
- d->id = knownToId(known); // always valid
+ d->section = knownToSection(known);
+ d->known = known;
+ d->id = knownToId(known); // always valid
}
CertificateInfoType::CertificateInfoType(const QString &id, Section section)
-:d(new Private)
+ : d(new Private)
{
- d->section = section;
- d->known = idToKnown(id); // can be -1 for unknown
- d->id = id;
+ d->section = section;
+ d->known = idToKnown(id); // can be -1 for unknown
+ d->id = id;
}
CertificateInfoType::CertificateInfoType(const CertificateInfoType &from)
-:d(from.d)
+ : d(from.d)
{
}
CertificateInfoType::~CertificateInfoType()
{
}
-CertificateInfoType & CertificateInfoType::operator=(const CertificateInfoType &from)
+CertificateInfoType &CertificateInfoType::operator=(const CertificateInfoType &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
CertificateInfoType::Section CertificateInfoType::section() const
{
- return d->section;
+ return d->section;
}
CertificateInfoTypeKnown CertificateInfoType::known() const
{
- return (CertificateInfoTypeKnown)d->known;
+ return (CertificateInfoTypeKnown)d->known;
}
QString CertificateInfoType::id() const
{
- return d->id;
+ return d->id;
}
bool CertificateInfoType::operator<(const CertificateInfoType &other) const
{
- // sort by knowns (in enum order), then by ids (in string order)
- if(d->known != -1)
- {
- if(other.d->known == -1)
- return true;
- else if(d->known < other.d->known)
- return true;
- else
- return false;
- }
- else
- {
- if(other.d->known != -1)
- return false;
- else if(d->id < other.d->id)
- return true;
- else
- return false;
- }
+ // sort by knowns (in enum order), then by ids (in string order)
+ if (d->known != -1) {
+ if (other.d->known == -1) {
+ return true;
+ } else if (d->known < other.d->known) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ if (other.d->known != -1) {
+ return false;
+ } else if (d->id < other.d->id) {
+ return true;
+ } else {
+ return false;
+ }
+ }
}
bool CertificateInfoType::operator==(const CertificateInfoType &other) const
{
- // are both known types?
- if(d->known != -1 && other.d->known != -1)
- {
- // if so, compare the ints
- if(d->known != other.d->known)
- return false;
- }
- else
- {
- // otherwise, compare the string ids
- if(d->id != other.d->id)
- return false;
- }
+ // are both known types?
+ if (d->known != -1 && other.d->known != -1) {
+ // if so, compare the ints
+ if (d->known != other.d->known) {
+ return false;
+ }
+ } else {
+ // otherwise, compare the string ids
+ if (d->id != other.d->id) {
+ return false;
+ }
+ }
- if(d->section != other.d->section)
- return false;
+ if (d->section != other.d->section) {
+ return false;
+ }
- return true;
+ return true;
}
//----------------------------------------------------------------------------
// CertificateInfoPair
//----------------------------------------------------------------------------
class CertificateInfoPair::Private : public QSharedData
{
public:
- CertificateInfoType type;
- QString value;
+ CertificateInfoType type;
+ QString value;
};
CertificateInfoPair::CertificateInfoPair()
-:d(new Private)
+ : d(new Private)
{
}
CertificateInfoPair::CertificateInfoPair(const CertificateInfoType &type, const QString &value)
-:d(new Private)
+ : d(new Private)
{
- d->type = type;
- d->value = value;
+ d->type = type;
+ d->value = value;
}
CertificateInfoPair::CertificateInfoPair(const CertificateInfoPair &from)
-:d(from.d)
+ : d(from.d)
{
}
CertificateInfoPair::~CertificateInfoPair()
{
}
-CertificateInfoPair & CertificateInfoPair::operator=(const CertificateInfoPair &from)
+CertificateInfoPair &CertificateInfoPair::operator=(const CertificateInfoPair &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
CertificateInfoType CertificateInfoPair::type() const
{
- return d->type;
+ return d->type;
}
QString CertificateInfoPair::value() const
{
- return d->value;
+ return d->value;
}
bool CertificateInfoPair::operator==(const CertificateInfoPair &other) const
{
- if(d->type == other.d->type && d->value == other.d->value)
- return true;
- return false;
+ if (d->type == other.d->type && d->value == other.d->value) {
+ return true;
+ }
+ return false;
}
//----------------------------------------------------------------------------
// ConstraintType
//----------------------------------------------------------------------------
class ConstraintType::Private : public QSharedData
{
public:
- ConstraintType::Section section;
- int known;
- QString id;
-
- Private() :
- section(ConstraintType::KeyUsage),
- known(-1)
- {
- }
+ ConstraintType::Section section;
+ int known;
+ QString id;
+
+ Private() :
+ section(ConstraintType::KeyUsage),
+ known(-1)
+ {
+ }
};
ConstraintType::ConstraintType()
-:d(new Private)
+ : d(new Private)
{
}
ConstraintType::ConstraintType(ConstraintTypeKnown known)
-:d(new Private)
+ : d(new Private)
{
- d->section = constraintKnownToSection(known);
- d->known = known;
- d->id = constraintKnownToId(known); // always valid
+ d->section = constraintKnownToSection(known);
+ d->known = known;
+ d->id = constraintKnownToId(known); // always valid
}
ConstraintType::ConstraintType(const QString &id, Section section)
-:d(new Private)
+ : d(new Private)
{
- d->section = section;
- d->known = constraintIdToKnown(id); // can be -1 for unknown
- d->id = id;
+ d->section = section;
+ d->known = constraintIdToKnown(id); // can be -1 for unknown
+ d->id = id;
}
ConstraintType::ConstraintType(const ConstraintType &from)
-:d(from.d)
+ : d(from.d)
{
}
ConstraintType::~ConstraintType()
{
}
-ConstraintType & ConstraintType::operator=(const ConstraintType &from)
+ConstraintType &ConstraintType::operator=(const ConstraintType &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
ConstraintType::Section ConstraintType::section() const
{
- return d->section;
+ return d->section;
}
ConstraintTypeKnown ConstraintType::known() const
{
- return (ConstraintTypeKnown)d->known;
+ return (ConstraintTypeKnown)d->known;
}
QString ConstraintType::id() const
{
- return d->id;
+ return d->id;
}
bool ConstraintType::operator<(const ConstraintType &other) const
{
- // sort by knowns (in enum order), then by ids (in string order)
- if(d->known != -1)
- {
- if(other.d->known == -1)
- return true;
- else if(d->known < other.d->known)
- return true;
- else
- return false;
- }
- else
- {
- if(other.d->known != -1)
- return false;
- else if(d->id < other.d->id)
- return true;
- else
- return false;
- }
+ // sort by knowns (in enum order), then by ids (in string order)
+ if (d->known != -1) {
+ if (other.d->known == -1) {
+ return true;
+ } else if (d->known < other.d->known) {
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ if (other.d->known != -1) {
+ return false;
+ } else if (d->id < other.d->id) {
+ return true;
+ } else {
+ return false;
+ }
+ }
}
bool ConstraintType::operator==(const ConstraintType &other) const
{
- // are both known types?
- if(d->known != -1 && other.d->known != -1)
- {
- // if so, compare the ints
- if(d->known != other.d->known)
- return false;
- }
- else
- {
- // otherwise, compare the string ids
- if(d->id != other.d->id)
- return false;
- }
+ // are both known types?
+ if (d->known != -1 && other.d->known != -1) {
+ // if so, compare the ints
+ if (d->known != other.d->known) {
+ return false;
+ }
+ } else {
+ // otherwise, compare the string ids
+ if (d->id != other.d->id) {
+ return false;
+ }
+ }
- if(d->section != other.d->section)
- return false;
+ if (d->section != other.d->section) {
+ return false;
+ }
- return true;
+ return true;
}
//----------------------------------------------------------------------------
// CertificateOptions
//----------------------------------------------------------------------------
class CertificateOptions::Private
{
public:
- CertificateRequestFormat format;
-
- QString challenge;
- CertificateInfoOrdered info;
- CertificateInfo infoMap;
- Constraints constraints;
- QStringList policies;
- QStringList crlLocations, issuerLocations, ocspLocations;
- bool isCA;
- int pathLimit;
- BigInteger serial;
- QDateTime start, end;
-
- Private() : isCA(false), pathLimit(0)
- {
- }
+ CertificateRequestFormat format;
+
+ QString challenge;
+ CertificateInfoOrdered info;
+ CertificateInfo infoMap;
+ Constraints constraints;
+ QStringList policies;
+ QStringList crlLocations, issuerLocations, ocspLocations;
+ bool isCA;
+ int pathLimit;
+ BigInteger serial;
+ QDateTime start, end;
+
+ Private() : isCA(false), pathLimit(0)
+ {
+ }
};
CertificateOptions::CertificateOptions(CertificateRequestFormat f)
{
- d = new Private;
- d->format = f;
+ d = new Private;
+ d->format = f;
}
CertificateOptions::CertificateOptions(const CertificateOptions &from)
{
- d = new Private(*from.d);
+ d = new Private(*from.d);
}
CertificateOptions::~CertificateOptions()
{
- delete d;
+ delete d;
}
-CertificateOptions & CertificateOptions::operator=(const CertificateOptions &from)
+CertificateOptions &CertificateOptions::operator=(const CertificateOptions &from)
{
- *d = *from.d;
- return *this;
+ *d = *from.d;
+ return *this;
}
CertificateRequestFormat CertificateOptions::format() const
{
- return d->format;
+ return d->format;
}
void CertificateOptions::setFormat(CertificateRequestFormat f)
{
- d->format = f;
+ d->format = f;
}
bool CertificateOptions::isValid() const
{
- // logic from Botan
- if(d->infoMap.value(CommonName).isEmpty() || d->infoMap.value(Country).isEmpty())
- return false;
- if(d->infoMap.value(Country).length() != 2)
- return false;
- if(d->start >= d->end)
- return false;
- return true;
+ // logic from Botan
+ if (d->infoMap.value(CommonName).isEmpty() || d->infoMap.value(Country).isEmpty()) {
+ return false;
+ }
+ if (d->infoMap.value(Country).length() != 2) {
+ return false;
+ }
+ if (d->start >= d->end) {
+ return false;
+ }
+ return true;
}
QString CertificateOptions::challenge() const
{
- return d->challenge;
+ return d->challenge;
}
CertificateInfo CertificateOptions::info() const
{
- return d->infoMap;
+ return d->infoMap;
}
CertificateInfoOrdered CertificateOptions::infoOrdered() const
{
- return d->info;
+ return d->info;
}
Constraints CertificateOptions::constraints() const
{
- return d->constraints;
+ return d->constraints;
}
QStringList CertificateOptions::policies() const
{
- return d->policies;
+ return d->policies;
}
QStringList CertificateOptions::crlLocations() const
{
- return d->crlLocations;
+ return d->crlLocations;
}
QStringList CertificateOptions::issuerLocations() const
{
- return d->issuerLocations;
+ return d->issuerLocations;
}
QStringList CertificateOptions::ocspLocations() const
{
- return d->ocspLocations;
+ return d->ocspLocations;
}
bool CertificateOptions::isCA() const
{
- return d->isCA;
+ return d->isCA;
}
int CertificateOptions::pathLimit() const
{
- return d->pathLimit;
+ return d->pathLimit;
}
BigInteger CertificateOptions::serialNumber() const
{
- return d->serial;
+ return d->serial;
}
QDateTime CertificateOptions::notValidBefore() const
{
- return d->start;
+ return d->start;
}
QDateTime CertificateOptions::notValidAfter() const
{
- return d->end;
+ return d->end;
}
void CertificateOptions::setChallenge(const QString &s)
{
- d->challenge = s;
+ d->challenge = s;
}
void CertificateOptions::setInfo(const CertificateInfo &info)
{
- d->info = mapToOrdered(info);
- d->infoMap = info;
+ d->info = mapToOrdered(info);
+ d->infoMap = info;
}
void CertificateOptions::setInfoOrdered(const CertificateInfoOrdered &info)
{
- d->info = info;
- d->infoMap = orderedToMap(info);
+ d->info = info;
+ d->infoMap = orderedToMap(info);
}
void CertificateOptions::setConstraints(const Constraints &constraints)
{
- d->constraints = constraints;
+ d->constraints = constraints;
}
void CertificateOptions::setPolicies(const QStringList &policies)
{
- d->policies = policies;
+ d->policies = policies;
}
void CertificateOptions::setCRLLocations(const QStringList &locations)
{
- d->crlLocations = locations;
+ d->crlLocations = locations;
}
void CertificateOptions::setIssuerLocations(const QStringList &locations)
{
- d->issuerLocations = locations;
+ d->issuerLocations = locations;
}
void CertificateOptions::setOCSPLocations(const QStringList &locations)
{
- d->ocspLocations = locations;
+ d->ocspLocations = locations;
}
void CertificateOptions::setAsCA(int pathLimit)
{
- d->isCA = true;
- d->pathLimit = pathLimit;
+ d->isCA = true;
+ d->pathLimit = pathLimit;
}
void CertificateOptions::setAsUser()
{
- d->isCA = false;
- d->pathLimit = 0;
+ d->isCA = false;
+ d->pathLimit = 0;
}
void CertificateOptions::setSerialNumber(const BigInteger &i)
{
- d->serial = i;
+ d->serial = i;
}
void CertificateOptions::setValidityPeriod(const QDateTime &start, const QDateTime &end)
{
- d->start = start;
- d->end = end;
+ d->start = start;
+ d->end = end;
}
//----------------------------------------------------------------------------
// Certificate
//----------------------------------------------------------------------------
// ip address string to binary (msb), adapted from jdns (adapted from qt)
// return: size 4 = ipv4, size 16 = ipv6, size 0 = error
static QByteArray ipaddr_str2bin(const QString &str)
{
- // ipv6
- if(str.contains(':'))
- {
- QStringList parts = str.split(':', QString::KeepEmptyParts);
- if(parts.count() < 3 || parts.count() > 8)
- return QByteArray();
-
- QByteArray ipv6(16, 0);
- int at = 16;
- int fill = 9 - parts.count();
- for(int n = parts.count() - 1; n >= 0; --n)
- {
- if(at <= 0)
- return QByteArray();
-
- if(parts[n].isEmpty())
- {
- if(n == parts.count() - 1)
- {
- if(!parts[n - 1].isEmpty())
- return QByteArray();
- ipv6[--at] = 0;
- ipv6[--at] = 0;
- }
- else if(n == 0)
- {
- if(!parts[n + 1].isEmpty())
- return QByteArray();
- ipv6[--at] = 0;
- ipv6[--at] = 0;
- }
- else
- {
- for(int i = 0; i < fill; ++i)
- {
- if(at <= 0)
- return QByteArray();
- ipv6[--at] = 0;
- ipv6[--at] = 0;
- }
- }
- }
- else
- {
- if(parts[n].indexOf('.') == -1)
- {
- bool ok;
- int x = parts[n].toInt(&ok, 16);
- if(!ok || x < 0 || x > 0xffff)
- return QByteArray();
- ipv6[--at] = x & 0xff;
- ipv6[--at] = (x >> 8) & 0xff;
- }
- else
- {
- if(n != parts.count() - 1)
- return QByteArray();
-
- QByteArray buf = ipaddr_str2bin(parts[n]);
- if(buf.isEmpty())
- return QByteArray();
-
- ipv6[--at] = buf[3];
- ipv6[--at] = buf[2];
- ipv6[--at] = buf[1];
- ipv6[--at] = buf[0];
- --fill;
- }
- }
- }
-
- return ipv6;
- }
- else if(str.contains('.'))
- {
- QStringList parts = str.split('.', QString::KeepEmptyParts);
- if(parts.count() != 4)
- return QByteArray();
-
- QByteArray out(4, 0);
- for(int n = 0; n < 4; ++n)
- {
- bool ok;
- int x = parts[n].toInt(&ok);
- if(!ok || x < 0 || x > 0xff)
- return QByteArray();
- out[n] = (unsigned char)x;
- }
- return out;
- }
- else
- return QByteArray();
+ // ipv6
+ if (str.contains(':')) {
+ QStringList parts = str.split(':', QString::KeepEmptyParts);
+ if (parts.count() < 3 || parts.count() > 8) {
+ return QByteArray();
+ }
+
+ QByteArray ipv6(16, 0);
+ int at = 16;
+ int fill = 9 - parts.count();
+ for (int n = parts.count() - 1; n >= 0; --n) {
+ if (at <= 0) {
+ return QByteArray();
+ }
+
+ if (parts[n].isEmpty()) {
+ if (n == parts.count() - 1) {
+ if (!parts[n - 1].isEmpty()) {
+ return QByteArray();
+ }
+ ipv6[--at] = 0;
+ ipv6[--at] = 0;
+ } else if (n == 0) {
+ if (!parts[n + 1].isEmpty()) {
+ return QByteArray();
+ }
+ ipv6[--at] = 0;
+ ipv6[--at] = 0;
+ } else {
+ for (int i = 0; i < fill; ++i) {
+ if (at <= 0) {
+ return QByteArray();
+ }
+ ipv6[--at] = 0;
+ ipv6[--at] = 0;
+ }
+ }
+ } else {
+ if (parts[n].indexOf('.') == -1) {
+ bool ok;
+ int x = parts[n].toInt(&ok, 16);
+ if (!ok || x < 0 || x > 0xffff) {
+ return QByteArray();
+ }
+ ipv6[--at] = x & 0xff;
+ ipv6[--at] = (x >> 8) & 0xff;
+ } else {
+ if (n != parts.count() - 1) {
+ return QByteArray();
+ }
+
+ QByteArray buf = ipaddr_str2bin(parts[n]);
+ if (buf.isEmpty()) {
+ return QByteArray();
+ }
+
+ ipv6[--at] = buf[3];
+ ipv6[--at] = buf[2];
+ ipv6[--at] = buf[1];
+ ipv6[--at] = buf[0];
+ --fill;
+ }
+ }
+ }
+
+ return ipv6;
+ } else if (str.contains('.')) {
+ QStringList parts = str.split('.', QString::KeepEmptyParts);
+ if (parts.count() != 4) {
+ return QByteArray();
+ }
+
+ QByteArray out(4, 0);
+ for (int n = 0; n < 4; ++n) {
+ bool ok;
+ int x = parts[n].toInt(&ok);
+ if (!ok || x < 0 || x > 0xff) {
+ return QByteArray();
+ }
+ out[n] = (unsigned char)x;
+ }
+ return out;
+ } else {
+ return QByteArray();
+ }
}
// acedomain must be all lowercase, with no trailing dot or wildcards
static bool cert_match_domain(const QString &certname, const QString &acedomain)
{
- // KSSL strips start/end whitespace, even though such whitespace is
- // probably not legal anyway. (compat)
- QString name = certname.trimmed();
-
- // KSSL strips trailing dot, even though the dot is probably not
- // legal anyway. (compat)
- if(name.length() > 0 && name[name.length()-1] == '.')
- name.truncate(name.length()-1);
-
- // after our compatibility modifications, make sure the name isn't
- // empty.
- if(name.isEmpty())
- return false;
-
- // lowercase, for later performing case insensitive matching
- name = name.toLower();
-
- // ensure the cert field contains valid characters only
- if(QRegExp("[^a-z0-9\\.\\*\\-]").indexIn(name) >= 0)
- return false;
-
- // hack into parts, and require at least 1 part
- QStringList parts_name = name.split('.', QString::KeepEmptyParts);
- if(parts_name.isEmpty())
- return false;
-
- // KSSL checks to make sure the last two parts don't contain
- // wildcards. I don't know where it is written that this
- // should be done, but for compat sake we'll do it.
- if(parts_name[parts_name.count()-1].contains('*'))
- return false;
- if(parts_name.count() >= 2 && parts_name[parts_name.count()-2].contains('*'))
- return false;
-
- QStringList parts_compare = acedomain.split('.', QString::KeepEmptyParts);
- if(parts_compare.isEmpty())
- return false;
-
- // don't allow empty parts
- foreach(const QString &s, parts_name)
- {
- if(s.isEmpty())
- return false;
- }
- foreach(const QString &s, parts_compare)
- {
- if(s.isEmpty())
- return false;
- }
-
- // RFC2818: "Names may contain the wildcard character * which is
- // considered to match any single domain name component or
- // component fragment. E.g., *.a.com matches foo.a.com but not
- // bar.foo.a.com. f*.com matches foo.com but not bar.com."
- //
- // This means that for the domain to match it must have the
- // same number of components, wildcards or not. If there are
- // wildcards, their scope must only be within the component
- // they reside in.
- //
- // First, make sure the number of parts is equal.
- if(parts_name.count() != parts_compare.count())
- return false;
-
- // Now compare each part
- for(int n = 0; n < parts_name.count(); ++n)
- {
- const QString &p1 = parts_name[n];
- const QString &p2 = parts_compare[n];
-
- if(!QRegExp(p1, Qt::CaseSensitive, QRegExp::Wildcard).exactMatch(p2))
- return false;
- }
-
- return true;
+ // KSSL strips start/end whitespace, even though such whitespace is
+ // probably not legal anyway. (compat)
+ QString name = certname.trimmed();
+
+ // KSSL strips trailing dot, even though the dot is probably not
+ // legal anyway. (compat)
+ if (name.length() > 0 && name[name.length() - 1] == '.') {
+ name.truncate(name.length() - 1);
+ }
+
+ // after our compatibility modifications, make sure the name isn't
+ // empty.
+ if (name.isEmpty()) {
+ return false;
+ }
+
+ // lowercase, for later performing case insensitive matching
+ name = name.toLower();
+
+ // ensure the cert field contains valid characters only
+ if (QRegExp("[^a-z0-9\\.\\*\\-]").indexIn(name) >= 0) {
+ return false;
+ }
+
+ // hack into parts, and require at least 1 part
+ QStringList parts_name = name.split('.', QString::KeepEmptyParts);
+ if (parts_name.isEmpty()) {
+ return false;
+ }
+
+ // KSSL checks to make sure the last two parts don't contain
+ // wildcards. I don't know where it is written that this
+ // should be done, but for compat sake we'll do it.
+ if (parts_name[parts_name.count() - 1].contains('*')) {
+ return false;
+ }
+ if (parts_name.count() >= 2 && parts_name[parts_name.count() - 2].contains('*')) {
+ return false;
+ }
+
+ QStringList parts_compare = acedomain.split('.', QString::KeepEmptyParts);
+ if (parts_compare.isEmpty()) {
+ return false;
+ }
+
+ // don't allow empty parts
+ foreach (const QString &s, parts_name) {
+ if (s.isEmpty()) {
+ return false;
+ }
+ }
+ foreach (const QString &s, parts_compare) {
+ if (s.isEmpty()) {
+ return false;
+ }
+ }
+
+ // RFC2818: "Names may contain the wildcard character * which is
+ // considered to match any single domain name component or
+ // component fragment. E.g., *.a.com matches foo.a.com but not
+ // bar.foo.a.com. f*.com matches foo.com but not bar.com."
+ //
+ // This means that for the domain to match it must have the
+ // same number of components, wildcards or not. If there are
+ // wildcards, their scope must only be within the component
+ // they reside in.
+ //
+ // First, make sure the number of parts is equal.
+ if (parts_name.count() != parts_compare.count()) {
+ return false;
+ }
+
+ // Now compare each part
+ for (int n = 0; n < parts_name.count(); ++n) {
+ const QString &p1 = parts_name[n];
+ const QString &p2 = parts_compare[n];
+
+ if (!QRegExp(p1, Qt::CaseSensitive, QRegExp::Wildcard).exactMatch(p2)) {
+ return false;
+ }
+ }
+
+ return true;
}
// ipaddress must be an ipv4 or ipv6 address in binary format
static bool cert_match_ipaddress(const QString &certname, const QByteArray &ipaddress)
{
- // KSSL strips start/end whitespace, even though such whitespace is
- // probably not legal anyway. (compat)
- QString name = certname.trimmed();
+ // KSSL strips start/end whitespace, even though such whitespace is
+ // probably not legal anyway. (compat)
+ QString name = certname.trimmed();
- // KSSL accepts IPv6 in brackets, which is usually done for URIs, but
- // IMO sounds very strange for a certificate. We'll follow this
- // behavior anyway. (compat)
- if(name.length() >= 2 && name[0] == '[' && name[name.length()-1] == ']')
- name = name.mid(1, name.length() - 2); // chop off brackets
+ // KSSL accepts IPv6 in brackets, which is usually done for URIs, but
+ // IMO sounds very strange for a certificate. We'll follow this
+ // behavior anyway. (compat)
+ if (name.length() >= 2 && name[0] == '[' && name[name.length() - 1] == ']') {
+ name = name.mid(1, name.length() - 2); // chop off brackets
+ }
- // after our compatibility modifications, make sure the name isn't
- // empty.
- if(name.isEmpty())
- return false;
+ // after our compatibility modifications, make sure the name isn't
+ // empty.
+ if (name.isEmpty()) {
+ return false;
+ }
- // convert to binary form
- QByteArray addr = ipaddr_str2bin(name);
- if(addr.isEmpty())
- return false;
+ // convert to binary form
+ QByteArray addr = ipaddr_str2bin(name);
+ if (addr.isEmpty()) {
+ return false;
+ }
- // not the same?
- if(addr != ipaddress)
- return false;
+ // not the same?
+ if (addr != ipaddress) {
+ return false;
+ }
- return true;
+ return true;
}
class Certificate::Private : public QSharedData
{
public:
- CertificateInfo subjectInfoMap, issuerInfoMap;
-
- void update(CertContext *c)
- {
- if(c)
- {
- subjectInfoMap = orderedToMap(c->props()->subject);
- issuerInfoMap = orderedToMap(c->props()->issuer);
- }
- else
- {
- subjectInfoMap = CertificateInfo();
- issuerInfoMap = CertificateInfo();
- }
- }
+ CertificateInfo subjectInfoMap, issuerInfoMap;
+
+ void update(CertContext *c)
+ {
+ if (c) {
+ subjectInfoMap = orderedToMap(c->props()->subject);
+ issuerInfoMap = orderedToMap(c->props()->issuer);
+ } else {
+ subjectInfoMap = CertificateInfo();
+ issuerInfoMap = CertificateInfo();
+ }
+ }
};
Certificate::Certificate()
-:d(new Private)
+ : d(new Private)
{
}
Certificate::Certificate(const QString &fileName)
-:d(new Private)
+ : d(new Private)
{
- *this = fromPEMFile(fileName, 0, QString());
+ *this = fromPEMFile(fileName, 0, QString());
}
Certificate::Certificate(const CertificateOptions &opts, const PrivateKey &key, const QString &provider)
-:d(new Private)
+ : d(new Private)
{
- CertContext *c = static_cast<CertContext *>(getContext("cert", provider));
- if(c->createSelfSigned(opts, *(static_cast<const PKeyContext *>(key.context()))))
- change(c);
- else
- delete c;
+ CertContext *c = static_cast<CertContext *>(getContext("cert", provider));
+ if (c->createSelfSigned(opts, *(static_cast<const PKeyContext *>(key.context())))) {
+ change(c);
+ } else {
+ delete c;
+ }
}
Certificate::Certificate(const Certificate &from)
-:Algorithm(from), d(from.d)
+ : Algorithm(from), d(from.d)
{
}
Certificate::~Certificate()
{
}
-Certificate & Certificate::operator=(const Certificate &from)
+Certificate &Certificate::operator=(const Certificate &from)
{
- Algorithm::operator=(from);
- d = from.d;
- return *this;
+ Algorithm::operator=(from);
+ d = from.d;
+ return *this;
}
bool Certificate::isNull() const
{
- return (!context() ? true : false);
+ return (!context() ? true : false);
}
QDateTime Certificate::notValidBefore() const
{
- return static_cast<const CertContext *>(context())->props()->start;
+ return static_cast<const CertContext *>(context())->props()->start;
}
QDateTime Certificate::notValidAfter() const
{
- return static_cast<const CertContext *>(context())->props()->end;
+ return static_cast<const CertContext *>(context())->props()->end;
}
CertificateInfo Certificate::subjectInfo() const
{
- return d->subjectInfoMap;
+ return d->subjectInfoMap;
}
CertificateInfoOrdered Certificate::subjectInfoOrdered() const
{
- return static_cast<const CertContext *>(context())->props()->subject;
+ return static_cast<const CertContext *>(context())->props()->subject;
}
CertificateInfo Certificate::issuerInfo() const
{
- return d->issuerInfoMap;
+ return d->issuerInfoMap;
}
CertificateInfoOrdered Certificate::issuerInfoOrdered() const
{
- return static_cast<const CertContext *>(context())->props()->issuer;
+ return static_cast<const CertContext *>(context())->props()->issuer;
}
Constraints Certificate::constraints() const
{
- return static_cast<const CertContext *>(context())->props()->constraints;
+ return static_cast<const CertContext *>(context())->props()->constraints;
}
QStringList Certificate::policies() const
{
- return static_cast<const CertContext *>(context())->props()->policies;
+ return static_cast<const CertContext *>(context())->props()->policies;
}
QStringList Certificate::crlLocations() const
{
- return static_cast<const CertContext *>(context())->props()->crlLocations;
+ return static_cast<const CertContext *>(context())->props()->crlLocations;
}
QStringList Certificate::issuerLocations() const
{
- return static_cast<const CertContext *>(context())->props()->issuerLocations;
+ return static_cast<const CertContext *>(context())->props()->issuerLocations;
}
QStringList Certificate::ocspLocations() const
{
- return static_cast<const CertContext *>(context())->props()->ocspLocations;
+ return static_cast<const CertContext *>(context())->props()->ocspLocations;
}
QString Certificate::commonName() const
{
- return d->subjectInfoMap.value(CommonName);
+ return d->subjectInfoMap.value(CommonName);
}
BigInteger Certificate::serialNumber() const
{
- return static_cast<const CertContext *>(context())->props()->serial;
+ return static_cast<const CertContext *>(context())->props()->serial;
}
PublicKey Certificate::subjectPublicKey() const
{
- PKeyContext *c = static_cast<const CertContext *>(context())->subjectPublicKey();
- PublicKey key;
- key.change(c);
- return key;
+ PKeyContext *c = static_cast<const CertContext *>(context())->subjectPublicKey();
+ PublicKey key;
+ key.change(c);
+ return key;
}
bool Certificate::isCA() const
{
- return static_cast<const CertContext *>(context())->props()->isCA;
+ return static_cast<const CertContext *>(context())->props()->isCA;
}
bool Certificate::isSelfSigned() const
{
- return static_cast<const CertContext *>(context())->props()->isSelfSigned;
+ return static_cast<const CertContext *>(context())->props()->isSelfSigned;
}
bool Certificate::isIssuerOf(const Certificate &other) const
{
- const CertContext *cc = static_cast<const CertContext *>(other.context());
- return static_cast<const CertContext *>(context())->isIssuerOf(cc);
+ const CertContext *cc = static_cast<const CertContext *>(other.context());
+ return static_cast<const CertContext *>(context())->isIssuerOf(cc);
}
int Certificate::pathLimit() const
{
- return static_cast<const CertContext *>(context())->props()->pathLimit;
+ return static_cast<const CertContext *>(context())->props()->pathLimit;
}
SignatureAlgorithm Certificate::signatureAlgorithm() const
{
- return static_cast<const CertContext *>(context())->props()->sigalgo;
+ return static_cast<const CertContext *>(context())->props()->sigalgo;
}
QByteArray Certificate::subjectKeyId() const
{
- return static_cast<const CertContext *>(context())->props()->subjectId;
+ return static_cast<const CertContext *>(context())->props()->subjectId;
}
QByteArray Certificate::issuerKeyId() const
{
- return static_cast<const CertContext *>(context())->props()->issuerId;
+ return static_cast<const CertContext *>(context())->props()->issuerId;
}
Validity Certificate::validate(const CertificateCollection &trusted, const CertificateCollection &untrusted, UsageMode u, ValidateFlags vf) const
{
- QList<Certificate> issuers = trusted.certificates() + untrusted.certificates();
- CertificateChain chain;
- chain += *this;
- Validity result;
- chain = chain.complete(issuers, &result);
- if(result != ValidityGood)
- return result;
- return chain.validate(trusted, untrusted.crls(), u, vf);
+ QList<Certificate> issuers = trusted.certificates() + untrusted.certificates();
+ CertificateChain chain;
+ chain += *this;
+ Validity result;
+ chain = chain.complete(issuers, &result);
+ if (result != ValidityGood) {
+ return result;
+ }
+ return chain.validate(trusted, untrusted.crls(), u, vf);
}
QByteArray Certificate::toDER() const
{
- return static_cast<const CertContext *>(context())->toDER();
+ return static_cast<const CertContext *>(context())->toDER();
}
QString Certificate::toPEM() const
{
- return static_cast<const CertContext *>(context())->toPEM();
+ return static_cast<const CertContext *>(context())->toPEM();
}
bool Certificate::toPEMFile(const QString &fileName) const
{
- return stringToFile(fileName, toPEM());
+ return stringToFile(fileName, toPEM());
}
Certificate Certificate::fromDER(const QByteArray &a, ConvertResult *result, const QString &provider)
{
- Certificate c;
- CertContext *cc = static_cast<CertContext *>(getContext("cert", provider));
- ConvertResult r = cc->fromDER(a);
- if(result)
- *result = r;
- if(r == ConvertGood)
- c.change(cc);
- else
- delete cc;
- return c;
+ Certificate c;
+ CertContext *cc = static_cast<CertContext *>(getContext("cert", provider));
+ ConvertResult r = cc->fromDER(a);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ c.change(cc);
+ } else {
+ delete cc;
+ }
+ return c;
}
Certificate Certificate::fromPEM(const QString &s, ConvertResult *result, const QString &provider)
{
- Certificate c;
- CertContext *cc = static_cast<CertContext *>(getContext("cert", provider));
- ConvertResult r = cc->fromPEM(s);
- if(result)
- *result = r;
- if(r == ConvertGood)
- c.change(cc);
- else
- delete cc;
- return c;
+ Certificate c;
+ CertContext *cc = static_cast<CertContext *>(getContext("cert", provider));
+ ConvertResult r = cc->fromPEM(s);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ c.change(cc);
+ } else {
+ delete cc;
+ }
+ return c;
}
Certificate Certificate::fromPEMFile(const QString &fileName, ConvertResult *result, const QString &provider)
{
- QString pem;
- if(!stringFromFile(fileName, &pem))
- {
- if(result)
- *result = ErrorFile;
- return Certificate();
- }
- return fromPEM(pem, result, provider);
+ QString pem;
+ if (!stringFromFile(fileName, &pem)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return Certificate();
+ }
+ return fromPEM(pem, result, provider);
}
// check for ip addresses in iPAddress, dNSName, then commonName
// for all else, check in dNSName, then commonName
bool Certificate::matchesHostName(const QString &host) const
{
- QByteArray ipaddr = ipaddr_str2bin(host);
- if(!ipaddr.isEmpty()) // ip address
- {
- // check iPAddress
- foreach(const QString &s, subjectInfo().values(IPAddress))
- {
- if(cert_match_ipaddress(s, ipaddr))
- return true;
- }
-
- // check dNSName
- foreach(const QString &s, subjectInfo().values(DNS))
- {
- if(cert_match_ipaddress(s, ipaddr))
- return true;
- }
-
- // check commonName
- foreach(const QString &s, subjectInfo().values(CommonName))
- {
- if(cert_match_ipaddress(s, ipaddr))
- return true;
- }
- }
- else // domain
- {
- // lowercase
- QString name = host.toLower();
-
- // ACE
- name = QString::fromLatin1(QUrl::toAce(name));
-
- // don't allow wildcards in the comparison host
- if(name.contains('*'))
- return false;
-
- // strip out trailing dot
- if(name.length() > 0 && name[name.length()-1] == '.')
- name.truncate(name.length()-1);
-
- // make sure the name is not empty after our modifications
- if(name.isEmpty())
- return false;
-
- // check dNSName
- foreach(const QString &s, subjectInfo().values(DNS))
- {
- if(cert_match_domain(s, name))
- return true;
- }
-
- // check commonName
- foreach(const QString &s, subjectInfo().values(CommonName))
- {
- if(cert_match_domain(s, name))
- return true;
- }
- }
-
- return false;
+ QByteArray ipaddr = ipaddr_str2bin(host);
+ if (!ipaddr.isEmpty()) { // ip address
+ // check iPAddress
+ foreach (const QString &s, subjectInfo().values(IPAddress)) {
+ if (cert_match_ipaddress(s, ipaddr)) {
+ return true;
+ }
+ }
+
+ // check dNSName
+ foreach (const QString &s, subjectInfo().values(DNS)) {
+ if (cert_match_ipaddress(s, ipaddr)) {
+ return true;
+ }
+ }
+
+ // check commonName
+ foreach (const QString &s, subjectInfo().values(CommonName)) {
+ if (cert_match_ipaddress(s, ipaddr)) {
+ return true;
+ }
+ }
+ } else { // domain
+ // lowercase
+ QString name = host.toLower();
+
+ // ACE
+ name = QString::fromLatin1(QUrl::toAce(name));
+
+ // don't allow wildcards in the comparison host
+ if (name.contains('*')) {
+ return false;
+ }
+
+ // strip out trailing dot
+ if (name.length() > 0 && name[name.length() - 1] == '.') {
+ name.truncate(name.length() - 1);
+ }
+
+ // make sure the name is not empty after our modifications
+ if (name.isEmpty()) {
+ return false;
+ }
+
+ // check dNSName
+ foreach (const QString &s, subjectInfo().values(DNS)) {
+ if (cert_match_domain(s, name)) {
+ return true;
+ }
+ }
+
+ // check commonName
+ foreach (const QString &s, subjectInfo().values(CommonName)) {
+ if (cert_match_domain(s, name)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
}
bool Certificate::operator==(const Certificate &otherCert) const
{
- if(isNull())
- {
- if(otherCert.isNull())
- return true;
- else
- return false;
- }
- else if(otherCert.isNull())
- return false;
+ if (isNull()) {
+ if (otherCert.isNull()) {
+ return true;
+ } else {
+ return false;
+ }
+ } else if (otherCert.isNull()) {
+ return false;
+ }
- const CertContext *other = static_cast<const CertContext *>(otherCert.context());
- return static_cast<const CertContext *>(context())->compare(other);
+ const CertContext *other = static_cast<const CertContext *>(otherCert.context());
+ return static_cast<const CertContext *>(context())->compare(other);
}
void Certificate::change(CertContext *c)
{
- Algorithm::change(c);
- d->update(static_cast<CertContext *>(context()));
+ Algorithm::change(c);
+ d->update(static_cast<CertContext *>(context()));
}
Validity Certificate::chain_validate(const CertificateChain &chain, const CertificateCollection &trusted, const QList<CRL> &untrusted_crls, UsageMode u, ValidateFlags vf) const
{
- QList<CertContext*> chain_list;
- QList<CertContext*> trusted_list;
- QList<CRLContext*> crl_list;
-
- QList<Certificate> chain_certs = chain;
- QList<Certificate> trusted_certs = trusted.certificates();
- QList<CRL> crls = trusted.crls() + untrusted_crls;
-
- for(int n = 0; n < chain_certs.count(); ++n)
- {
- CertContext *c = static_cast<CertContext *>(chain_certs[n].context());
- chain_list += c;
- }
- for(int n = 0; n < trusted_certs.count(); ++n)
- {
- CertContext *c = static_cast<CertContext *>(trusted_certs[n].context());
- trusted_list += c;
- }
- for(int n = 0; n < crls.count(); ++n)
- {
- CRLContext *c = static_cast<CRLContext *>(crls[n].context());
- crl_list += c;
- }
-
- return static_cast<const CertContext *>(context())->validate_chain(chain_list, trusted_list, crl_list, u, vf);
+ QList<CertContext *> chain_list;
+ QList<CertContext *> trusted_list;
+ QList<CRLContext *> crl_list;
+
+ QList<Certificate> chain_certs = chain;
+ QList<Certificate> trusted_certs = trusted.certificates();
+ QList<CRL> crls = trusted.crls() + untrusted_crls;
+
+ for (int n = 0; n < chain_certs.count(); ++n) {
+ CertContext *c = static_cast<CertContext *>(chain_certs[n].context());
+ chain_list += c;
+ }
+ for (int n = 0; n < trusted_certs.count(); ++n) {
+ CertContext *c = static_cast<CertContext *>(trusted_certs[n].context());
+ trusted_list += c;
+ }
+ for (int n = 0; n < crls.count(); ++n) {
+ CRLContext *c = static_cast<CRLContext *>(crls[n].context());
+ crl_list += c;
+ }
+
+ return static_cast<const CertContext *>(context())->validate_chain(chain_list, trusted_list, crl_list, u, vf);
}
CertificateChain Certificate::chain_complete(const CertificateChain &chain, const QList<Certificate> &issuers, Validity *result) const
{
- CertificateChain out;
- QList<Certificate> pool = issuers + chain.mid(1);
- out += chain.first();
- if(result)
- *result = ValidityGood;
- while(!out.last().isSelfSigned())
- {
- // try to get next in chain
- int at = -1;
- for(int n = 0; n < pool.count(); ++n)
- {
- //QString str = QString("[%1] issued by [%2] ? ").arg(out.last().commonName()).arg(pool[n].commonName());
- if(pool[n].isIssuerOf(out.last()))
- {
- //printf("%s yes\n", qPrintable(str));
- at = n;
- break;
- }
- //printf("%s no\n", qPrintable(str));
- }
- if(at == -1)
- {
- if(result)
- *result = ErrorInvalidCA;
- break;
- }
-
- // take it out of the pool
- Certificate next = pool.takeAt(at);
-
- // make sure it isn't in the chain already (avoid loops)
- if(out.contains(next))
- break;
-
- // append to the chain
- out += next;
- }
- return out;
+ CertificateChain out;
+ QList<Certificate> pool = issuers + chain.mid(1);
+ out += chain.first();
+ if (result) {
+ *result = ValidityGood;
+ }
+ while (!out.last().isSelfSigned()) {
+ // try to get next in chain
+ int at = -1;
+ for (int n = 0; n < pool.count(); ++n) {
+ //QString str = QString("[%1] issued by [%2] ? ").arg(out.last().commonName()).arg(pool[n].commonName());
+ if (pool[n].isIssuerOf(out.last())) {
+ //printf("%s yes\n", qPrintable(str));
+ at = n;
+ break;
+ }
+ //printf("%s no\n", qPrintable(str));
+ }
+ if (at == -1) {
+ if (result) {
+ *result = ErrorInvalidCA;
+ }
+ break;
+ }
+
+ // take it out of the pool
+ Certificate next = pool.takeAt(at);
+
+ // make sure it isn't in the chain already (avoid loops)
+ if (out.contains(next)) {
+ break;
+ }
+
+ // append to the chain
+ out += next;
+ }
+ return out;
}
//----------------------------------------------------------------------------
// CertificateRequest
//----------------------------------------------------------------------------
class CertificateRequest::Private : public QSharedData
{
public:
- CertificateInfo subjectInfoMap;
-
- void update(CSRContext *c)
- {
- if(c)
- subjectInfoMap = orderedToMap(c->props()->subject);
- else
- subjectInfoMap = CertificateInfo();
- }
+ CertificateInfo subjectInfoMap;
+
+ void update(CSRContext *c)
+ {
+ if (c) {
+ subjectInfoMap = orderedToMap(c->props()->subject);
+ } else {
+ subjectInfoMap = CertificateInfo();
+ }
+ }
};
CertificateRequest::CertificateRequest()
-:d(new Private)
+ : d(new Private)
{
}
CertificateRequest::CertificateRequest(const QString &fileName)
-:d(new Private)
+ : d(new Private)
{
- *this = fromPEMFile(fileName, 0, QString());
+ *this = fromPEMFile(fileName, 0, QString());
}
CertificateRequest::CertificateRequest(const CertificateOptions &opts, const PrivateKey &key, const QString &provider)
-:d(new Private)
+ : d(new Private)
{
- CSRContext *c = static_cast<CSRContext *>(getContext("csr", provider));
- if(c->createRequest(opts, *(static_cast<const PKeyContext *>(key.context()))))
- change(c);
- else
- delete c;
+ CSRContext *c = static_cast<CSRContext *>(getContext("csr", provider));
+ if (c->createRequest(opts, *(static_cast<const PKeyContext *>(key.context())))) {
+ change(c);
+ } else {
+ delete c;
+ }
}
CertificateRequest::CertificateRequest(const CertificateRequest &from)
-:Algorithm(from), d(from.d)
+ : Algorithm(from), d(from.d)
{
}
CertificateRequest::~CertificateRequest()
{
}
-CertificateRequest & CertificateRequest::operator=(const CertificateRequest &from)
+CertificateRequest &CertificateRequest::operator=(const CertificateRequest &from)
{
- Algorithm::operator=(from);
- d = from.d;
- return *this;
+ Algorithm::operator=(from);
+ d = from.d;
+ return *this;
}
bool CertificateRequest::isNull() const
{
- return (!context() ? true : false);
+ return (!context() ? true : false);
}
bool CertificateRequest::canUseFormat(CertificateRequestFormat f, const QString &provider)
{
- CSRContext *c = static_cast<CSRContext *>(getContext("csr", provider));
- bool ok = c->canUseFormat(f);
- delete c;
- return ok;
+ CSRContext *c = static_cast<CSRContext *>(getContext("csr", provider));
+ bool ok = c->canUseFormat(f);
+ delete c;
+ return ok;
}
CertificateRequestFormat CertificateRequest::format() const
{
- if(isNull())
- return PKCS10; // some default so we don't explode
- return static_cast<const CSRContext *>(context())->props()->format;
+ if (isNull()) {
+ return PKCS10; // some default so we don't explode
+ }
+ return static_cast<const CSRContext *>(context())->props()->format;
}
CertificateInfo CertificateRequest::subjectInfo() const
{
- return d->subjectInfoMap;
+ return d->subjectInfoMap;
}
CertificateInfoOrdered CertificateRequest::subjectInfoOrdered() const
{
- return static_cast<const CSRContext *>(context())->props()->subject;
+ return static_cast<const CSRContext *>(context())->props()->subject;
}
Constraints CertificateRequest::constraints() const
{
- return static_cast<const CSRContext *>(context())->props()->constraints;
+ return static_cast<const CSRContext *>(context())->props()->constraints;
}
QStringList CertificateRequest::policies() const
{
- return static_cast<const CSRContext *>(context())->props()->policies;
+ return static_cast<const CSRContext *>(context())->props()->policies;
}
PublicKey CertificateRequest::subjectPublicKey() const
{
- PKeyContext *c = static_cast<const CSRContext *>(context())->subjectPublicKey();
- PublicKey key;
- key.change(c);
- return key;
+ PKeyContext *c = static_cast<const CSRContext *>(context())->subjectPublicKey();
+ PublicKey key;
+ key.change(c);
+ return key;
}
bool CertificateRequest::isCA() const
{
- return static_cast<const CSRContext *>(context())->props()->isCA;
+ return static_cast<const CSRContext *>(context())->props()->isCA;
}
int CertificateRequest::pathLimit() const
{
- return static_cast<const CSRContext *>(context())->props()->pathLimit;
+ return static_cast<const CSRContext *>(context())->props()->pathLimit;
}
QString CertificateRequest::challenge() const
{
- return static_cast<const CSRContext *>(context())->props()->challenge;
+ return static_cast<const CSRContext *>(context())->props()->challenge;
}
SignatureAlgorithm CertificateRequest::signatureAlgorithm() const
{
- return static_cast<const CSRContext *>(context())->props()->sigalgo;
+ return static_cast<const CSRContext *>(context())->props()->sigalgo;
}
bool CertificateRequest::operator==(const CertificateRequest &otherCsr) const
{
- if(isNull())
- {
- if(otherCsr.isNull())
- return true;
- else
- return false;
- }
- else if(otherCsr.isNull())
- return false;
+ if (isNull()) {
+ if (otherCsr.isNull()) {
+ return true;
+ } else {
+ return false;
+ }
+ } else if (otherCsr.isNull()) {
+ return false;
+ }
- const CSRContext *other = static_cast<const CSRContext *>(otherCsr.context());
- return static_cast<const CSRContext *>(context())->compare(other);
+ const CSRContext *other = static_cast<const CSRContext *>(otherCsr.context());
+ return static_cast<const CSRContext *>(context())->compare(other);
}
QByteArray CertificateRequest::toDER() const
{
- return static_cast<const CSRContext *>(context())->toDER();
+ return static_cast<const CSRContext *>(context())->toDER();
}
QString CertificateRequest::toPEM() const
{
- return static_cast<const CSRContext *>(context())->toPEM();
+ return static_cast<const CSRContext *>(context())->toPEM();
}
bool CertificateRequest::toPEMFile(const QString &fileName) const
{
- return stringToFile(fileName, toPEM());
+ return stringToFile(fileName, toPEM());
}
CertificateRequest CertificateRequest::fromDER(const QByteArray &a, ConvertResult *result, const QString &provider)
{
- CertificateRequest c;
- CSRContext *csr = static_cast<CSRContext *>(getContext("csr", provider));
- ConvertResult r = csr->fromDER(a);
- if(result)
- *result = r;
- if(r == ConvertGood)
- c.change(csr);
- else
- delete csr;
- return c;
+ CertificateRequest c;
+ CSRContext *csr = static_cast<CSRContext *>(getContext("csr", provider));
+ ConvertResult r = csr->fromDER(a);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ c.change(csr);
+ } else {
+ delete csr;
+ }
+ return c;
}
CertificateRequest CertificateRequest::fromPEM(const QString &s, ConvertResult *result, const QString &provider)
{
- CertificateRequest c;
- CSRContext *csr = static_cast<CSRContext *>(getContext("csr", provider));
- ConvertResult r = csr->fromPEM(s);
- if(result)
- *result = r;
- if(r == ConvertGood)
- c.change(csr);
- else
- delete csr;
- return c;
+ CertificateRequest c;
+ CSRContext *csr = static_cast<CSRContext *>(getContext("csr", provider));
+ ConvertResult r = csr->fromPEM(s);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ c.change(csr);
+ } else {
+ delete csr;
+ }
+ return c;
}
CertificateRequest CertificateRequest::fromPEMFile(const QString &fileName, ConvertResult *result, const QString &provider)
{
- QString pem;
- if(!stringFromFile(fileName, &pem))
- {
- if(result)
- *result = ErrorFile;
- return CertificateRequest();
- }
- return fromPEM(pem, result, provider);
+ QString pem;
+ if (!stringFromFile(fileName, &pem)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return CertificateRequest();
+ }
+ return fromPEM(pem, result, provider);
}
QString CertificateRequest::toString() const
{
- return static_cast<const CSRContext *>(context())->toSPKAC();
+ return static_cast<const CSRContext *>(context())->toSPKAC();
}
CertificateRequest CertificateRequest::fromString(const QString &s, ConvertResult *result, const QString &provider)
{
- CertificateRequest c;
- CSRContext *csr = static_cast<CSRContext *>(getContext("csr", provider));
- ConvertResult r = csr->fromSPKAC(s);
- if(result)
- *result = r;
- if(r == ConvertGood)
- c.change(csr);
- else
- delete csr;
- return c;
+ CertificateRequest c;
+ CSRContext *csr = static_cast<CSRContext *>(getContext("csr", provider));
+ ConvertResult r = csr->fromSPKAC(s);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ c.change(csr);
+ } else {
+ delete csr;
+ }
+ return c;
}
void CertificateRequest::change(CSRContext *c)
{
- Algorithm::change(c);
- d->update(static_cast<CSRContext *>(context()));
+ Algorithm::change(c);
+ d->update(static_cast<CSRContext *>(context()));
}
//----------------------------------------------------------------------------
// CRLEntry
//----------------------------------------------------------------------------
CRLEntry::CRLEntry()
{
- _reason = Unspecified;
+ _reason = Unspecified;
}
CRLEntry::CRLEntry(const Certificate &c, Reason r)
{
- _serial = c.serialNumber();
- _time = QDateTime::currentDateTime();
- _reason = r;
+ _serial = c.serialNumber();
+ _time = QDateTime::currentDateTime();
+ _reason = r;
}
CRLEntry::CRLEntry(const BigInteger serial, const QDateTime &time, Reason r)
{
- _serial = serial;
- _time = time;
- _reason = r;
+ _serial = serial;
+ _time = time;
+ _reason = r;
}
CRLEntry::CRLEntry(const CRLEntry &from)
-:_serial(from._serial), _time(from._time), _reason(from._reason)
+ : _serial(from._serial), _time(from._time), _reason(from._reason)
{
}
CRLEntry::~CRLEntry()
{
}
-CRLEntry & CRLEntry::operator=(const CRLEntry &from)
+CRLEntry &CRLEntry::operator=(const CRLEntry &from)
{
- _serial = from._serial;
- _time = from._time;
- _reason = from._reason;
- return *this;
+ _serial = from._serial;
+ _time = from._time;
+ _reason = from._reason;
+ return *this;
}
bool CRLEntry::isNull() const
{
- return (_time.isNull());
+ return (_time.isNull());
}
BigInteger CRLEntry::serialNumber() const
{
- return _serial;
+ return _serial;
}
QDateTime CRLEntry::time() const
{
- return _time;
+ return _time;
}
CRLEntry::Reason CRLEntry::reason() const
{
- return _reason;
+ return _reason;
}
bool CRLEntry::operator==(const CRLEntry &otherEntry) const
{
- if(isNull())
- {
- if(otherEntry.isNull())
- return true;
- else
- return false;
- }
- else if(otherEntry.isNull())
- return false;
-
- if((_serial != otherEntry._serial) ||
- (_time != otherEntry._time) ||
- (_reason != otherEntry._reason))
- {
- return false;
- }
- return true;
+ if (isNull()) {
+ if (otherEntry.isNull()) {
+ return true;
+ } else {
+ return false;
+ }
+ } else if (otherEntry.isNull()) {
+ return false;
+ }
+
+ if ((_serial != otherEntry._serial) ||
+ (_time != otherEntry._time) ||
+ (_reason != otherEntry._reason)) {
+ return false;
+ }
+ return true;
}
bool CRLEntry::operator<(const CRLEntry &otherEntry) const
{
- if(isNull() || otherEntry.isNull())
- return false;
+ if (isNull() || otherEntry.isNull()) {
+ return false;
+ }
- if(_serial < otherEntry._serial)
- return true;
+ if (_serial < otherEntry._serial) {
+ return true;
+ }
- return false;
+ return false;
}
//----------------------------------------------------------------------------
// CRL
//----------------------------------------------------------------------------
class CRL::Private : public QSharedData
{
public:
- CertificateInfo issuerInfoMap;
-
- void update(CRLContext *c)
- {
- if(c)
- issuerInfoMap = orderedToMap(c->props()->issuer);
- else
- issuerInfoMap = CertificateInfo();
- }
+ CertificateInfo issuerInfoMap;
+
+ void update(CRLContext *c)
+ {
+ if (c) {
+ issuerInfoMap = orderedToMap(c->props()->issuer);
+ } else {
+ issuerInfoMap = CertificateInfo();
+ }
+ }
};
CRL::CRL()
-:d(new Private)
+ : d(new Private)
{
}
CRL::CRL(const CRL &from)
-:Algorithm(from), d(from.d)
+ : Algorithm(from), d(from.d)
{
}
CRL::~CRL()
{
}
-CRL & CRL::operator=(const CRL &from)
+CRL &CRL::operator=(const CRL &from)
{
- Algorithm::operator=(from);
- d = from.d;
- return *this;
+ Algorithm::operator=(from);
+ d = from.d;
+ return *this;
}
bool CRL::isNull() const
{
- return (!context() ? true : false);
+ return (!context() ? true : false);
}
CertificateInfo CRL::issuerInfo() const
{
- return d->issuerInfoMap;
+ return d->issuerInfoMap;
}
CertificateInfoOrdered CRL::issuerInfoOrdered() const
{
- return static_cast<const CRLContext *>(context())->props()->issuer;
+ return static_cast<const CRLContext *>(context())->props()->issuer;
}
int CRL::number() const
{
- return static_cast<const CRLContext *>(context())->props()->number;
+ return static_cast<const CRLContext *>(context())->props()->number;
}
QDateTime CRL::thisUpdate() const
{
- return static_cast<const CRLContext *>(context())->props()->thisUpdate;
+ return static_cast<const CRLContext *>(context())->props()->thisUpdate;
}
QDateTime CRL::nextUpdate() const
{
- return static_cast<const CRLContext *>(context())->props()->nextUpdate;
+ return static_cast<const CRLContext *>(context())->props()->nextUpdate;
}
QList<CRLEntry> CRL::revoked() const
{
- return static_cast<const CRLContext *>(context())->props()->revoked;
+ return static_cast<const CRLContext *>(context())->props()->revoked;
}
SignatureAlgorithm CRL::signatureAlgorithm() const
{
- return static_cast<const CRLContext *>(context())->props()->sigalgo;
+ return static_cast<const CRLContext *>(context())->props()->sigalgo;
}
QByteArray CRL::issuerKeyId() const
{
- return static_cast<const CRLContext *>(context())->props()->issuerId;
+ return static_cast<const CRLContext *>(context())->props()->issuerId;
}
QByteArray CRL::toDER() const
{
- return static_cast<const CRLContext *>(context())->toDER();
+ return static_cast<const CRLContext *>(context())->toDER();
}
QString CRL::toPEM() const
{
- return static_cast<const CRLContext *>(context())->toPEM();
+ return static_cast<const CRLContext *>(context())->toPEM();
}
bool CRL::operator==(const CRL &otherCrl) const
{
- if(isNull())
- {
- if(otherCrl.isNull())
- return true;
- else
- return false;
- }
- else if(otherCrl.isNull())
- return false;
+ if (isNull()) {
+ if (otherCrl.isNull()) {
+ return true;
+ } else {
+ return false;
+ }
+ } else if (otherCrl.isNull()) {
+ return false;
+ }
- const CRLContext *other = static_cast<const CRLContext *>(otherCrl.context());
- return static_cast<const CRLContext *>(context())->compare(other);
+ const CRLContext *other = static_cast<const CRLContext *>(otherCrl.context());
+ return static_cast<const CRLContext *>(context())->compare(other);
}
CRL CRL::fromDER(const QByteArray &a, ConvertResult *result, const QString &provider)
{
- CRL c;
- CRLContext *cc = static_cast<CRLContext *>(getContext("crl", provider));
- ConvertResult r = cc->fromDER(a);
- if(result)
- *result = r;
- if(r == ConvertGood)
- c.change(cc);
- else
- delete cc;
- return c;
+ CRL c;
+ CRLContext *cc = static_cast<CRLContext *>(getContext("crl", provider));
+ ConvertResult r = cc->fromDER(a);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ c.change(cc);
+ } else {
+ delete cc;
+ }
+ return c;
}
CRL CRL::fromPEM(const QString &s, ConvertResult *result, const QString &provider)
{
- CRL c;
- CRLContext *cc = static_cast<CRLContext *>(getContext("crl", provider));
- ConvertResult r = cc->fromPEM(s);
- if(result)
- *result = r;
- if(r == ConvertGood)
- c.change(cc);
- else
- delete cc;
- return c;
+ CRL c;
+ CRLContext *cc = static_cast<CRLContext *>(getContext("crl", provider));
+ ConvertResult r = cc->fromPEM(s);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ c.change(cc);
+ } else {
+ delete cc;
+ }
+ return c;
}
CRL CRL::fromPEMFile(const QString &fileName, ConvertResult *result, const QString &provider)
{
- QString pem;
- if(!stringFromFile(fileName, &pem))
- {
- if(result)
- *result = ErrorFile;
- return CRL();
- }
- return fromPEM(pem, result, provider);
+ QString pem;
+ if (!stringFromFile(fileName, &pem)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return CRL();
+ }
+ return fromPEM(pem, result, provider);
}
bool CRL::toPEMFile(const QString &fileName) const
{
- return stringToFile(fileName, toPEM());
+ return stringToFile(fileName, toPEM());
}
void CRL::change(CRLContext *c)
{
- Algorithm::change(c);
- d->update(static_cast<CRLContext *>(context()));
+ Algorithm::change(c);
+ d->update(static_cast<CRLContext *>(context()));
}
//----------------------------------------------------------------------------
// Store
//----------------------------------------------------------------------------
// CRL / X509 CRL
// CERTIFICATE / X509 CERTIFICATE
static QString readNextPem(QTextStream *ts, bool *isCRL)
{
- QString pem;
- bool crl = false;
- bool found = false;
- bool done = false;
- while(!ts->atEnd())
- {
- QString line = ts->readLine();
- if(!found)
- {
- if(line.startsWith("-----BEGIN "))
- {
- if(line.contains("CERTIFICATE"))
- {
- found = true;
- pem += line + '\n';
- crl = false;
- }
- else if(line.contains("CRL"))
- {
- found = true;
- pem += line + '\n';
- crl = true;
- }
- }
- }
- else
- {
- pem += line + '\n';
- if(line.startsWith("-----END "))
- {
- done = true;
- break;
- }
- }
- }
- if(!done)
- return QString();
- if(isCRL)
- *isCRL = crl;
- return pem;
+ QString pem;
+ bool crl = false;
+ bool found = false;
+ bool done = false;
+ while (!ts->atEnd()) {
+ QString line = ts->readLine();
+ if (!found) {
+ if (line.startsWith("-----BEGIN ")) {
+ if (line.contains("CERTIFICATE")) {
+ found = true;
+ pem += line + '\n';
+ crl = false;
+ } else if (line.contains("CRL")) {
+ found = true;
+ pem += line + '\n';
+ crl = true;
+ }
+ }
+ } else {
+ pem += line + '\n';
+ if (line.startsWith("-----END ")) {
+ done = true;
+ break;
+ }
+ }
+ }
+ if (!done) {
+ return QString();
+ }
+ if (isCRL) {
+ *isCRL = crl;
+ }
+ return pem;
}
class CertificateCollection::Private : public QSharedData
{
public:
- QList<Certificate> certs;
- QList<CRL> crls;
+ QList<Certificate> certs;
+ QList<CRL> crls;
};
CertificateCollection::CertificateCollection()
-:d(new Private)
+ : d(new Private)
{
}
CertificateCollection::CertificateCollection(const CertificateCollection &from)
-:d(from.d)
+ : d(from.d)
{
}
CertificateCollection::~CertificateCollection()
{
}
-CertificateCollection & CertificateCollection::operator=(const CertificateCollection &from)
+CertificateCollection &CertificateCollection::operator=(const CertificateCollection &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
void CertificateCollection::addCertificate(const Certificate &cert)
{
- d->certs.append(cert);
+ d->certs.append(cert);
}
void CertificateCollection::addCRL(const CRL &crl)
{
- d->crls.append(crl);
+ d->crls.append(crl);
}
QList<Certificate> CertificateCollection::certificates() const
{
- return d->certs;
+ return d->certs;
}
QList<CRL> CertificateCollection::crls() const
{
- return d->crls;
+ return d->crls;
}
void CertificateCollection::append(const CertificateCollection &other)
{
- d->certs += other.d->certs;
- d->crls += other.d->crls;
+ d->certs += other.d->certs;
+ d->crls += other.d->crls;
}
CertificateCollection CertificateCollection::operator+(const CertificateCollection &other) const
{
- CertificateCollection c = *this;
- c.append(other);
- return c;
+ CertificateCollection c = *this;
+ c.append(other);
+ return c;
}
-CertificateCollection & CertificateCollection::operator+=(const CertificateCollection &other)
+CertificateCollection &CertificateCollection::operator+=(const CertificateCollection &other)
{
- append(other);
- return *this;
+ append(other);
+ return *this;
}
bool CertificateCollection::canUsePKCS7(const QString &provider)
{
- return isSupported("certcollection", provider);
+ return isSupported("certcollection", provider);
}
bool CertificateCollection::toFlatTextFile(const QString &fileName)
{
- QFile f(fileName);
- if(!f.open(QFile::WriteOnly))
- return false;
+ QFile f(fileName);
+ if (!f.open(QFile::WriteOnly)) {
+ return false;
+ }
- QTextStream ts(&f);
- int n;
- for(n = 0; n < d->certs.count(); ++n)
- ts << d->certs[n].toPEM();
- for(n = 0; n < d->crls.count(); ++n)
- ts << d->crls[n].toPEM();
- return true;
+ QTextStream ts(&f);
+ int n;
+ for (n = 0; n < d->certs.count(); ++n) {
+ ts << d->certs[n].toPEM();
+ }
+ for (n = 0; n < d->crls.count(); ++n) {
+ ts << d->crls[n].toPEM();
+ }
+ return true;
}
bool CertificateCollection::toPKCS7File(const QString &fileName, const QString &provider)
{
- CertCollectionContext *col = static_cast<CertCollectionContext *>(getContext("certcollection", provider));
+ CertCollectionContext *col = static_cast<CertCollectionContext *>(getContext("certcollection", provider));
- QList<CertContext*> cert_list;
- QList<CRLContext*> crl_list;
- int n;
- for(n = 0; n < d->certs.count(); ++n)
- {
- CertContext *c = static_cast<CertContext *>(d->certs[n].context());
- cert_list += c;
- }
- for(n = 0; n < d->crls.count(); ++n)
- {
- CRLContext *c = static_cast<CRLContext *>(d->crls[n].context());
- crl_list += c;
- }
+ QList<CertContext *> cert_list;
+ QList<CRLContext *> crl_list;
+ int n;
+ for (n = 0; n < d->certs.count(); ++n) {
+ CertContext *c = static_cast<CertContext *>(d->certs[n].context());
+ cert_list += c;
+ }
+ for (n = 0; n < d->crls.count(); ++n) {
+ CRLContext *c = static_cast<CRLContext *>(d->crls[n].context());
+ crl_list += c;
+ }
- QByteArray result = col->toPKCS7(cert_list, crl_list);
- delete col;
+ QByteArray result = col->toPKCS7(cert_list, crl_list);
+ delete col;
- return arrayToFile(fileName, result);
+ return arrayToFile(fileName, result);
}
CertificateCollection CertificateCollection::fromFlatTextFile(const QString &fileName, ConvertResult *result, const QString &provider)
{
- QFile f(fileName);
- if(!f.open(QFile::ReadOnly))
- {
- if(result)
- *result = ErrorFile;
- return CertificateCollection();
- }
-
- CertificateCollection certs;
- QTextStream ts(&f);
- while(1)
- {
- bool isCRL = false;
- QString pem = readNextPem(&ts, &isCRL);
- if(pem.isNull())
- break;
- if(isCRL)
- {
- CRL c = CRL::fromPEM(pem, 0, provider);
- if(!c.isNull())
- certs.addCRL(c);
- }
- else
- {
- Certificate c = Certificate::fromPEM(pem, 0, provider);
- if(!c.isNull())
- certs.addCertificate(c);
- }
- }
-
- if(result)
- *result = ConvertGood;
-
- return certs;
+ QFile f(fileName);
+ if (!f.open(QFile::ReadOnly)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return CertificateCollection();
+ }
+
+ CertificateCollection certs;
+ QTextStream ts(&f);
+ while (1) {
+ bool isCRL = false;
+ QString pem = readNextPem(&ts, &isCRL);
+ if (pem.isNull()) {
+ break;
+ }
+ if (isCRL) {
+ CRL c = CRL::fromPEM(pem, 0, provider);
+ if (!c.isNull()) {
+ certs.addCRL(c);
+ }
+ } else {
+ Certificate c = Certificate::fromPEM(pem, 0, provider);
+ if (!c.isNull()) {
+ certs.addCertificate(c);
+ }
+ }
+ }
+
+ if (result) {
+ *result = ConvertGood;
+ }
+
+ return certs;
}
CertificateCollection CertificateCollection::fromPKCS7File(const QString &fileName, ConvertResult *result, const QString &provider)
{
- QByteArray der;
- if(!arrayFromFile(fileName, &der))
- {
- if(result)
- *result = ErrorFile;
- return CertificateCollection();
- }
-
- CertificateCollection certs;
-
- QList<CertContext*> cert_list;
- QList<CRLContext*> crl_list;
- CertCollectionContext *col = static_cast<CertCollectionContext *>(getContext("certcollection", provider));
- ConvertResult r = col->fromPKCS7(der, &cert_list, &crl_list);
- delete col;
-
- if(result)
- *result = r;
- if(r == ConvertGood)
- {
- int n;
- for(n = 0; n < cert_list.count(); ++n)
- {
- Certificate c;
- c.change(cert_list[n]);
- certs.addCertificate(c);
- }
- for(n = 0; n < crl_list.count(); ++n)
- {
- CRL c;
- c.change(crl_list[n]);
- certs.addCRL(c);
- }
- }
- return certs;
+ QByteArray der;
+ if (!arrayFromFile(fileName, &der)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return CertificateCollection();
+ }
+
+ CertificateCollection certs;
+
+ QList<CertContext *> cert_list;
+ QList<CRLContext *> crl_list;
+ CertCollectionContext *col = static_cast<CertCollectionContext *>(getContext("certcollection", provider));
+ ConvertResult r = col->fromPKCS7(der, &cert_list, &crl_list);
+ delete col;
+
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ int n;
+ for (n = 0; n < cert_list.count(); ++n) {
+ Certificate c;
+ c.change(cert_list[n]);
+ certs.addCertificate(c);
+ }
+ for (n = 0; n < crl_list.count(); ++n) {
+ CRL c;
+ c.change(crl_list[n]);
+ certs.addCRL(c);
+ }
+ }
+ return certs;
}
//----------------------------------------------------------------------------
// CertificateAuthority
//----------------------------------------------------------------------------
CertificateAuthority::CertificateAuthority(const Certificate &cert, const PrivateKey &key, const QString &provider)
-:Algorithm("ca", provider)
+ : Algorithm("ca", provider)
{
- static_cast<CAContext *>(context())->setup(*(static_cast<const CertContext *>(cert.context())), *(static_cast<const PKeyContext *>(key.context())));
+ static_cast<CAContext *>(context())->setup(*(static_cast<const CertContext *>(cert.context())), *(static_cast<const PKeyContext *>(key.context())));
}
CertificateAuthority::CertificateAuthority(const CertificateAuthority &from)
-:Algorithm(from)
+ : Algorithm(from)
{
}
CertificateAuthority::~CertificateAuthority()
{
}
-CertificateAuthority & CertificateAuthority::operator=(const CertificateAuthority &from)
+CertificateAuthority &CertificateAuthority::operator=(const CertificateAuthority &from)
{
- Algorithm::operator=(from);
- return *this;
+ Algorithm::operator=(from);
+ return *this;
}
Certificate CertificateAuthority::certificate() const
{
- Certificate c;
- c.change(static_cast<const CAContext *>(context())->certificate());
- return c;
+ Certificate c;
+ c.change(static_cast<const CAContext *>(context())->certificate());
+ return c;
}
Certificate CertificateAuthority::signRequest(const CertificateRequest &req, const QDateTime &notValidAfter) const
{
- Certificate c;
- CertContext *cc = static_cast<const CAContext *>(context())->signRequest(*(static_cast<const CSRContext *>(req.context())), notValidAfter);
- if(cc)
- c.change(cc);
- return c;
+ Certificate c;
+ CertContext *cc = static_cast<const CAContext *>(context())->signRequest(*(static_cast<const CSRContext *>(req.context())), notValidAfter);
+ if (cc) {
+ c.change(cc);
+ }
+ return c;
}
CRL CertificateAuthority::createCRL(const QDateTime &nextUpdate) const
{
- CRL crl;
- CRLContext *cc = static_cast<const CAContext *>(context())->createCRL(nextUpdate);
- if(cc)
- crl.change(cc);
- return crl;
+ CRL crl;
+ CRLContext *cc = static_cast<const CAContext *>(context())->createCRL(nextUpdate);
+ if (cc) {
+ crl.change(cc);
+ }
+ return crl;
}
CRL CertificateAuthority::updateCRL(const CRL &crl, const QList<CRLEntry> &entries, const QDateTime &nextUpdate) const
{
- CRL new_crl;
- CRLContext *cc = static_cast<const CAContext *>(context())->updateCRL(*(static_cast<const CRLContext *>(crl.context())), entries, nextUpdate);
- if(cc)
- new_crl.change(cc);
- return new_crl;
+ CRL new_crl;
+ CRLContext *cc = static_cast<const CAContext *>(context())->updateCRL(*(static_cast<const CRLContext *>(crl.context())), entries, nextUpdate);
+ if (cc) {
+ new_crl.change(cc);
+ }
+ return new_crl;
}
//----------------------------------------------------------------------------
// KeyBundle
//----------------------------------------------------------------------------
class KeyBundle::Private : public QSharedData
{
public:
- QString name;
- CertificateChain chain;
- PrivateKey key;
+ QString name;
+ CertificateChain chain;
+ PrivateKey key;
};
KeyBundle::KeyBundle()
-:d(new Private)
+ : d(new Private)
{
}
KeyBundle::KeyBundle(const QString &fileName, const SecureArray &passphrase)
-:d(new Private)
+ : d(new Private)
{
- *this = fromFile(fileName, passphrase, 0, QString());
+ *this = fromFile(fileName, passphrase, 0, QString());
}
KeyBundle::KeyBundle(const KeyBundle &from)
-:d(from.d)
+ : d(from.d)
{
}
KeyBundle::~KeyBundle()
{
}
-KeyBundle & KeyBundle::operator=(const KeyBundle &from)
+KeyBundle &KeyBundle::operator=(const KeyBundle &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
bool KeyBundle::isNull() const
{
- return d->chain.isEmpty();
+ return d->chain.isEmpty();
}
QString KeyBundle::name() const
{
- return d->name;
+ return d->name;
}
CertificateChain KeyBundle::certificateChain() const
{
- return d->chain;
+ return d->chain;
}
PrivateKey KeyBundle::privateKey() const
{
- return d->key;
+ return d->key;
}
void KeyBundle::setName(const QString &s)
{
- d->name = s;
+ d->name = s;
}
void KeyBundle::setCertificateChainAndKey(const CertificateChain &c, const PrivateKey &key)
{
- d->chain = c;
- d->key = key;
+ d->chain = c;
+ d->key = key;
}
QByteArray KeyBundle::toArray(const SecureArray &passphrase, const QString &provider) const
{
- PKCS12Context *pix = static_cast<PKCS12Context *>(getContext("pkcs12", provider));
+ PKCS12Context *pix = static_cast<PKCS12Context *>(getContext("pkcs12", provider));
- QList<const CertContext*> list;
- for(int n = 0; n < d->chain.count(); ++n)
- list.append(static_cast<const CertContext *>(d->chain[n].context()));
- QByteArray buf = pix->toPKCS12(d->name, list, *(static_cast<const PKeyContext *>(d->key.context())), passphrase);
- delete pix;
+ QList<const CertContext *> list;
+ for (int n = 0; n < d->chain.count(); ++n) {
+ list.append(static_cast<const CertContext *>(d->chain[n].context()));
+ }
+ QByteArray buf = pix->toPKCS12(d->name, list, *(static_cast<const PKeyContext *>(d->key.context())), passphrase);
+ delete pix;
- return buf;
+ return buf;
}
bool KeyBundle::toFile(const QString &fileName, const SecureArray &passphrase, const QString &provider) const
{
- return arrayToFile(fileName, toArray(passphrase, provider));
+ return arrayToFile(fileName, toArray(passphrase, provider));
}
KeyBundle KeyBundle::fromArray(const QByteArray &a, const SecureArray &passphrase, ConvertResult *result, const QString &provider)
{
- KeyBundle bundle;
- get_pkcs12_der(a, QString(), (void *)&a, passphrase, result, provider, &bundle.d->name, &bundle.d->chain, &bundle.d->key);
- return bundle;
+ KeyBundle bundle;
+ get_pkcs12_der(a, QString(), (void *)&a, passphrase, result, provider, &bundle.d->name, &bundle.d->chain, &bundle.d->key);
+ return bundle;
}
KeyBundle KeyBundle::fromFile(const QString &fileName, const SecureArray &passphrase, ConvertResult *result, const QString &provider)
{
- QByteArray der;
- if(!arrayFromFile(fileName, &der))
- {
- if(result)
- *result = ErrorFile;
- return KeyBundle();
- }
+ QByteArray der;
+ if (!arrayFromFile(fileName, &der)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return KeyBundle();
+ }
- KeyBundle bundle;
- get_pkcs12_der(der, fileName, 0, passphrase, result, provider, &bundle.d->name, &bundle.d->chain, &bundle.d->key);
- return bundle;
+ KeyBundle bundle;
+ get_pkcs12_der(der, fileName, 0, passphrase, result, provider, &bundle.d->name, &bundle.d->chain, &bundle.d->key);
+ return bundle;
}
//----------------------------------------------------------------------------
// PGPKey
//----------------------------------------------------------------------------
PGPKey::PGPKey()
{
}
PGPKey::PGPKey(const QString &fileName)
{
- *this = fromFile(fileName, 0, QString());
+ *this = fromFile(fileName, 0, QString());
}
PGPKey::PGPKey(const PGPKey &from)
-:Algorithm(from)
+ : Algorithm(from)
{
}
PGPKey::~PGPKey()
{
}
-PGPKey & PGPKey::operator=(const PGPKey &from)
+PGPKey &PGPKey::operator=(const PGPKey &from)
{
- Algorithm::operator=(from);
- return *this;
+ Algorithm::operator=(from);
+ return *this;
}
bool PGPKey::isNull() const
{
- return (!context() ? true : false);
+ return (!context() ? true : false);
}
QString PGPKey::keyId() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->keyId;
+ return static_cast<const PGPKeyContext *>(context())->props()->keyId;
}
QString PGPKey::primaryUserId() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->userIds.first();
+ return static_cast<const PGPKeyContext *>(context())->props()->userIds.first();
}
QStringList PGPKey::userIds() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->userIds;
+ return static_cast<const PGPKeyContext *>(context())->props()->userIds;
}
bool PGPKey::isSecret() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->isSecret;
+ return static_cast<const PGPKeyContext *>(context())->props()->isSecret;
}
QDateTime PGPKey::creationDate() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->creationDate;
+ return static_cast<const PGPKeyContext *>(context())->props()->creationDate;
}
QDateTime PGPKey::expirationDate() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->expirationDate;
+ return static_cast<const PGPKeyContext *>(context())->props()->expirationDate;
}
QString PGPKey::fingerprint() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->fingerprint;
+ return static_cast<const PGPKeyContext *>(context())->props()->fingerprint;
}
bool PGPKey::inKeyring() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->inKeyring;
+ return static_cast<const PGPKeyContext *>(context())->props()->inKeyring;
}
bool PGPKey::isTrusted() const
{
- return static_cast<const PGPKeyContext *>(context())->props()->isTrusted;
+ return static_cast<const PGPKeyContext *>(context())->props()->isTrusted;
}
QByteArray PGPKey::toArray() const
{
- return static_cast<const PGPKeyContext *>(context())->toBinary();
+ return static_cast<const PGPKeyContext *>(context())->toBinary();
}
QString PGPKey::toString() const
{
- return static_cast<const PGPKeyContext *>(context())->toAscii();
+ return static_cast<const PGPKeyContext *>(context())->toAscii();
}
bool PGPKey::toFile(const QString &fileName) const
{
- return stringToFile(fileName, toString());
+ return stringToFile(fileName, toString());
}
PGPKey PGPKey::fromArray(const QByteArray &a, ConvertResult *result, const QString &provider)
{
- PGPKey k;
- PGPKeyContext *kc = static_cast<PGPKeyContext *>(getContext("pgpkey", provider));
- ConvertResult r = kc->fromBinary(a);
- if(result)
- *result = r;
- if(r == ConvertGood)
- k.change(kc);
- else
- delete kc;
- return k;
+ PGPKey k;
+ PGPKeyContext *kc = static_cast<PGPKeyContext *>(getContext("pgpkey", provider));
+ ConvertResult r = kc->fromBinary(a);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ k.change(kc);
+ } else {
+ delete kc;
+ }
+ return k;
}
PGPKey PGPKey::fromString(const QString &s, ConvertResult *result, const QString &provider)
{
- PGPKey k;
- PGPKeyContext *kc = static_cast<PGPKeyContext *>(getContext("pgpkey", provider));
- ConvertResult r = kc->fromAscii(s);
- if(result)
- *result = r;
- if(r == ConvertGood)
- k.change(kc);
- else
- delete kc;
- return k;
+ PGPKey k;
+ PGPKeyContext *kc = static_cast<PGPKeyContext *>(getContext("pgpkey", provider));
+ ConvertResult r = kc->fromAscii(s);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ k.change(kc);
+ } else {
+ delete kc;
+ }
+ return k;
}
PGPKey PGPKey::fromFile(const QString &fileName, ConvertResult *result, const QString &provider)
{
- QString str;
- if(!stringFromFile(fileName, &str))
- {
- if(result)
- *result = ErrorFile;
- return PGPKey();
- }
- return fromString(str, result, provider);
+ QString str;
+ if (!stringFromFile(fileName, &str)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return PGPKey();
+ }
+ return fromString(str, result, provider);
}
//----------------------------------------------------------------------------
// KeyLoader
//----------------------------------------------------------------------------
class KeyLoaderThread : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum Type { PKPEMFile, PKPEM, PKDER, KBDERFile, KBDER };
-
- class In
- {
- public:
- Type type;
- QString fileName, pem;
- SecureArray der;
- QByteArray kbder;
- };
-
- class Out
- {
- public:
- ConvertResult convertResult;
- PrivateKey privateKey;
- KeyBundle keyBundle;
- };
-
- In in;
- Out out;
-
- KeyLoaderThread(QObject *parent = 0) : QThread(parent)
- {
- }
+ enum Type { PKPEMFile, PKPEM, PKDER, KBDERFile, KBDER };
+
+ class In
+ {
+ public:
+ Type type;
+ QString fileName, pem;
+ SecureArray der;
+ QByteArray kbder;
+ };
+
+ class Out
+ {
+ public:
+ ConvertResult convertResult;
+ PrivateKey privateKey;
+ KeyBundle keyBundle;
+ };
+
+ In in;
+ Out out;
+
+ KeyLoaderThread(QObject *parent = 0) : QThread(parent)
+ {
+ }
protected:
- virtual void run()
- {
- if(in.type == PKPEMFile)
- out.privateKey = PrivateKey::fromPEMFile(in.fileName, SecureArray(), &out.convertResult);
- else if(in.type == PKPEM)
- out.privateKey = PrivateKey::fromPEM(in.pem, SecureArray(), &out.convertResult);
- else if(in.type == PKDER)
- out.privateKey = PrivateKey::fromDER(in.der, SecureArray(), &out.convertResult);
- else if(in.type == KBDERFile)
- out.keyBundle = KeyBundle::fromFile(in.fileName, SecureArray(), &out.convertResult);
- else if(in.type == KBDER)
- out.keyBundle = KeyBundle::fromArray(in.kbder, SecureArray(), &out.convertResult);
- }
+ virtual void run()
+ {
+ if (in.type == PKPEMFile) {
+ out.privateKey = PrivateKey::fromPEMFile(in.fileName, SecureArray(), &out.convertResult);
+ } else if (in.type == PKPEM) {
+ out.privateKey = PrivateKey::fromPEM(in.pem, SecureArray(), &out.convertResult);
+ } else if (in.type == PKDER) {
+ out.privateKey = PrivateKey::fromDER(in.der, SecureArray(), &out.convertResult);
+ } else if (in.type == KBDERFile) {
+ out.keyBundle = KeyBundle::fromFile(in.fileName, SecureArray(), &out.convertResult);
+ } else if (in.type == KBDER) {
+ out.keyBundle = KeyBundle::fromArray(in.kbder, SecureArray(), &out.convertResult);
+ }
+ }
};
class KeyLoader::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeyLoader *q;
-
- bool active;
- KeyLoaderThread *thread;
- KeyLoaderThread::In in;
- KeyLoaderThread::Out out;
-
- Private(KeyLoader *_q) : QObject(_q), q(_q)
- {
- active = false;
- }
-
- void reset()
- {
- in = KeyLoaderThread::In();
- out = KeyLoaderThread::Out();
- }
-
- void start()
- {
- active = true;
- thread = new KeyLoaderThread(this);
- // used queued for signal-safety
- connect(thread, SIGNAL(finished()), SLOT(thread_finished()), Qt::QueuedConnection);
- thread->in = in;
- thread->start();
- }
+ KeyLoader *q;
+
+ bool active;
+ KeyLoaderThread *thread;
+ KeyLoaderThread::In in;
+ KeyLoaderThread::Out out;
+
+ Private(KeyLoader *_q) : QObject(_q), q(_q)
+ {
+ active = false;
+ }
+
+ void reset()
+ {
+ in = KeyLoaderThread::In();
+ out = KeyLoaderThread::Out();
+ }
+
+ void start()
+ {
+ active = true;
+ thread = new KeyLoaderThread(this);
+ // used queued for signal-safety
+ connect(thread, SIGNAL(finished()), SLOT(thread_finished()), Qt::QueuedConnection);
+ thread->in = in;
+ thread->start();
+ }
private slots:
- void thread_finished()
- {
- out = thread->out;
- delete thread;
- thread = 0;
- active = false;
-
- emit q->finished();
- }
+ void thread_finished()
+ {
+ out = thread->out;
+ delete thread;
+ thread = 0;
+ active = false;
+
+ emit q->finished();
+ }
};
KeyLoader::KeyLoader(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
KeyLoader::~KeyLoader()
{
- delete d;
+ delete d;
}
void KeyLoader::loadPrivateKeyFromPEMFile(const QString &fileName)
{
- Q_ASSERT(!d->active);
- if(d->active)
- return;
+ Q_ASSERT(!d->active);
+ if (d->active) {
+ return;
+ }
- d->reset();
- d->in.type = KeyLoaderThread::PKPEMFile;
- d->in.fileName = fileName;
- d->start();
+ d->reset();
+ d->in.type = KeyLoaderThread::PKPEMFile;
+ d->in.fileName = fileName;
+ d->start();
}
void KeyLoader::loadPrivateKeyFromPEM(const QString &s)
{
- Q_ASSERT(!d->active);
- if(d->active)
- return;
+ Q_ASSERT(!d->active);
+ if (d->active) {
+ return;
+ }
- d->reset();
- d->in.type = KeyLoaderThread::PKPEM;
- d->in.pem = s;
- d->start();
+ d->reset();
+ d->in.type = KeyLoaderThread::PKPEM;
+ d->in.pem = s;
+ d->start();
}
void KeyLoader::loadPrivateKeyFromDER(const SecureArray &a)
{
- Q_ASSERT(!d->active);
- if(d->active)
- return;
+ Q_ASSERT(!d->active);
+ if (d->active) {
+ return;
+ }
- d->reset();
- d->in.type = KeyLoaderThread::PKDER;
- d->in.der = a;
- d->start();
+ d->reset();
+ d->in.type = KeyLoaderThread::PKDER;
+ d->in.der = a;
+ d->start();
}
void KeyLoader::loadKeyBundleFromFile(const QString &fileName)
{
- Q_ASSERT(!d->active);
- if(d->active)
- return;
+ Q_ASSERT(!d->active);
+ if (d->active) {
+ return;
+ }
- d->reset();
- d->in.type = KeyLoaderThread::KBDERFile;
- d->in.fileName = fileName;
- d->start();
+ d->reset();
+ d->in.type = KeyLoaderThread::KBDERFile;
+ d->in.fileName = fileName;
+ d->start();
}
void KeyLoader::loadKeyBundleFromArray(const QByteArray &a)
{
- Q_ASSERT(!d->active);
- if(d->active)
- return;
+ Q_ASSERT(!d->active);
+ if (d->active) {
+ return;
+ }
- d->reset();
- d->in.type = KeyLoaderThread::KBDERFile;
- d->in.kbder = a;
- d->start();
+ d->reset();
+ d->in.type = KeyLoaderThread::KBDERFile;
+ d->in.kbder = a;
+ d->start();
}
ConvertResult KeyLoader::convertResult() const
{
- return d->out.convertResult;
+ return d->out.convertResult;
}
PrivateKey KeyLoader::privateKey() const
{
- return d->out.privateKey;
+ return d->out.privateKey;
}
KeyBundle KeyLoader::keyBundle() const
{
- return d->out.keyBundle;
+ return d->out.keyBundle;
}
}
#include "qca_cert.moc"
diff --git a/src/qca_core.cpp b/src/qca_core.cpp
index dfb93b74..662fb9a8 100644
--- a/src/qca_core.cpp
+++ b/src/qca_core.cpp
@@ -1,2234 +1,2293 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
* Copyright (C) 2004,2005 Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2014-2016 Ivan Romanov <drizt@land.ru>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_core.h"
#include "qca_plugin.h"
#include "qca_textfilter.h"
#include "qca_cert.h"
#include "qca_keystore.h"
#include "qcaprovider.h"
// for qAddPostRoutine
#include <QCoreApplication>
#include <QMutex>
#include <QSettings>
#include <QVariantMap>
#include <QWaitCondition>
#include <QDir>
#ifdef Q_OS_UNIX
# include <unistd.h>
#endif
int qcaVersion()
{
- return QCA_VERSION;
+ return QCA_VERSION;
}
const char *qcaVersionStr()
{
- return QCA_VERSION_STR;
+ return QCA_VERSION_STR;
}
int qcaMajorVersion()
{
- return QCA_MAJOR_VERSION;
+ return QCA_MAJOR_VERSION;
}
int qcaMinorVersion()
{
- return QCA_MINOR_VERSION;
+ return QCA_MINOR_VERSION;
}
int qcaPatchVersion()
{
- return QCA_PATCH_VERSION;
+ return QCA_PATCH_VERSION;
}
-namespace QCA {
+namespace QCA
+{
// from qca_tools
bool botan_init(int prealloc, bool mmap);
void botan_deinit();
// from qca_default
Provider *create_default_provider();
//----------------------------------------------------------------------------
// Global
//----------------------------------------------------------------------------
class Global
{
public:
- int refs;
- bool secmem;
- bool loaded;
- bool first_scan;
- QString app_name;
- QMutex name_mutex;
- ProviderManager *manager;
- QMutex scan_mutex;
- Random *rng;
- QMutex rng_mutex;
- Logger *logger;
- QVariantMap properties;
- QMutex prop_mutex;
- QMap<QString,QVariantMap> config;
- QMutex config_mutex;
- QMutex logger_mutex;
-
- Global()
- {
- refs = 0;
- secmem = false;
- loaded = false;
- first_scan = false;
- rng = 0;
- logger = 0;
- manager = new ProviderManager;
- }
-
- ~Global()
- {
- KeyStoreManager::shutdown();
- delete rng;
- rng = 0;
- delete manager;
- manager = 0;
- delete logger;
- logger = 0;
- }
-
- void ensure_loaded()
- {
- // probably we shouldn't overload scan mutex, or else rename it
- QMutexLocker locker(&scan_mutex);
- if(!loaded)
- {
- loaded = true;
- manager->setDefault(create_default_provider()); // manager owns it
- }
- }
-
- bool ensure_first_scan()
- {
- scan_mutex.lock();
- if(!first_scan)
- {
- first_scan = true;
- manager->scan();
- scan_mutex.unlock();
- return true;
- }
- scan_mutex.unlock();
- return false;
- }
-
- void scan()
- {
- scan_mutex.lock();
- first_scan = true;
- manager->scan();
- scan_mutex.unlock();
- }
-
- void ksm_scan()
- {
- KeyStoreManager::scan();
- }
-
- Logger *get_logger()
- {
- QMutexLocker locker(&logger_mutex);
- if(!logger)
- {
- logger = new Logger;
-
- // needed so deinit may delete the logger regardless
- // of what thread the logger was created from
- logger->moveToThread(0);
- }
- return logger;
- }
-
- void unloadAllPlugins()
- {
- KeyStoreManager::shutdown();
-
- // if the global_rng was owned by a plugin, then delete it
- rng_mutex.lock();
- if(rng && (rng->provider() != manager->find("default")))
- {
- delete rng;
- rng = 0;
- }
- rng_mutex.unlock();
-
- manager->unloadAll();
- }
+ int refs;
+ bool secmem;
+ bool loaded;
+ bool first_scan;
+ QString app_name;
+ QMutex name_mutex;
+ ProviderManager *manager;
+ QMutex scan_mutex;
+ Random *rng;
+ QMutex rng_mutex;
+ Logger *logger;
+ QVariantMap properties;
+ QMutex prop_mutex;
+ QMap<QString, QVariantMap> config;
+ QMutex config_mutex;
+ QMutex logger_mutex;
+
+ Global()
+ {
+ refs = 0;
+ secmem = false;
+ loaded = false;
+ first_scan = false;
+ rng = 0;
+ logger = 0;
+ manager = new ProviderManager;
+ }
+
+ ~Global()
+ {
+ KeyStoreManager::shutdown();
+ delete rng;
+ rng = 0;
+ delete manager;
+ manager = 0;
+ delete logger;
+ logger = 0;
+ }
+
+ void ensure_loaded()
+ {
+ // probably we shouldn't overload scan mutex, or else rename it
+ QMutexLocker locker(&scan_mutex);
+ if (!loaded) {
+ loaded = true;
+ manager->setDefault(create_default_provider()); // manager owns it
+ }
+ }
+
+ bool ensure_first_scan()
+ {
+ scan_mutex.lock();
+ if (!first_scan) {
+ first_scan = true;
+ manager->scan();
+ scan_mutex.unlock();
+ return true;
+ }
+ scan_mutex.unlock();
+ return false;
+ }
+
+ void scan()
+ {
+ scan_mutex.lock();
+ first_scan = true;
+ manager->scan();
+ scan_mutex.unlock();
+ }
+
+ void ksm_scan()
+ {
+ KeyStoreManager::scan();
+ }
+
+ Logger *get_logger()
+ {
+ QMutexLocker locker(&logger_mutex);
+ if (!logger) {
+ logger = new Logger;
+
+ // needed so deinit may delete the logger regardless
+ // of what thread the logger was created from
+ logger->moveToThread(0);
+ }
+ return logger;
+ }
+
+ void unloadAllPlugins()
+ {
+ KeyStoreManager::shutdown();
+
+ // if the global_rng was owned by a plugin, then delete it
+ rng_mutex.lock();
+ if (rng && (rng->provider() != manager->find("default"))) {
+ delete rng;
+ rng = 0;
+ }
+ rng_mutex.unlock();
+
+ manager->unloadAll();
+ }
};
Q_GLOBAL_STATIC(QMutex, global_mutex)
static Global *global = 0;
static bool features_have(const QStringList &have, const QStringList &want)
{
- foreach(const QString &i, want)
- {
- if(!have.contains(i))
- return false;
- }
- return true;
+ foreach (const QString &i, want) {
+ if (!have.contains(i)) {
+ return false;
+ }
+ }
+ return true;
}
void init(MemoryMode mode, int prealloc)
{
- QMutexLocker locker(global_mutex());
- if(global)
- {
- ++(global->refs);
- return;
- }
-
- bool allow_mmap_fallback = false;
- bool drop_root = false;
- if(mode == Practical)
- {
- allow_mmap_fallback = true;
- drop_root = true;
- }
- else if(mode == Locking)
- drop_root = true;
-
- bool secmem = botan_init(prealloc, allow_mmap_fallback);
-
- if(drop_root)
- {
+ QMutexLocker locker(global_mutex());
+ if (global) {
+ ++(global->refs);
+ return;
+ }
+
+ bool allow_mmap_fallback = false;
+ bool drop_root = false;
+ if (mode == Practical) {
+ allow_mmap_fallback = true;
+ drop_root = true;
+ } else if (mode == Locking) {
+ drop_root = true;
+ }
+
+ bool secmem = botan_init(prealloc, allow_mmap_fallback);
+
+ if (drop_root) {
#ifdef Q_OS_UNIX
- setuid(getuid());
+ setuid(getuid());
#endif
- }
-
- global = new Global;
- global->secmem = secmem;
- ++(global->refs);
-
- // for maximum setuid safety, qca should be initialized before qapp:
- //
- // int main(int argc, char **argv)
- // {
- // QCA::Initializer init;
- // QCoreApplication app(argc, argv);
- // return 0;
- // }
- //
- // however, the above code has the unfortunate side-effect of causing
- // qapp to deinit before qca, which can cause problems with any
- // plugins that have active objects (notably KeyStore). we'll use a
- // post routine to force qca to deinit first.
- qAddPostRoutine(deinit);
+ }
+
+ global = new Global;
+ global->secmem = secmem;
+ ++(global->refs);
+
+ // for maximum setuid safety, qca should be initialized before qapp:
+ //
+ // int main(int argc, char **argv)
+ // {
+ // QCA::Initializer init;
+ // QCoreApplication app(argc, argv);
+ // return 0;
+ // }
+ //
+ // however, the above code has the unfortunate side-effect of causing
+ // qapp to deinit before qca, which can cause problems with any
+ // plugins that have active objects (notably KeyStore). we'll use a
+ // post routine to force qca to deinit first.
+ qAddPostRoutine(deinit);
}
void init()
{
- init(Practical, 64);
+ init(Practical, 64);
}
void deinit()
{
- QMutexLocker locker(global_mutex());
- if(!global)
- return;
- --(global->refs);
- if(global->refs == 0)
- {
- // In order to maintain symmetry with the init() function, remove the
- // post routine from QCoreApplication. This is needed in case when the
- // QCA library is unloaded before QCoreApplication instance completes:
- // QCoreApplication d-tor would try to execute the deinit() function,
- // which would no longer be there.
- // Note that this function is documented only in Qt 5.3 and later, but
- // it has been present since ancient times with the same semantics.
- qRemovePostRoutine(deinit);
-
- delete global;
- global = 0;
- botan_deinit();
- }
+ QMutexLocker locker(global_mutex());
+ if (!global) {
+ return;
+ }
+ --(global->refs);
+ if (global->refs == 0) {
+ // In order to maintain symmetry with the init() function, remove the
+ // post routine from QCoreApplication. This is needed in case when the
+ // QCA library is unloaded before QCoreApplication instance completes:
+ // QCoreApplication d-tor would try to execute the deinit() function,
+ // which would no longer be there.
+ // Note that this function is documented only in Qt 5.3 and later, but
+ // it has been present since ancient times with the same semantics.
+ qRemovePostRoutine(deinit);
+
+ delete global;
+ global = 0;
+ botan_deinit();
+ }
}
static bool global_check()
{
- Q_ASSERT(global);
- if(!global)
- return false;
- return true;
+ Q_ASSERT(global);
+ if (!global) {
+ return false;
+ }
+ return true;
}
static bool global_check_load()
{
- Q_ASSERT(global);
- if(!global)
- return false;
- global->ensure_loaded();
- return true;
+ Q_ASSERT(global);
+ if (!global) {
+ return false;
+ }
+ global->ensure_loaded();
+ return true;
}
QMutex *global_random_mutex()
{
- return &global->rng_mutex;
+ return &global->rng_mutex;
}
Random *global_random()
{
- if(!global->rng)
- global->rng = new Random;
- return global->rng;
+ if (!global->rng) {
+ global->rng = new Random;
+ }
+ return global->rng;
}
bool haveSecureMemory()
{
- if(!global_check())
- return false;
+ if (!global_check()) {
+ return false;
+ }
- return global->secmem;
+ return global->secmem;
}
bool haveSecureRandom()
{
- if(!global_check_load())
- return false;
+ if (!global_check_load()) {
+ return false;
+ }
- QMutexLocker locker(global_random_mutex());
- if(global_random()->provider()->name() != "default")
- return true;
+ QMutexLocker locker(global_random_mutex());
+ if (global_random()->provider()->name() != "default") {
+ return true;
+ }
- return false;
+ return false;
}
bool isSupported(const QStringList &features, const QString &provider)
{
- if(!global_check_load())
- return false;
-
- // single
- if(!provider.isEmpty())
- {
- Provider *p = global->manager->find(provider);
- if(!p)
- {
- // ok, try scanning for new stuff
- global->scan();
- p = global->manager->find(provider);
- }
-
- if(p && features_have(p->features(), features))
- return true;
- }
- // all
- else
- {
- if(features_have(global->manager->allFeatures(), features))
- return true;
-
- global->manager->appendDiagnosticText(QString("Scanning to find features: %1\n").arg(features.join(" ")));
-
- // ok, try scanning for new stuff
- global->scan();
-
- if(features_have(global->manager->allFeatures(), features))
- return true;
- }
- return false;
+ if (!global_check_load()) {
+ return false;
+ }
+
+ // single
+ if (!provider.isEmpty()) {
+ Provider *p = global->manager->find(provider);
+ if (!p) {
+ // ok, try scanning for new stuff
+ global->scan();
+ p = global->manager->find(provider);
+ }
+
+ if (p && features_have(p->features(), features)) {
+ return true;
+ }
+ }
+ // all
+ else {
+ if (features_have(global->manager->allFeatures(), features)) {
+ return true;
+ }
+
+ global->manager->appendDiagnosticText(QString("Scanning to find features: %1\n").arg(features.join(" ")));
+
+ // ok, try scanning for new stuff
+ global->scan();
+
+ if (features_have(global->manager->allFeatures(), features)) {
+ return true;
+ }
+ }
+ return false;
}
bool isSupported(const char *features, const QString &provider)
{
- return isSupported(QString(features).split(',', QString::SkipEmptyParts), provider);
+ return isSupported(QString(features).split(',', QString::SkipEmptyParts), provider);
}
QStringList supportedFeatures()
{
- if(!global_check_load())
- return QStringList();
+ if (!global_check_load()) {
+ return QStringList();
+ }
- // query all features
- global->scan();
- return global->manager->allFeatures();
+ // query all features
+ global->scan();
+ return global->manager->allFeatures();
}
QStringList defaultFeatures()
{
- if(!global_check_load())
- return QStringList();
+ if (!global_check_load()) {
+ return QStringList();
+ }
- return global->manager->find("default")->features();
+ return global->manager->find("default")->features();
}
ProviderList providers()
{
- if(!global_check_load())
- return ProviderList();
+ if (!global_check_load()) {
+ return ProviderList();
+ }
- global->ensure_first_scan();
+ global->ensure_first_scan();
- return global->manager->providers();
+ return global->manager->providers();
}
bool insertProvider(Provider *p, int priority)
{
- if(!global_check_load())
- return false;
+ if (!global_check_load()) {
+ return false;
+ }
- global->ensure_first_scan();
+ global->ensure_first_scan();
- return global->manager->add(p, priority);
+ return global->manager->add(p, priority);
}
bool unloadProvider(const QString &name)
{
- if(!global_check_load())
- return false;
+ if (!global_check_load()) {
+ return false;
+ }
- global->ensure_first_scan();
+ global->ensure_first_scan();
- return global->manager->unload(name);
+ return global->manager->unload(name);
}
void setProviderPriority(const QString &name, int priority)
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- global->ensure_first_scan();
+ global->ensure_first_scan();
- global->manager->changePriority(name, priority);
+ global->manager->changePriority(name, priority);
}
int providerPriority(const QString &name)
{
- if(!global_check_load())
- return -1;
+ if (!global_check_load()) {
+ return -1;
+ }
- global->ensure_first_scan();
+ global->ensure_first_scan();
- return global->manager->getPriority(name);
+ return global->manager->getPriority(name);
}
Provider *findProvider(const QString &name)
{
- if(!global_check_load())
- return 0;
+ if (!global_check_load()) {
+ return 0;
+ }
- global->ensure_first_scan();
+ global->ensure_first_scan();
- return global->manager->find(name);
+ return global->manager->find(name);
}
Provider *defaultProvider()
{
- if(!global_check_load())
- return 0;
+ if (!global_check_load()) {
+ return 0;
+ }
- return global->manager->find("default");
+ return global->manager->find("default");
}
QStringList pluginPaths()
{
- QStringList paths;
+ QStringList paths;
#ifndef DEVELOPER_MODE
- const QString qcaPluginPath = qgetenv("QCA_PLUGIN_PATH");
- if (!qcaPluginPath.isEmpty())
- {
+ const QString qcaPluginPath = qgetenv("QCA_PLUGIN_PATH");
+ if (!qcaPluginPath.isEmpty()) {
#ifdef Q_OS_WIN
- QLatin1Char pathSep(';');
+ QLatin1Char pathSep(';');
#else
- QLatin1Char pathSep(':');
+ QLatin1Char pathSep(':');
#endif
- foreach (const QString &path, qcaPluginPath.split(pathSep))
- {
- QString canonicalPath = QDir(path).canonicalPath();
- if (!canonicalPath.isEmpty())
- paths << canonicalPath;
- }
-
- }
- paths += QCoreApplication::libraryPaths();
+ foreach (const QString &path, qcaPluginPath.split(pathSep)) {
+ QString canonicalPath = QDir(path).canonicalPath();
+ if (!canonicalPath.isEmpty()) {
+ paths << canonicalPath;
+ }
+ }
+
+ }
+ paths += QCoreApplication::libraryPaths();
#endif
- // In developer mode load plugins only from buildtree.
- // In regular mode QCA_PLUGIN_PATH is path where plugins was installed
- paths << QDir(QCA_PLUGIN_PATH).canonicalPath();
+ // In developer mode load plugins only from buildtree.
+ // In regular mode QCA_PLUGIN_PATH is path where plugins was installed
+ paths << QDir(QCA_PLUGIN_PATH).canonicalPath();
#ifndef DEVELOPER_MODE
- paths.removeDuplicates();
+ paths.removeDuplicates();
#endif
- // No empty strings
- paths.removeAll(QString());
- return paths;
+ // No empty strings
+ paths.removeAll(QString());
+ return paths;
}
void scanForPlugins()
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- global->scan();
- global->ksm_scan();
+ global->scan();
+ global->ksm_scan();
}
void unloadAllPlugins()
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- global->unloadAllPlugins();
+ global->unloadAllPlugins();
}
QString pluginDiagnosticText()
{
- if(!global_check_load())
- return QString();
+ if (!global_check_load()) {
+ return QString();
+ }
- return global->manager->diagnosticText();
+ return global->manager->diagnosticText();
}
void clearPluginDiagnosticText()
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- global->manager->clearDiagnosticText();
+ global->manager->clearDiagnosticText();
}
void appendPluginDiagnosticText(const QString &text)
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- global->manager->appendDiagnosticText(text);
+ global->manager->appendDiagnosticText(text);
}
void setProperty(const QString &name, const QVariant &value)
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- QMutexLocker locker(&global->prop_mutex);
+ QMutexLocker locker(&global->prop_mutex);
- global->properties[name] = value;
+ global->properties[name] = value;
}
QVariant getProperty(const QString &name)
{
- if(!global_check_load())
- return QVariant();
+ if (!global_check_load()) {
+ return QVariant();
+ }
- QMutexLocker locker(&global->prop_mutex);
+ QMutexLocker locker(&global->prop_mutex);
- return global->properties.value(name);
+ return global->properties.value(name);
}
static bool configIsValid(const QVariantMap &config)
{
- if(!config.contains("formtype"))
- return false;
- QMapIterator<QString,QVariant> it(config);
- while(it.hasNext())
- {
- it.next();
- const QVariant &v = it.value();
- if(v.type() != QVariant::String && v.type() != QVariant::Int && v.type() != QVariant::Bool)
- return false;
- }
- return true;
+ if (!config.contains("formtype")) {
+ return false;
+ }
+ QMapIterator<QString, QVariant> it(config);
+ while (it.hasNext()) {
+ it.next();
+ const QVariant &v = it.value();
+ if (v.type() != QVariant::String && v.type() != QVariant::Int && v.type() != QVariant::Bool) {
+ return false;
+ }
+ }
+ return true;
}
static QVariantMap readConfig(const QString &name)
{
- QSettings settings("Affinix", "QCA2");
- settings.beginGroup("ProviderConfig");
- QStringList providerNames = settings.value("providerNames").toStringList();
- if(!providerNames.contains(name))
- return QVariantMap();
+ QSettings settings("Affinix", "QCA2");
+ settings.beginGroup("ProviderConfig");
+ QStringList providerNames = settings.value("providerNames").toStringList();
+ if (!providerNames.contains(name)) {
+ return QVariantMap();
+ }
- settings.beginGroup(name);
- QStringList keys = settings.childKeys();
- QVariantMap map;
- foreach(const QString &key, keys)
- map[key] = settings.value(key);
- settings.endGroup();
+ settings.beginGroup(name);
+ QStringList keys = settings.childKeys();
+ QVariantMap map;
+ foreach (const QString &key, keys) {
+ map[key] = settings.value(key);
+ }
+ settings.endGroup();
- if(!configIsValid(map))
- return QVariantMap();
- return map;
+ if (!configIsValid(map)) {
+ return QVariantMap();
+ }
+ return map;
}
static bool writeConfig(const QString &name, const QVariantMap &config, bool systemWide = false)
{
- QSettings settings(QSettings::NativeFormat, systemWide ? QSettings::SystemScope : QSettings::UserScope, "Affinix", "QCA2");
- settings.beginGroup("ProviderConfig");
+ QSettings settings(QSettings::NativeFormat, systemWide ? QSettings::SystemScope : QSettings::UserScope, "Affinix", "QCA2");
+ settings.beginGroup("ProviderConfig");
- // version
- settings.setValue("version", 2);
+ // version
+ settings.setValue("version", 2);
- // add the entry if needed
- QStringList providerNames = settings.value("providerNames").toStringList();
- if(!providerNames.contains(name))
- providerNames += name;
- settings.setValue("providerNames", providerNames);
+ // add the entry if needed
+ QStringList providerNames = settings.value("providerNames").toStringList();
+ if (!providerNames.contains(name)) {
+ providerNames += name;
+ }
+ settings.setValue("providerNames", providerNames);
- settings.beginGroup(name);
- QMapIterator<QString,QVariant> it(config);
- while(it.hasNext())
- {
- it.next();
- settings.setValue(it.key(), it.value());
- }
- settings.endGroup();
+ settings.beginGroup(name);
+ QMapIterator<QString, QVariant> it(config);
+ while (it.hasNext()) {
+ it.next();
+ settings.setValue(it.key(), it.value());
+ }
+ settings.endGroup();
- if(settings.status() == QSettings::NoError)
- return true;
- return false;
+ if (settings.status() == QSettings::NoError) {
+ return true;
+ }
+ return false;
}
void setProviderConfig(const QString &name, const QVariantMap &config)
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- if(!configIsValid(config))
- return;
+ if (!configIsValid(config)) {
+ return;
+ }
- global->config_mutex.lock();
- global->config[name] = config;
- global->config_mutex.unlock();
+ global->config_mutex.lock();
+ global->config[name] = config;
+ global->config_mutex.unlock();
- Provider *p = findProvider(name);
- if(p)
- p->configChanged(config);
+ Provider *p = findProvider(name);
+ if (p) {
+ p->configChanged(config);
+ }
}
QVariantMap getProviderConfig(const QString &name)
{
- if(!global_check_load())
- return QVariantMap();
+ if (!global_check_load()) {
+ return QVariantMap();
+ }
- QVariantMap conf;
+ QVariantMap conf;
- global->config_mutex.lock();
+ global->config_mutex.lock();
- // try loading from persistent storage
- conf = readConfig(name);
+ // try loading from persistent storage
+ conf = readConfig(name);
- // if not, load the one from memory
- if(conf.isEmpty())
- conf = global->config.value(name);
+ // if not, load the one from memory
+ if (conf.isEmpty()) {
+ conf = global->config.value(name);
+ }
- global->config_mutex.unlock();
+ global->config_mutex.unlock();
- // if provider doesn't exist or doesn't have a valid config form,
- // use the config we loaded
- Provider *p = findProvider(name);
- if(!p)
- return conf;
- QVariantMap pconf = p->defaultConfig();
- if(!configIsValid(pconf))
- return conf;
+ // if provider doesn't exist or doesn't have a valid config form,
+ // use the config we loaded
+ Provider *p = findProvider(name);
+ if (!p) {
+ return conf;
+ }
+ QVariantMap pconf = p->defaultConfig();
+ if (!configIsValid(pconf)) {
+ return conf;
+ }
- // if the config loaded was empty, use the provider's config
- if(conf.isEmpty())
- return pconf;
+ // if the config loaded was empty, use the provider's config
+ if (conf.isEmpty()) {
+ return pconf;
+ }
- // if the config formtype doesn't match the provider's formtype,
- // then use the provider's
- if(pconf["formtype"] != conf["formtype"])
- return pconf;
+ // if the config formtype doesn't match the provider's formtype,
+ // then use the provider's
+ if (pconf["formtype"] != conf["formtype"]) {
+ return pconf;
+ }
- // otherwise, use the config loaded
- return conf;
+ // otherwise, use the config loaded
+ return conf;
}
void saveProviderConfig(const QString &name)
{
- if(!global_check_load())
- return;
+ if (!global_check_load()) {
+ return;
+ }
- QMutexLocker locker(&global->config_mutex);
+ QMutexLocker locker(&global->config_mutex);
- QVariantMap conf = global->config.value(name);
- if(conf.isEmpty())
- return;
+ QVariantMap conf = global->config.value(name);
+ if (conf.isEmpty()) {
+ return;
+ }
- writeConfig(name, conf);
+ writeConfig(name, conf);
}
QVariantMap getProviderConfig_internal(Provider *p)
{
- QVariantMap conf;
- QString name = p->name();
+ QVariantMap conf;
+ QString name = p->name();
- global->config_mutex.lock();
+ global->config_mutex.lock();
- // try loading from persistent storage
- conf = readConfig(name);
+ // try loading from persistent storage
+ conf = readConfig(name);
- // if not, load the one from memory
- if(conf.isEmpty())
- conf = global->config.value(name);
+ // if not, load the one from memory
+ if (conf.isEmpty()) {
+ conf = global->config.value(name);
+ }
- global->config_mutex.unlock();
+ global->config_mutex.unlock();
- // if provider doesn't exist or doesn't have a valid config form,
- // use the config we loaded
- QVariantMap pconf = p->defaultConfig();
- if(!configIsValid(pconf))
- return conf;
+ // if provider doesn't exist or doesn't have a valid config form,
+ // use the config we loaded
+ QVariantMap pconf = p->defaultConfig();
+ if (!configIsValid(pconf)) {
+ return conf;
+ }
- // if the config loaded was empty, use the provider's config
- if(conf.isEmpty())
- return pconf;
+ // if the config loaded was empty, use the provider's config
+ if (conf.isEmpty()) {
+ return pconf;
+ }
- // if the config formtype doesn't match the provider's formtype,
- // then use the provider's
- if(pconf["formtype"] != conf["formtype"])
- return pconf;
+ // if the config formtype doesn't match the provider's formtype,
+ // then use the provider's
+ if (pconf["formtype"] != conf["formtype"]) {
+ return pconf;
+ }
- // otherwise, use the config loaded
- return conf;
+ // otherwise, use the config loaded
+ return conf;
}
QString globalRandomProvider()
{
- QMutexLocker locker(global_random_mutex());
- return global_random()->provider()->name();
+ QMutexLocker locker(global_random_mutex());
+ return global_random()->provider()->name();
}
void setGlobalRandomProvider(const QString &provider)
{
- QMutexLocker locker(global_random_mutex());
- delete global->rng;
- global->rng = new Random(provider);
+ QMutexLocker locker(global_random_mutex());
+ delete global->rng;
+ global->rng = new Random(provider);
}
Logger *logger()
{
- return global->get_logger();
+ return global->get_logger();
}
bool haveSystemStore()
{
- // ensure the system store is loaded
- KeyStoreManager::start("default");
- KeyStoreManager ksm;
- ksm.waitForBusyFinished();
+ // ensure the system store is loaded
+ KeyStoreManager::start("default");
+ KeyStoreManager ksm;
+ ksm.waitForBusyFinished();
- QStringList list = ksm.keyStores();
- for(int n = 0; n < list.count(); ++n)
- {
- KeyStore ks(list[n], &ksm);
- if(ks.type() == KeyStore::System && ks.holdsTrustedCertificates())
- return true;
- }
- return false;
+ QStringList list = ksm.keyStores();
+ for (int n = 0; n < list.count(); ++n) {
+ KeyStore ks(list[n], &ksm);
+ if (ks.type() == KeyStore::System && ks.holdsTrustedCertificates()) {
+ return true;
+ }
+ }
+ return false;
}
CertificateCollection systemStore()
{
- // ensure the system store is loaded
- KeyStoreManager::start("default");
- KeyStoreManager ksm;
- ksm.waitForBusyFinished();
-
- CertificateCollection col;
- QStringList list = ksm.keyStores();
- for(int n = 0; n < list.count(); ++n)
- {
- KeyStore ks(list[n], &ksm);
-
- // system store
- if(ks.type() == KeyStore::System && ks.holdsTrustedCertificates())
- {
- // extract contents
- QList<KeyStoreEntry> entries = ks.entryList();
- for(int i = 0; i < entries.count(); ++i)
- {
- if(entries[i].type() == KeyStoreEntry::TypeCertificate)
- col.addCertificate(entries[i].certificate());
- else if(entries[i].type() == KeyStoreEntry::TypeCRL)
- col.addCRL(entries[i].crl());
- }
- break;
- }
- }
- return col;
+ // ensure the system store is loaded
+ KeyStoreManager::start("default");
+ KeyStoreManager ksm;
+ ksm.waitForBusyFinished();
+
+ CertificateCollection col;
+ QStringList list = ksm.keyStores();
+ for (int n = 0; n < list.count(); ++n) {
+ KeyStore ks(list[n], &ksm);
+
+ // system store
+ if (ks.type() == KeyStore::System && ks.holdsTrustedCertificates()) {
+ // extract contents
+ QList<KeyStoreEntry> entries = ks.entryList();
+ for (int i = 0; i < entries.count(); ++i) {
+ if (entries[i].type() == KeyStoreEntry::TypeCertificate) {
+ col.addCertificate(entries[i].certificate());
+ } else if (entries[i].type() == KeyStoreEntry::TypeCRL) {
+ col.addCRL(entries[i].crl());
+ }
+ }
+ break;
+ }
+ }
+ return col;
}
QString appName()
{
- if(!global_check())
- return QString();
+ if (!global_check()) {
+ return QString();
+ }
- QMutexLocker locker(&global->name_mutex);
+ QMutexLocker locker(&global->name_mutex);
- return global->app_name;
+ return global->app_name;
}
void setAppName(const QString &s)
{
- if(!global_check())
- return;
+ if (!global_check()) {
+ return;
+ }
- QMutexLocker locker(&global->name_mutex);
+ QMutexLocker locker(&global->name_mutex);
- global->app_name = s;
+ global->app_name = s;
}
QString arrayToHex(const QByteArray &a)
{
- return Hex().arrayToString(a);
+ return Hex().arrayToString(a);
}
QByteArray hexToArray(const QString &str)
{
- return Hex().stringToArray(str).toByteArray();
+ return Hex().stringToArray(str).toByteArray();
}
QString arrayToBase64(const QByteArray &a)
{
- return Base64().arrayToString(a);
+ return Base64().arrayToString(a);
}
QByteArray base64ToArray(const QString &base64String)
{
- return Base64().stringToArray(base64String).toByteArray();
+ return Base64().stringToArray(base64String).toByteArray();
}
static Provider *getProviderForType(const QString &type, const QString &provider)
{
- Provider *p = 0;
- bool scanned = global->ensure_first_scan();
- if(!provider.isEmpty())
- {
- // try using specific provider
- p = global->manager->findFor(provider, type);
- if(!p && !scanned)
- {
- // maybe this provider is new, so scan and try again
- global->scan();
- scanned = true;
- p = global->manager->findFor(provider, type);
- }
- }
- if(!p)
- {
- // try using some other provider
- p = global->manager->findFor(QString(), type);
-
- // note: we used to rescan if no provider was found or if
- // the only found provider was 'default'. now we only
- // rescan if no provider was found. this optimizes lookups
- // for features that are in the default provider (such as
- // 'sha1') when no other plugin is available. the drawback
- // is that if a plugin is installed later during runtime,
- // then it won't be picked up without restarting the
- // application or manually calling QCA::scanForPlugins.
- //if((!p || p->name() == "default") && !scanned)
- if(!p && !scanned)
- {
- // maybe there are new providers, so scan and try again
- // before giving up or using default
- global->scan();
- scanned = true;
- p = global->manager->findFor(QString(), type);
- }
- }
-
- return p;
+ Provider *p = 0;
+ bool scanned = global->ensure_first_scan();
+ if (!provider.isEmpty()) {
+ // try using specific provider
+ p = global->manager->findFor(provider, type);
+ if (!p && !scanned) {
+ // maybe this provider is new, so scan and try again
+ global->scan();
+ scanned = true;
+ p = global->manager->findFor(provider, type);
+ }
+ }
+ if (!p) {
+ // try using some other provider
+ p = global->manager->findFor(QString(), type);
+
+ // note: we used to rescan if no provider was found or if
+ // the only found provider was 'default'. now we only
+ // rescan if no provider was found. this optimizes lookups
+ // for features that are in the default provider (such as
+ // 'sha1') when no other plugin is available. the drawback
+ // is that if a plugin is installed later during runtime,
+ // then it won't be picked up without restarting the
+ // application or manually calling QCA::scanForPlugins.
+ //if((!p || p->name() == "default") && !scanned)
+ if (!p && !scanned) {
+ // maybe there are new providers, so scan and try again
+ // before giving up or using default
+ global->scan();
+ scanned = true;
+ p = global->manager->findFor(QString(), type);
+ }
+ }
+
+ return p;
}
static inline Provider::Context *doCreateContext(Provider *p, const QString &type)
{
- return p->createContext(type);
+ return p->createContext(type);
}
Provider::Context *getContext(const QString &type, const QString &provider)
{
- if(!global_check_load())
- return 0;
+ if (!global_check_load()) {
+ return 0;
+ }
- Provider *p;
- {
- p = getProviderForType(type, provider);
- if(!p)
- return 0;
- }
+ Provider *p;
+ {
+ p = getProviderForType(type, provider);
+ if (!p) {
+ return 0;
+ }
+ }
- return doCreateContext(p, type);
+ return doCreateContext(p, type);
}
Provider::Context *getContext(const QString &type, Provider *_p)
{
- if(!global_check_load())
- return 0;
+ if (!global_check_load()) {
+ return 0;
+ }
- Provider *p;
- {
- p = global->manager->find(_p);
- if(!p)
- return 0;
- }
+ Provider *p;
+ {
+ p = global->manager->find(_p);
+ if (!p) {
+ return 0;
+ }
+ }
- return doCreateContext(p, type);
+ return doCreateContext(p, type);
}
//----------------------------------------------------------------------------
// Initializer
//----------------------------------------------------------------------------
Initializer::Initializer(MemoryMode m, int prealloc)
{
- init(m, prealloc);
+ init(m, prealloc);
}
Initializer::~Initializer()
{
- deinit();
+ deinit();
}
//----------------------------------------------------------------------------
// Provider
//----------------------------------------------------------------------------
Provider::~Provider()
{
}
void Provider::init()
{
}
void Provider::deinit()
{
}
int Provider::version() const
{
- return 0;
+ return 0;
}
QString Provider::credit() const
{
- return QString();
+ return QString();
}
QVariantMap Provider::defaultConfig() const
{
- return QVariantMap();
+ return QVariantMap();
}
void Provider::configChanged(const QVariantMap &)
{
}
Provider::Context::Context(Provider *parent, const QString &type)
-:QObject()
+ : QObject()
{
- _provider = parent;
- _type = type;
+ _provider = parent;
+ _type = type;
}
Provider::Context::Context(const Context &from)
-:QObject()
+ : QObject()
{
- _provider = from._provider;
- _type = from._type;
+ _provider = from._provider;
+ _type = from._type;
}
Provider::Context::~Context()
{
}
Provider *Provider::Context::provider() const
{
- return _provider;
+ return _provider;
}
QString Provider::Context::type() const
{
- return _type;
+ return _type;
}
bool Provider::Context::sameProvider(const Context *c) const
{
- return (c->provider() == _provider);
+ return (c->provider() == _provider);
}
//----------------------------------------------------------------------------
// BasicContext
//----------------------------------------------------------------------------
BasicContext::BasicContext(Provider *parent, const QString &type)
-:Context(parent, type)
+ : Context(parent, type)
{
- moveToThread(0); // no thread association
+ moveToThread(0); // no thread association
}
BasicContext::BasicContext(const BasicContext &from)
-:Context(from)
+ : Context(from)
{
- moveToThread(0); // no thread association
+ moveToThread(0); // no thread association
}
BasicContext::~BasicContext()
{
}
//----------------------------------------------------------------------------
// InfoContext
//----------------------------------------------------------------------------
QStringList InfoContext::supportedHashTypes() const
{
- return QStringList();
+ return QStringList();
}
QStringList InfoContext::supportedCipherTypes() const
{
- return QStringList();
+ return QStringList();
}
QStringList InfoContext::supportedMACTypes() const
{
- return QStringList();
+ return QStringList();
}
//----------------------------------------------------------------------------
// PKeyBase
//----------------------------------------------------------------------------
PKeyBase::PKeyBase(Provider *p, const QString &type)
-:BasicContext(p, type)
+ : BasicContext(p, type)
{
}
int PKeyBase::maximumEncryptSize(EncryptionAlgorithm) const
{
- return 0;
+ return 0;
}
SecureArray PKeyBase::encrypt(const SecureArray &, EncryptionAlgorithm)
{
- return SecureArray();
+ return SecureArray();
}
bool PKeyBase::decrypt(const SecureArray &, SecureArray *, EncryptionAlgorithm)
{
- return false;
+ return false;
}
void PKeyBase::startSign(SignatureAlgorithm, SignatureFormat)
{
}
void PKeyBase::startVerify(SignatureAlgorithm, SignatureFormat)
{
}
void PKeyBase::update(const MemoryRegion &)
{
}
QByteArray PKeyBase::endSign()
{
- return QByteArray();
+ return QByteArray();
}
bool PKeyBase::endVerify(const QByteArray &)
{
- return false;
+ return false;
}
SymmetricKey PKeyBase::deriveKey(const PKeyBase &)
{
- return SymmetricKey();
+ return SymmetricKey();
}
//----------------------------------------------------------------------------
// PKeyContext
//----------------------------------------------------------------------------
QByteArray PKeyContext::publicToDER() const
{
- return QByteArray();
+ return QByteArray();
}
QString PKeyContext::publicToPEM() const
{
- return QString();
+ return QString();
}
ConvertResult PKeyContext::publicFromDER(const QByteArray &)
{
- return ErrorDecode;
+ return ErrorDecode;
}
ConvertResult PKeyContext::publicFromPEM(const QString &)
{
- return ErrorDecode;
+ return ErrorDecode;
}
SecureArray PKeyContext::privateToDER(const SecureArray &, PBEAlgorithm) const
{
- return SecureArray();
+ return SecureArray();
}
QString PKeyContext::privateToPEM(const SecureArray &, PBEAlgorithm) const
{
- return QString();
+ return QString();
}
ConvertResult PKeyContext::privateFromDER(const SecureArray &, const SecureArray &)
{
- return ErrorDecode;
+ return ErrorDecode;
}
ConvertResult PKeyContext::privateFromPEM(const QString &, const SecureArray &)
{
- return ErrorDecode;
+ return ErrorDecode;
}
//----------------------------------------------------------------------------
// KeyStoreEntryContext
//----------------------------------------------------------------------------
bool KeyStoreEntryContext::isAvailable() const
{
- return true;
+ return true;
}
KeyBundle KeyStoreEntryContext::keyBundle() const
{
- return KeyBundle();
+ return KeyBundle();
}
Certificate KeyStoreEntryContext::certificate() const
{
- return Certificate();
+ return Certificate();
}
CRL KeyStoreEntryContext::crl() const
{
- return CRL();
+ return CRL();
}
PGPKey KeyStoreEntryContext::pgpSecretKey() const
{
- return PGPKey();
+ return PGPKey();
}
PGPKey KeyStoreEntryContext::pgpPublicKey() const
{
- return PGPKey();
+ return PGPKey();
}
bool KeyStoreEntryContext::ensureAccess()
{
- return true;
+ return true;
}
//----------------------------------------------------------------------------
// KeyStoreListContext
//----------------------------------------------------------------------------
void KeyStoreListContext::start()
{
- QMetaObject::invokeMethod(this, "busyEnd", Qt::QueuedConnection);
+ QMetaObject::invokeMethod(this, "busyEnd", Qt::QueuedConnection);
}
void KeyStoreListContext::setUpdatesEnabled(bool)
{
}
bool KeyStoreListContext::isReadOnly(int) const
{
- return true;
+ return true;
}
KeyStoreEntryContext *KeyStoreListContext::entry(int id, const QString &entryId)
{
- KeyStoreEntryContext *out = 0;
- QList<KeyStoreEntryContext*> list = entryList(id);
- for(int n = 0; n < list.count(); ++n)
- {
- if(list[n]->id() == entryId)
- {
- out = list.takeAt(n);
- break;
- }
- }
- qDeleteAll(list);
- return out;
+ KeyStoreEntryContext *out = 0;
+ QList<KeyStoreEntryContext *> list = entryList(id);
+ for (int n = 0; n < list.count(); ++n) {
+ if (list[n]->id() == entryId) {
+ out = list.takeAt(n);
+ break;
+ }
+ }
+ qDeleteAll(list);
+ return out;
}
KeyStoreEntryContext *KeyStoreListContext::entryPassive(const QString &serialized)
{
- Q_UNUSED(serialized);
- return 0;
+ Q_UNUSED(serialized);
+ return 0;
}
QString KeyStoreListContext::writeEntry(int, const KeyBundle &)
{
- return QString();
+ return QString();
}
QString KeyStoreListContext::writeEntry(int, const Certificate &)
{
- return QString();
+ return QString();
}
QString KeyStoreListContext::writeEntry(int, const CRL &)
{
- return QString();
+ return QString();
}
QString KeyStoreListContext::writeEntry(int, const PGPKey &)
{
- return QString();
+ return QString();
}
bool KeyStoreListContext::removeEntry(int, const QString &)
{
- return false;
+ return false;
}
//----------------------------------------------------------------------------
// TLSContext
//----------------------------------------------------------------------------
void TLSContext::setMTU(int)
{
}
//----------------------------------------------------------------------------
// MessageContext
//----------------------------------------------------------------------------
QString MessageContext::diagnosticText() const
{
- return QString();
+ return QString();
}
//----------------------------------------------------------------------------
// SMSContext
//----------------------------------------------------------------------------
void SMSContext::setTrustedCertificates(const CertificateCollection &)
{
}
void SMSContext::setUntrustedCertificates(const CertificateCollection &)
{
}
void SMSContext::setPrivateKeys(const QList<SecureMessageKey> &)
{
}
//----------------------------------------------------------------------------
// BufferedComputation
//----------------------------------------------------------------------------
BufferedComputation::~BufferedComputation()
{
}
MemoryRegion BufferedComputation::process(const MemoryRegion &a)
{
- clear();
- update(a);
- return final();
+ clear();
+ update(a);
+ return final();
}
//----------------------------------------------------------------------------
// Filter
//----------------------------------------------------------------------------
Filter::~Filter()
{
}
MemoryRegion Filter::process(const MemoryRegion &a)
{
- clear();
- MemoryRegion buf = update(a);
- if(!ok())
- return MemoryRegion();
- MemoryRegion fin = final();
- if(!ok())
- return MemoryRegion();
- if(buf.isSecure() || fin.isSecure())
- return (SecureArray(buf) + SecureArray(fin));
- else
- return (buf.toByteArray() + fin.toByteArray());
+ clear();
+ MemoryRegion buf = update(a);
+ if (!ok()) {
+ return MemoryRegion();
+ }
+ MemoryRegion fin = final();
+ if (!ok()) {
+ return MemoryRegion();
+ }
+ if (buf.isSecure() || fin.isSecure()) {
+ return (SecureArray(buf) + SecureArray(fin));
+ } else {
+ return (buf.toByteArray() + fin.toByteArray());
+ }
}
//----------------------------------------------------------------------------
// Algorithm
//----------------------------------------------------------------------------
class Algorithm::Private : public QSharedData
{
public:
- Provider::Context *c;
-
- Private(Provider::Context *context)
- {
- c = context;
- //printf("** [%p] Algorithm Created\n", c);
- }
-
- Private(const Private &from) : QSharedData(from)
- {
- c = from.c->clone();
- //printf("** [%p] Algorithm Copied (to [%p])\n", from.c, c);
- }
-
- ~Private()
- {
- //printf("** [%p] Algorithm Destroyed\n", c);
- delete c;
- }
+ Provider::Context *c;
+
+ Private(Provider::Context *context)
+ {
+ c = context;
+ //printf("** [%p] Algorithm Created\n", c);
+ }
+
+ Private(const Private &from) : QSharedData(from)
+ {
+ c = from.c->clone();
+ //printf("** [%p] Algorithm Copied (to [%p])\n", from.c, c);
+ }
+
+ ~Private()
+ {
+ //printf("** [%p] Algorithm Destroyed\n", c);
+ delete c;
+ }
};
Algorithm::Algorithm()
{
}
Algorithm::Algorithm(const QString &type, const QString &provider)
{
- change(type, provider);
+ change(type, provider);
}
Algorithm::Algorithm(const Algorithm &from)
{
- *this = from;
+ *this = from;
}
Algorithm::~Algorithm()
{
}
-Algorithm & Algorithm::operator=(const Algorithm &from)
+Algorithm &Algorithm::operator=(const Algorithm &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
QString Algorithm::type() const
{
- if(d)
- return d->c->type();
- else
- return QString();
+ if (d) {
+ return d->c->type();
+ } else {
+ return QString();
+ }
}
Provider *Algorithm::provider() const
{
- if(d)
- return d->c->provider();
- else
- return 0;
+ if (d) {
+ return d->c->provider();
+ } else {
+ return 0;
+ }
}
Provider::Context *Algorithm::context()
{
- if(d)
- return d->c;
- else
- return 0;
+ if (d) {
+ return d->c;
+ } else {
+ return 0;
+ }
}
const Provider::Context *Algorithm::context() const
{
- if(d)
- return d->c;
- else
- return 0;
+ if (d) {
+ return d->c;
+ } else {
+ return 0;
+ }
}
void Algorithm::change(Provider::Context *c)
{
- if(c)
- d = new Private(c);
- else
- d = 0;
+ if (c) {
+ d = new Private(c);
+ } else {
+ d = 0;
+ }
}
void Algorithm::change(const QString &type, const QString &provider)
{
- if(!type.isEmpty())
- change(getContext(type, provider));
- else
- change(0);
+ if (!type.isEmpty()) {
+ change(getContext(type, provider));
+ } else {
+ change(0);
+ }
}
Provider::Context *Algorithm::takeContext()
{
- if(d)
- {
- Provider::Context *c = d->c; // should cause a detach
- d->c = 0;
- d = 0;
- return c;
- }
- else
- return 0;
+ if (d) {
+ Provider::Context *c = d->c; // should cause a detach
+ d->c = 0;
+ d = 0;
+ return c;
+ } else {
+ return 0;
+ }
}
//----------------------------------------------------------------------------
// SymmetricKey
//----------------------------------------------------------------------------
SymmetricKey::SymmetricKey()
{
}
SymmetricKey::SymmetricKey(int size)
{
- set(Random::randomArray(size));
+ set(Random::randomArray(size));
}
SymmetricKey::SymmetricKey(const SecureArray &a)
{
- set(a);
+ set(a);
}
SymmetricKey::SymmetricKey(const QByteArray &a)
{
- set(SecureArray(a));
+ set(SecureArray(a));
}
/* from libgcrypt-1.2.0 */
-static unsigned char desWeakKeyTable[64][8] =
-{
- { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, /*w*/
- { 0x00, 0x00, 0x1e, 0x1e, 0x00, 0x00, 0x0e, 0x0e },
- { 0x00, 0x00, 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0xf0 },
- { 0x00, 0x00, 0xfe, 0xfe, 0x00, 0x00, 0xfe, 0xfe },
- { 0x00, 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e }, /*sw*/
- { 0x00, 0x1e, 0x1e, 0x00, 0x00, 0x0e, 0x0e, 0x00 },
- { 0x00, 0x1e, 0xe0, 0xfe, 0x00, 0x0e, 0xf0, 0xfe },
- { 0x00, 0x1e, 0xfe, 0xe0, 0x00, 0x0e, 0xfe, 0xf0 },
- { 0x00, 0xe0, 0x00, 0xe0, 0x00, 0xf0, 0x00, 0xf0 }, /*sw*/
- { 0x00, 0xe0, 0x1e, 0xfe, 0x00, 0xf0, 0x0e, 0xfe },
- { 0x00, 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0xf0, 0x00 },
- { 0x00, 0xe0, 0xfe, 0x1e, 0x00, 0xf0, 0xfe, 0x0e },
- { 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe }, /*sw*/
- { 0x00, 0xfe, 0x1e, 0xe0, 0x00, 0xfe, 0x0e, 0xf0 },
- { 0x00, 0xfe, 0xe0, 0x1e, 0x00, 0xfe, 0xf0, 0x0e },
- { 0x00, 0xfe, 0xfe, 0x00, 0x00, 0xfe, 0xfe, 0x00 },
- { 0x1e, 0x00, 0x00, 0x1e, 0x0e, 0x00, 0x00, 0x0e },
- { 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e, 0x00 }, /*sw*/
- { 0x1e, 0x00, 0xe0, 0xfe, 0x0e, 0x00, 0xf0, 0xfe },
- { 0x1e, 0x00, 0xfe, 0xe0, 0x0e, 0x00, 0xfe, 0xf0 },
- { 0x1e, 0x1e, 0x00, 0x00, 0x0e, 0x0e, 0x00, 0x00 },
- { 0x1e, 0x1e, 0x1e, 0x1e, 0x0e, 0x0e, 0x0e, 0x0e }, /*w*/
- { 0x1e, 0x1e, 0xe0, 0xe0, 0x0e, 0x0e, 0xf0, 0xf0 },
- { 0x1e, 0x1e, 0xfe, 0xfe, 0x0e, 0x0e, 0xfe, 0xfe },
- { 0x1e, 0xe0, 0x00, 0xfe, 0x0e, 0xf0, 0x00, 0xfe },
- { 0x1e, 0xe0, 0x1e, 0xe0, 0x0e, 0xf0, 0x0e, 0xf0 }, /*sw*/
- { 0x1e, 0xe0, 0xe0, 0x1e, 0x0e, 0xf0, 0xf0, 0x0e },
- { 0x1e, 0xe0, 0xfe, 0x00, 0x0e, 0xf0, 0xfe, 0x00 },
- { 0x1e, 0xfe, 0x00, 0xe0, 0x0e, 0xfe, 0x00, 0xf0 },
- { 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe }, /*sw*/
- { 0x1e, 0xfe, 0xe0, 0x00, 0x0e, 0xfe, 0xf0, 0x00 },
- { 0x1e, 0xfe, 0xfe, 0x1e, 0x0e, 0xfe, 0xfe, 0x0e },
- { 0xe0, 0x00, 0x00, 0xe0, 0xf0, 0x00, 0x00, 0xf0 },
- { 0xe0, 0x00, 0x1e, 0xfe, 0xf0, 0x00, 0x0e, 0xfe },
- { 0xe0, 0x00, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00 }, /*sw*/
- { 0xe0, 0x00, 0xfe, 0x1e, 0xf0, 0x00, 0xfe, 0x0e },
- { 0xe0, 0x1e, 0x00, 0xfe, 0xf0, 0x0e, 0x00, 0xfe },
- { 0xe0, 0x1e, 0x1e, 0xe0, 0xf0, 0x0e, 0x0e, 0xf0 },
- { 0xe0, 0x1e, 0xe0, 0x1e, 0xf0, 0x0e, 0xf0, 0x0e }, /*sw*/
- { 0xe0, 0x1e, 0xfe, 0x00, 0xf0, 0x0e, 0xfe, 0x00 },
- { 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0xf0, 0x00, 0x00 },
- { 0xe0, 0xe0, 0x1e, 0x1e, 0xf0, 0xf0, 0x0e, 0x0e },
- { 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0xf0, 0xf0, 0xf0 }, /*w*/
- { 0xe0, 0xe0, 0xfe, 0xfe, 0xf0, 0xf0, 0xfe, 0xfe },
- { 0xe0, 0xfe, 0x00, 0x1e, 0xf0, 0xfe, 0x00, 0x0e },
- { 0xe0, 0xfe, 0x1e, 0x00, 0xf0, 0xfe, 0x0e, 0x00 },
- { 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0, 0xfe }, /*sw*/
- { 0xe0, 0xfe, 0xfe, 0xe0, 0xf0, 0xfe, 0xfe, 0xf0 },
- { 0xfe, 0x00, 0x00, 0xfe, 0xfe, 0x00, 0x00, 0xfe },
- { 0xfe, 0x00, 0x1e, 0xe0, 0xfe, 0x00, 0x0e, 0xf0 },
- { 0xfe, 0x00, 0xe0, 0x1e, 0xfe, 0x00, 0xf0, 0x0e },
- { 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00 }, /*sw*/
- { 0xfe, 0x1e, 0x00, 0xe0, 0xfe, 0x0e, 0x00, 0xf0 },
- { 0xfe, 0x1e, 0x1e, 0xfe, 0xfe, 0x0e, 0x0e, 0xfe },
- { 0xfe, 0x1e, 0xe0, 0x00, 0xfe, 0x0e, 0xf0, 0x00 },
- { 0xfe, 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e }, /*sw*/
- { 0xfe, 0xe0, 0x00, 0x1e, 0xfe, 0xf0, 0x00, 0x0e },
- { 0xfe, 0xe0, 0x1e, 0x00, 0xfe, 0xf0, 0x0e, 0x00 },
- { 0xfe, 0xe0, 0xe0, 0xfe, 0xfe, 0xf0, 0xf0, 0xfe },
- { 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0 }, /*sw*/
- { 0xfe, 0xfe, 0x00, 0x00, 0xfe, 0xfe, 0x00, 0x00 },
- { 0xfe, 0xfe, 0x1e, 0x1e, 0xfe, 0xfe, 0x0e, 0x0e },
- { 0xfe, 0xfe, 0xe0, 0xe0, 0xfe, 0xfe, 0xf0, 0xf0 },
- { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe } /*w*/
+static unsigned char desWeakKeyTable[64][8] = {
+ { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }, /*w*/
+ { 0x00, 0x00, 0x1e, 0x1e, 0x00, 0x00, 0x0e, 0x0e },
+ { 0x00, 0x00, 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0xf0 },
+ { 0x00, 0x00, 0xfe, 0xfe, 0x00, 0x00, 0xfe, 0xfe },
+ { 0x00, 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e }, /*sw*/
+ { 0x00, 0x1e, 0x1e, 0x00, 0x00, 0x0e, 0x0e, 0x00 },
+ { 0x00, 0x1e, 0xe0, 0xfe, 0x00, 0x0e, 0xf0, 0xfe },
+ { 0x00, 0x1e, 0xfe, 0xe0, 0x00, 0x0e, 0xfe, 0xf0 },
+ { 0x00, 0xe0, 0x00, 0xe0, 0x00, 0xf0, 0x00, 0xf0 }, /*sw*/
+ { 0x00, 0xe0, 0x1e, 0xfe, 0x00, 0xf0, 0x0e, 0xfe },
+ { 0x00, 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0xf0, 0x00 },
+ { 0x00, 0xe0, 0xfe, 0x1e, 0x00, 0xf0, 0xfe, 0x0e },
+ { 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe }, /*sw*/
+ { 0x00, 0xfe, 0x1e, 0xe0, 0x00, 0xfe, 0x0e, 0xf0 },
+ { 0x00, 0xfe, 0xe0, 0x1e, 0x00, 0xfe, 0xf0, 0x0e },
+ { 0x00, 0xfe, 0xfe, 0x00, 0x00, 0xfe, 0xfe, 0x00 },
+ { 0x1e, 0x00, 0x00, 0x1e, 0x0e, 0x00, 0x00, 0x0e },
+ { 0x1e, 0x00, 0x1e, 0x00, 0x0e, 0x00, 0x0e, 0x00 }, /*sw*/
+ { 0x1e, 0x00, 0xe0, 0xfe, 0x0e, 0x00, 0xf0, 0xfe },
+ { 0x1e, 0x00, 0xfe, 0xe0, 0x0e, 0x00, 0xfe, 0xf0 },
+ { 0x1e, 0x1e, 0x00, 0x00, 0x0e, 0x0e, 0x00, 0x00 },
+ { 0x1e, 0x1e, 0x1e, 0x1e, 0x0e, 0x0e, 0x0e, 0x0e }, /*w*/
+ { 0x1e, 0x1e, 0xe0, 0xe0, 0x0e, 0x0e, 0xf0, 0xf0 },
+ { 0x1e, 0x1e, 0xfe, 0xfe, 0x0e, 0x0e, 0xfe, 0xfe },
+ { 0x1e, 0xe0, 0x00, 0xfe, 0x0e, 0xf0, 0x00, 0xfe },
+ { 0x1e, 0xe0, 0x1e, 0xe0, 0x0e, 0xf0, 0x0e, 0xf0 }, /*sw*/
+ { 0x1e, 0xe0, 0xe0, 0x1e, 0x0e, 0xf0, 0xf0, 0x0e },
+ { 0x1e, 0xe0, 0xfe, 0x00, 0x0e, 0xf0, 0xfe, 0x00 },
+ { 0x1e, 0xfe, 0x00, 0xe0, 0x0e, 0xfe, 0x00, 0xf0 },
+ { 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe }, /*sw*/
+ { 0x1e, 0xfe, 0xe0, 0x00, 0x0e, 0xfe, 0xf0, 0x00 },
+ { 0x1e, 0xfe, 0xfe, 0x1e, 0x0e, 0xfe, 0xfe, 0x0e },
+ { 0xe0, 0x00, 0x00, 0xe0, 0xf0, 0x00, 0x00, 0xf0 },
+ { 0xe0, 0x00, 0x1e, 0xfe, 0xf0, 0x00, 0x0e, 0xfe },
+ { 0xe0, 0x00, 0xe0, 0x00, 0xf0, 0x00, 0xf0, 0x00 }, /*sw*/
+ { 0xe0, 0x00, 0xfe, 0x1e, 0xf0, 0x00, 0xfe, 0x0e },
+ { 0xe0, 0x1e, 0x00, 0xfe, 0xf0, 0x0e, 0x00, 0xfe },
+ { 0xe0, 0x1e, 0x1e, 0xe0, 0xf0, 0x0e, 0x0e, 0xf0 },
+ { 0xe0, 0x1e, 0xe0, 0x1e, 0xf0, 0x0e, 0xf0, 0x0e }, /*sw*/
+ { 0xe0, 0x1e, 0xfe, 0x00, 0xf0, 0x0e, 0xfe, 0x00 },
+ { 0xe0, 0xe0, 0x00, 0x00, 0xf0, 0xf0, 0x00, 0x00 },
+ { 0xe0, 0xe0, 0x1e, 0x1e, 0xf0, 0xf0, 0x0e, 0x0e },
+ { 0xe0, 0xe0, 0xe0, 0xe0, 0xf0, 0xf0, 0xf0, 0xf0 }, /*w*/
+ { 0xe0, 0xe0, 0xfe, 0xfe, 0xf0, 0xf0, 0xfe, 0xfe },
+ { 0xe0, 0xfe, 0x00, 0x1e, 0xf0, 0xfe, 0x00, 0x0e },
+ { 0xe0, 0xfe, 0x1e, 0x00, 0xf0, 0xfe, 0x0e, 0x00 },
+ { 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0, 0xfe }, /*sw*/
+ { 0xe0, 0xfe, 0xfe, 0xe0, 0xf0, 0xfe, 0xfe, 0xf0 },
+ { 0xfe, 0x00, 0x00, 0xfe, 0xfe, 0x00, 0x00, 0xfe },
+ { 0xfe, 0x00, 0x1e, 0xe0, 0xfe, 0x00, 0x0e, 0xf0 },
+ { 0xfe, 0x00, 0xe0, 0x1e, 0xfe, 0x00, 0xf0, 0x0e },
+ { 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00 }, /*sw*/
+ { 0xfe, 0x1e, 0x00, 0xe0, 0xfe, 0x0e, 0x00, 0xf0 },
+ { 0xfe, 0x1e, 0x1e, 0xfe, 0xfe, 0x0e, 0x0e, 0xfe },
+ { 0xfe, 0x1e, 0xe0, 0x00, 0xfe, 0x0e, 0xf0, 0x00 },
+ { 0xfe, 0x1e, 0xfe, 0x1e, 0xfe, 0x0e, 0xfe, 0x0e }, /*sw*/
+ { 0xfe, 0xe0, 0x00, 0x1e, 0xfe, 0xf0, 0x00, 0x0e },
+ { 0xfe, 0xe0, 0x1e, 0x00, 0xfe, 0xf0, 0x0e, 0x00 },
+ { 0xfe, 0xe0, 0xe0, 0xfe, 0xfe, 0xf0, 0xf0, 0xfe },
+ { 0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf0, 0xfe, 0xf0 }, /*sw*/
+ { 0xfe, 0xfe, 0x00, 0x00, 0xfe, 0xfe, 0x00, 0x00 },
+ { 0xfe, 0xfe, 0x1e, 0x1e, 0xfe, 0xfe, 0x0e, 0x0e },
+ { 0xfe, 0xfe, 0xe0, 0xe0, 0xfe, 0xfe, 0xf0, 0xf0 },
+ { 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe } /*w*/
};
bool SymmetricKey::isWeakDESKey()
{
- if(size() != 8)
- return false; // dubious
- SecureArray workingCopy(8);
- // clear parity bits
- for(uint i = 0; i < 8; i++)
- workingCopy[i] = (data()[i]) & 0xfe;
+ if (size() != 8) {
+ return false; // dubious
+ }
+ SecureArray workingCopy(8);
+ // clear parity bits
+ for (uint i = 0; i < 8; i++) {
+ workingCopy[i] = (data()[i]) & 0xfe;
+ }
- for(int n = 0; n < 64; n++)
- {
- if(memcmp(workingCopy.data(), desWeakKeyTable[n], 8) == 0)
- return true;
- }
- return false;
+ for (int n = 0; n < 64; n++) {
+ if (memcmp(workingCopy.data(), desWeakKeyTable[n], 8) == 0) {
+ return true;
+ }
+ }
+ return false;
}
//----------------------------------------------------------------------------
// InitializationVector
//----------------------------------------------------------------------------
InitializationVector::InitializationVector()
{
}
InitializationVector::InitializationVector(int size)
{
- set(Random::randomArray(size));
+ set(Random::randomArray(size));
}
InitializationVector::InitializationVector(const SecureArray &a)
{
- set(a);
+ set(a);
}
InitializationVector::InitializationVector(const QByteArray &a)
{
- set(SecureArray(a));
+ set(SecureArray(a));
}
//----------------------------------------------------------------------------
// AuthTag
//----------------------------------------------------------------------------
AuthTag::AuthTag()
{
}
AuthTag::AuthTag(int size)
{
- resize(size);
+ resize(size);
}
AuthTag::AuthTag(const SecureArray &a)
{
- set(a);
+ set(a);
}
AuthTag::AuthTag(const QByteArray &a)
{
- set(SecureArray(a));
+ set(SecureArray(a));
}
//----------------------------------------------------------------------------
// Event
//----------------------------------------------------------------------------
class Event::Private : public QSharedData
{
public:
- Type type;
- Source source;
- PasswordStyle style;
- KeyStoreInfo ksi;
- KeyStoreEntry kse;
- QString fname;
- void *ptr;
+ Type type;
+ Source source;
+ PasswordStyle style;
+ KeyStoreInfo ksi;
+ KeyStoreEntry kse;
+ QString fname;
+ void *ptr;
};
Event::Event()
{
}
Event::Event(const Event &from)
-:d(from.d)
+ : d(from.d)
{
}
Event::~Event()
{
}
-Event & Event::operator=(const Event &from)
+Event &Event::operator=(const Event &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
bool Event::isNull() const
{
- return (d ? false : true);
+ return (d ? false : true);
}
Event::Type Event::type() const
{
- return d->type;
+ return d->type;
}
Event::Source Event::source() const
{
- return d->source;
+ return d->source;
}
Event::PasswordStyle Event::passwordStyle() const
{
- return d->style;
+ return d->style;
}
KeyStoreInfo Event::keyStoreInfo() const
{
- return d->ksi;
+ return d->ksi;
}
KeyStoreEntry Event::keyStoreEntry() const
{
- return d->kse;
+ return d->kse;
}
QString Event::fileName() const
{
- return d->fname;
+ return d->fname;
}
void *Event::ptr() const
{
- return d->ptr;
+ return d->ptr;
}
void Event::setPasswordKeyStore(PasswordStyle pstyle, const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr)
{
- if(!d)
- d = new Private;
- d->type = Password;
- d->source = KeyStore;
- d->style = pstyle;
- d->ksi = keyStoreInfo;
- d->kse = keyStoreEntry;
- d->fname = QString();
- d->ptr = ptr;
+ if (!d) {
+ d = new Private;
+ }
+ d->type = Password;
+ d->source = KeyStore;
+ d->style = pstyle;
+ d->ksi = keyStoreInfo;
+ d->kse = keyStoreEntry;
+ d->fname = QString();
+ d->ptr = ptr;
}
void Event::setPasswordData(PasswordStyle pstyle, const QString &fileName, void *ptr)
{
- if(!d)
- d = new Private;
- d->type = Password;
- d->source = Data;
- d->style = pstyle;
- d->ksi = KeyStoreInfo();
- d->kse = KeyStoreEntry();
- d->fname = fileName;
- d->ptr = ptr;
+ if (!d) {
+ d = new Private;
+ }
+ d->type = Password;
+ d->source = Data;
+ d->style = pstyle;
+ d->ksi = KeyStoreInfo();
+ d->kse = KeyStoreEntry();
+ d->fname = fileName;
+ d->ptr = ptr;
}
void Event::setToken(const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr)
{
- if(!d)
- d = new Private;
- d->type = Token;
- d->source = KeyStore;
- d->style = StylePassword;
- d->ksi = keyStoreInfo;
- d->kse = keyStoreEntry;
- d->fname = QString();
- d->ptr = ptr;
+ if (!d) {
+ d = new Private;
+ }
+ d->type = Token;
+ d->source = KeyStore;
+ d->style = StylePassword;
+ d->ksi = keyStoreInfo;
+ d->kse = keyStoreEntry;
+ d->fname = QString();
+ d->ptr = ptr;
}
//----------------------------------------------------------------------------
// EventGlobal
//----------------------------------------------------------------------------
class HandlerBase : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- HandlerBase(QObject *parent = 0) : QObject(parent)
- {
- }
+ HandlerBase(QObject *parent = 0) : QObject(parent)
+ {
+ }
protected slots:
- virtual void ask(int id, const QCA::Event &e) = 0;
+ virtual void ask(int id, const QCA::Event &e) = 0;
};
class AskerBase : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- AskerBase(QObject *parent = 0) : QObject(parent)
- {
- }
+ AskerBase(QObject *parent = 0) : QObject(parent)
+ {
+ }
- virtual void set_accepted(const SecureArray &password) = 0;
- virtual void set_rejected() = 0;
+ virtual void set_accepted(const SecureArray &password) = 0;
+ virtual void set_rejected() = 0;
};
static void handler_add(HandlerBase *h, int pos = -1);
static void handler_remove(HandlerBase *h);
static void handler_accept(HandlerBase *h, int id, const SecureArray &password);
static void handler_reject(HandlerBase *h, int id);
static bool asker_ask(AskerBase *a, const Event &e);
static void asker_cancel(AskerBase *a);
Q_GLOBAL_STATIC(QMutex, g_event_mutex)
class EventGlobal;
static EventGlobal *g_event = 0;
class EventGlobal
{
public:
- class HandlerItem
- {
- public:
- HandlerBase *h;
- QList<int> ids;
- };
-
- class AskerItem
- {
- public:
- AskerBase *a;
- int id;
- Event event;
- int handler_pos;
- };
-
- QList<HandlerItem> handlers;
- QList<AskerItem> askers;
-
- int next_id;
-
- EventGlobal()
- {
- qRegisterMetaType<Event>("QCA::Event");
- qRegisterMetaType<SecureArray>("QCA::SecureArray");
- next_id = 0;
- }
-
- int findHandlerItem(HandlerBase *h)
- {
- for(int n = 0; n < handlers.count(); ++n)
- {
- if(handlers[n].h == h)
- return n;
- }
- return -1;
- }
-
- int findAskerItem(AskerBase *a)
- {
- for(int n = 0; n < askers.count(); ++n)
- {
- if(askers[n].a == a)
- return n;
- }
- return -1;
- }
-
- int findAskerItemById(int id)
- {
- for(int n = 0; n < askers.count(); ++n)
- {
- if(askers[n].id == id)
- return n;
- }
- return -1;
- }
-
- void ask(int asker_at)
- {
- AskerItem &i = askers[asker_at];
-
- g_event->handlers[i.handler_pos].ids += i.id;
- QMetaObject::invokeMethod(handlers[i.handler_pos].h, "ask",
- Qt::QueuedConnection, Q_ARG(int, i.id),
- Q_ARG(QCA::Event, i.event));
- }
-
- void reject(int asker_at)
- {
- AskerItem &i = askers[asker_at];
-
- // look for the next usable handler
- int pos = -1;
- for(int n = i.handler_pos + 1; n < g_event->handlers.count(); ++n)
- {
- // handler and asker can't be in the same thread
- //Q_ASSERT(g_event->handlers[n].h->thread() != i.a->thread());
- //if(g_event->handlers[n].h->thread() != i.a->thread())
- //{
- pos = n;
- break;
- //}
- }
-
- // if there is one, try it
- if(pos != -1)
- {
- i.handler_pos = pos;
- ask(asker_at);
- }
- // if not, send official reject
- else
- {
- AskerBase *asker = i.a;
- askers.removeAt(asker_at);
-
- asker->set_rejected();
- }
- }
+ class HandlerItem
+ {
+ public:
+ HandlerBase *h;
+ QList<int> ids;
+ };
+
+ class AskerItem
+ {
+ public:
+ AskerBase *a;
+ int id;
+ Event event;
+ int handler_pos;
+ };
+
+ QList<HandlerItem> handlers;
+ QList<AskerItem> askers;
+
+ int next_id;
+
+ EventGlobal()
+ {
+ qRegisterMetaType<Event>("QCA::Event");
+ qRegisterMetaType<SecureArray>("QCA::SecureArray");
+ next_id = 0;
+ }
+
+ int findHandlerItem(HandlerBase *h)
+ {
+ for (int n = 0; n < handlers.count(); ++n) {
+ if (handlers[n].h == h) {
+ return n;
+ }
+ }
+ return -1;
+ }
+
+ int findAskerItem(AskerBase *a)
+ {
+ for (int n = 0; n < askers.count(); ++n) {
+ if (askers[n].a == a) {
+ return n;
+ }
+ }
+ return -1;
+ }
+
+ int findAskerItemById(int id)
+ {
+ for (int n = 0; n < askers.count(); ++n) {
+ if (askers[n].id == id) {
+ return n;
+ }
+ }
+ return -1;
+ }
+
+ void ask(int asker_at)
+ {
+ AskerItem &i = askers[asker_at];
+
+ g_event->handlers[i.handler_pos].ids += i.id;
+ QMetaObject::invokeMethod(handlers[i.handler_pos].h, "ask",
+ Qt::QueuedConnection, Q_ARG(int, i.id),
+ Q_ARG(QCA::Event, i.event));
+ }
+
+ void reject(int asker_at)
+ {
+ AskerItem &i = askers[asker_at];
+
+ // look for the next usable handler
+ int pos = -1;
+ for (int n = i.handler_pos + 1; n < g_event->handlers.count(); ++n) {
+ // handler and asker can't be in the same thread
+ //Q_ASSERT(g_event->handlers[n].h->thread() != i.a->thread());
+ //if(g_event->handlers[n].h->thread() != i.a->thread())
+ //{
+ pos = n;
+ break;
+ //}
+ }
+
+ // if there is one, try it
+ if (pos != -1) {
+ i.handler_pos = pos;
+ ask(asker_at);
+ }
+ // if not, send official reject
+ else {
+ AskerBase *asker = i.a;
+ askers.removeAt(asker_at);
+
+ asker->set_rejected();
+ }
+ }
};
void handler_add(HandlerBase *h, int pos)
{
- QMutexLocker locker(g_event_mutex());
- if(!g_event)
- g_event = new EventGlobal;
+ QMutexLocker locker(g_event_mutex());
+ if (!g_event) {
+ g_event = new EventGlobal;
+ }
- EventGlobal::HandlerItem i;
- i.h = h;
+ EventGlobal::HandlerItem i;
+ i.h = h;
- if(pos != -1)
- {
- g_event->handlers.insert(pos, i);
+ if (pos != -1) {
+ g_event->handlers.insert(pos, i);
- // adjust handler positions
- for(int n = 0; n < g_event->askers.count(); ++n)
- {
- if(g_event->askers[n].handler_pos >= pos)
- g_event->askers[n].handler_pos++;
- }
- }
- else
- g_event->handlers += i;
+ // adjust handler positions
+ for (int n = 0; n < g_event->askers.count(); ++n) {
+ if (g_event->askers[n].handler_pos >= pos) {
+ g_event->askers[n].handler_pos++;
+ }
+ }
+ } else {
+ g_event->handlers += i;
+ }
}
void handler_remove(HandlerBase *h)
{
- QMutexLocker locker(g_event_mutex());
- Q_ASSERT(g_event);
- if(!g_event)
- return;
- int at = g_event->findHandlerItem(h);
- Q_ASSERT(at != -1);
- if(at == -1)
- return;
-
- QList<int> ids = g_event->handlers[at].ids;
- g_event->handlers.removeAt(at);
-
- // adjust handler positions within askers
- for(int n = 0; n < g_event->askers.count(); ++n)
- {
- if(g_event->askers[n].handler_pos >= at)
- g_event->askers[n].handler_pos--;
- }
-
- // reject all askers
- foreach(int id, ids)
- {
- int asker_at = g_event->findAskerItemById(id);
- Q_ASSERT(asker_at != -1);
-
- g_event->reject(asker_at);
- }
-
- if(g_event->handlers.isEmpty())
- {
- delete g_event;
- g_event = 0;
- }
+ QMutexLocker locker(g_event_mutex());
+ Q_ASSERT(g_event);
+ if (!g_event) {
+ return;
+ }
+ int at = g_event->findHandlerItem(h);
+ Q_ASSERT(at != -1);
+ if (at == -1) {
+ return;
+ }
+
+ QList<int> ids = g_event->handlers[at].ids;
+ g_event->handlers.removeAt(at);
+
+ // adjust handler positions within askers
+ for (int n = 0; n < g_event->askers.count(); ++n) {
+ if (g_event->askers[n].handler_pos >= at) {
+ g_event->askers[n].handler_pos--;
+ }
+ }
+
+ // reject all askers
+ foreach (int id, ids) {
+ int asker_at = g_event->findAskerItemById(id);
+ Q_ASSERT(asker_at != -1);
+
+ g_event->reject(asker_at);
+ }
+
+ if (g_event->handlers.isEmpty()) {
+ delete g_event;
+ g_event = 0;
+ }
}
void handler_accept(HandlerBase *h, int id, const SecureArray &password)
{
- QMutexLocker locker(g_event_mutex());
- Q_ASSERT(g_event);
- if(!g_event)
- return;
- int at = g_event->findHandlerItem(h);
- Q_ASSERT(at != -1);
- if(at == -1)
- return;
- int asker_at = g_event->findAskerItemById(id);
- Q_ASSERT(asker_at != -1);
- if(asker_at == -1)
- return;
+ QMutexLocker locker(g_event_mutex());
+ Q_ASSERT(g_event);
+ if (!g_event) {
+ return;
+ }
+ int at = g_event->findHandlerItem(h);
+ Q_ASSERT(at != -1);
+ if (at == -1) {
+ return;
+ }
+ int asker_at = g_event->findAskerItemById(id);
+ Q_ASSERT(asker_at != -1);
+ if (asker_at == -1) {
+ return;
+ }
- g_event->handlers[at].ids.removeAll(g_event->askers[asker_at].id);
+ g_event->handlers[at].ids.removeAll(g_event->askers[asker_at].id);
- AskerBase *asker = g_event->askers[asker_at].a;
- asker->set_accepted(password);
+ AskerBase *asker = g_event->askers[asker_at].a;
+ asker->set_accepted(password);
}
void handler_reject(HandlerBase *h, int id)
{
- QMutexLocker locker(g_event_mutex());
- Q_ASSERT(g_event);
- if(!g_event)
- return;
- int at = g_event->findHandlerItem(h);
- Q_ASSERT(at != -1);
- if(at == -1)
- return;
- int asker_at = g_event->findAskerItemById(id);
- Q_ASSERT(asker_at != -1);
- if(asker_at == -1)
- return;
+ QMutexLocker locker(g_event_mutex());
+ Q_ASSERT(g_event);
+ if (!g_event) {
+ return;
+ }
+ int at = g_event->findHandlerItem(h);
+ Q_ASSERT(at != -1);
+ if (at == -1) {
+ return;
+ }
+ int asker_at = g_event->findAskerItemById(id);
+ Q_ASSERT(asker_at != -1);
+ if (asker_at == -1) {
+ return;
+ }
- g_event->handlers[at].ids.removeAll(g_event->askers[asker_at].id);
+ g_event->handlers[at].ids.removeAll(g_event->askers[asker_at].id);
- g_event->reject(asker_at);
+ g_event->reject(asker_at);
}
bool asker_ask(AskerBase *a, const Event &e)
{
- QMutexLocker locker(g_event_mutex());
- if(!g_event)
- return false;
-
- int pos = -1;
- for(int n = 0; n < g_event->handlers.count(); ++n)
- {
- // handler and asker can't be in the same thread
- //Q_ASSERT(g_event->handlers[n].h->thread() != a->thread());
- //if(g_event->handlers[n].h->thread() != a->thread())
- //{
- pos = n;
- break;
- //}
- }
- if(pos == -1)
- return false;
-
- EventGlobal::AskerItem i;
- i.a = a;
- i.id = g_event->next_id++;
- i.event = e;
- i.handler_pos = pos;
- g_event->askers += i;
- int asker_at = g_event->askers.count() - 1;
-
- g_event->ask(asker_at);
- return true;
+ QMutexLocker locker(g_event_mutex());
+ if (!g_event) {
+ return false;
+ }
+
+ int pos = -1;
+ for (int n = 0; n < g_event->handlers.count(); ++n) {
+ // handler and asker can't be in the same thread
+ //Q_ASSERT(g_event->handlers[n].h->thread() != a->thread());
+ //if(g_event->handlers[n].h->thread() != a->thread())
+ //{
+ pos = n;
+ break;
+ //}
+ }
+ if (pos == -1) {
+ return false;
+ }
+
+ EventGlobal::AskerItem i;
+ i.a = a;
+ i.id = g_event->next_id++;
+ i.event = e;
+ i.handler_pos = pos;
+ g_event->askers += i;
+ int asker_at = g_event->askers.count() - 1;
+
+ g_event->ask(asker_at);
+ return true;
}
void asker_cancel(AskerBase *a)
{
- QMutexLocker locker(g_event_mutex());
- if(!g_event)
- return;
- int at = g_event->findAskerItem(a);
- if(at == -1)
- return;
+ QMutexLocker locker(g_event_mutex());
+ if (!g_event) {
+ return;
+ }
+ int at = g_event->findAskerItem(a);
+ if (at == -1) {
+ return;
+ }
- for(int n = 0; n < g_event->handlers.count(); ++n)
- g_event->handlers[n].ids.removeAll(g_event->askers[at].id);
+ for (int n = 0; n < g_event->handlers.count(); ++n) {
+ g_event->handlers[n].ids.removeAll(g_event->askers[at].id);
+ }
- g_event->askers.removeAt(at);
+ g_event->askers.removeAt(at);
}
//----------------------------------------------------------------------------
// EventHandler
//----------------------------------------------------------------------------
class EventHandler::Private : public HandlerBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- EventHandler *q;
- bool started;
- QList<int> activeIds;
+ EventHandler *q;
+ bool started;
+ QList<int> activeIds;
- Private(EventHandler *_q) : HandlerBase(_q), q(_q)
- {
- started = false;
- }
+ Private(EventHandler *_q) : HandlerBase(_q), q(_q)
+ {
+ started = false;
+ }
public slots:
- virtual void ask(int id, const QCA::Event &e)
- {
- activeIds += id;
- emit q->eventReady(id, e);
- }
+ virtual void ask(int id, const QCA::Event &e)
+ {
+ activeIds += id;
+ emit q->eventReady(id, e);
+ }
};
EventHandler::EventHandler(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
EventHandler::~EventHandler()
{
- if(d->started)
- {
- foreach(int id, d->activeIds)
- handler_reject(d, id);
+ if (d->started) {
+ foreach (int id, d->activeIds) {
+ handler_reject(d, id);
+ }
- handler_remove(d);
- }
+ handler_remove(d);
+ }
- delete d;
+ delete d;
}
void EventHandler::start()
{
- d->started = true;
- handler_add(d);
+ d->started = true;
+ handler_add(d);
}
void EventHandler::submitPassword(int id, const SecureArray &password)
{
- if(!d->activeIds.contains(id))
- return;
+ if (!d->activeIds.contains(id)) {
+ return;
+ }
- d->activeIds.removeAll(id);
- handler_accept(d, id, password);
+ d->activeIds.removeAll(id);
+ handler_accept(d, id, password);
}
void EventHandler::tokenOkay(int id)
{
- if(!d->activeIds.contains(id))
- return;
+ if (!d->activeIds.contains(id)) {
+ return;
+ }
- d->activeIds.removeAll(id);
- handler_accept(d, id, SecureArray());
+ d->activeIds.removeAll(id);
+ handler_accept(d, id, SecureArray());
}
void EventHandler::reject(int id)
{
- if(!d->activeIds.contains(id))
- return;
+ if (!d->activeIds.contains(id)) {
+ return;
+ }
- d->activeIds.removeAll(id);
- handler_reject(d, id);
+ d->activeIds.removeAll(id);
+ handler_reject(d, id);
}
//----------------------------------------------------------------------------
// PasswordAsker
//----------------------------------------------------------------------------
class AskerPrivate : public AskerBase
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum Type { Password, Token };
-
- Type type;
- PasswordAsker *passwordAsker;
- TokenAsker *tokenAsker;
-
- QMutex m;
- QWaitCondition w;
-
- bool accepted;
- SecureArray password;
- bool waiting;
- bool done;
-
- AskerPrivate(PasswordAsker *parent) : AskerBase(parent)
- {
- passwordAsker = parent;
- tokenAsker = 0;
- type = Password;
- accepted = false;
- waiting = false;
- done = true;
- }
-
- AskerPrivate(TokenAsker *parent) : AskerBase(parent)
- {
- passwordAsker = 0;
- tokenAsker = parent;
- type = Token;
- accepted = false;
- waiting = false;
- done = true;
- }
-
- void ask(const Event &e)
- {
- accepted = false;
- waiting = false;
- done = false;
- password.clear();
-
- if(!asker_ask(this, e))
- {
- done = true;
- QMetaObject::invokeMethod(this, "emitResponseReady", Qt::QueuedConnection);
- }
- }
-
- void cancel()
- {
- if(!done)
- asker_cancel(this);
- }
-
- virtual void set_accepted(const SecureArray &_password)
- {
- QMutexLocker locker(&m);
- accepted = true;
- password = _password;
- done = true;
- if(waiting)
- w.wakeOne();
- else
- QMetaObject::invokeMethod(this, "emitResponseReady", Qt::QueuedConnection);
- }
-
- virtual void set_rejected()
- {
- QMutexLocker locker(&m);
- done = true;
- if(waiting)
- w.wakeOne();
- else
- QMetaObject::invokeMethod(this, "emitResponseReady", Qt::QueuedConnection);
- }
-
- void waitForResponse()
- {
- QMutexLocker locker(&m);
- if(done)
- return;
- waiting = true;
- w.wait(&m);
- waiting = false;
- }
+ enum Type { Password, Token };
+
+ Type type;
+ PasswordAsker *passwordAsker;
+ TokenAsker *tokenAsker;
+
+ QMutex m;
+ QWaitCondition w;
+
+ bool accepted;
+ SecureArray password;
+ bool waiting;
+ bool done;
+
+ AskerPrivate(PasswordAsker *parent) : AskerBase(parent)
+ {
+ passwordAsker = parent;
+ tokenAsker = 0;
+ type = Password;
+ accepted = false;
+ waiting = false;
+ done = true;
+ }
+
+ AskerPrivate(TokenAsker *parent) : AskerBase(parent)
+ {
+ passwordAsker = 0;
+ tokenAsker = parent;
+ type = Token;
+ accepted = false;
+ waiting = false;
+ done = true;
+ }
+
+ void ask(const Event &e)
+ {
+ accepted = false;
+ waiting = false;
+ done = false;
+ password.clear();
+
+ if (!asker_ask(this, e)) {
+ done = true;
+ QMetaObject::invokeMethod(this, "emitResponseReady", Qt::QueuedConnection);
+ }
+ }
+
+ void cancel()
+ {
+ if (!done) {
+ asker_cancel(this);
+ }
+ }
+
+ virtual void set_accepted(const SecureArray &_password)
+ {
+ QMutexLocker locker(&m);
+ accepted = true;
+ password = _password;
+ done = true;
+ if (waiting) {
+ w.wakeOne();
+ } else {
+ QMetaObject::invokeMethod(this, "emitResponseReady", Qt::QueuedConnection);
+ }
+ }
+
+ virtual void set_rejected()
+ {
+ QMutexLocker locker(&m);
+ done = true;
+ if (waiting) {
+ w.wakeOne();
+ } else {
+ QMetaObject::invokeMethod(this, "emitResponseReady", Qt::QueuedConnection);
+ }
+ }
+
+ void waitForResponse()
+ {
+ QMutexLocker locker(&m);
+ if (done) {
+ return;
+ }
+ waiting = true;
+ w.wait(&m);
+ waiting = false;
+ }
public slots:
- virtual void emitResponseReady() = 0;
+ virtual void emitResponseReady() = 0;
};
class PasswordAsker::Private : public AskerPrivate
{
public:
- Private(PasswordAsker *_q) : AskerPrivate(_q)
- {
- }
-
- virtual void emitResponseReady()
- {
- emit passwordAsker->responseReady();
- }
+ Private(PasswordAsker *_q) : AskerPrivate(_q)
+ {
+ }
+
+ virtual void emitResponseReady()
+ {
+ emit passwordAsker->responseReady();
+ }
};
PasswordAsker::PasswordAsker(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
PasswordAsker::~PasswordAsker()
{
- delete d;
+ delete d;
}
void PasswordAsker::ask(Event::PasswordStyle pstyle, const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr)
{
- Event e;
- e.setPasswordKeyStore(pstyle, keyStoreInfo, keyStoreEntry, ptr);
- d->ask(e);
+ Event e;
+ e.setPasswordKeyStore(pstyle, keyStoreInfo, keyStoreEntry, ptr);
+ d->ask(e);
}
void PasswordAsker::ask(Event::PasswordStyle pstyle, const QString &fileName, void *ptr)
{
- Event e;
- e.setPasswordData(pstyle, fileName, ptr);
- d->ask(e);
+ Event e;
+ e.setPasswordData(pstyle, fileName, ptr);
+ d->ask(e);
}
void PasswordAsker::cancel()
{
- d->cancel();
+ d->cancel();
}
void PasswordAsker::waitForResponse()
{
- d->waitForResponse();
+ d->waitForResponse();
}
bool PasswordAsker::accepted() const
{
- return d->accepted;
+ return d->accepted;
}
SecureArray PasswordAsker::password() const
{
- return d->password;
+ return d->password;
}
//----------------------------------------------------------------------------
// TokenAsker
//----------------------------------------------------------------------------
class TokenAsker::Private : public AskerPrivate
{
public:
- Private(TokenAsker *_q) : AskerPrivate(_q)
- {
- }
-
- virtual void emitResponseReady()
- {
- emit tokenAsker->responseReady();
- }
+ Private(TokenAsker *_q) : AskerPrivate(_q)
+ {
+ }
+
+ virtual void emitResponseReady()
+ {
+ emit tokenAsker->responseReady();
+ }
};
TokenAsker::TokenAsker(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
TokenAsker::~TokenAsker()
{
- delete d;
+ delete d;
}
void TokenAsker::ask(const KeyStoreInfo &keyStoreInfo, const KeyStoreEntry &keyStoreEntry, void *ptr)
{
- Event e;
- e.setToken(keyStoreInfo, keyStoreEntry, ptr);
- d->ask(e);
+ Event e;
+ e.setToken(keyStoreInfo, keyStoreEntry, ptr);
+ d->ask(e);
}
void TokenAsker::cancel()
{
- d->cancel();
+ d->cancel();
}
void TokenAsker::waitForResponse()
{
- d->waitForResponse();
+ d->waitForResponse();
}
bool TokenAsker::accepted() const
{
- return d->accepted;
+ return d->accepted;
}
}
#include "qca_core.moc"
diff --git a/src/qca_default.cpp b/src/qca_default.cpp
index 0499bbcb..f31d4c82 100644
--- a/src/qca_default.cpp
+++ b/src/qca_default.cpp
@@ -1,1325 +1,1328 @@
/*
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_core.h"
#include <QMutex>
#include "qca_textfilter.h"
#include "qca_cert.h"
#include "qcaprovider.h"
#ifndef QCA_NO_SYSTEMSTORE
# include "qca_systemstore.h"
#endif
#define FRIENDLY_NAMES
-namespace QCA {
+namespace QCA
+{
class DefaultShared
{
private:
- mutable QMutex m;
- bool _use_system;
- QString _roots_file;
- QStringList _skip_plugins;
- QStringList _plugin_priorities;
+ mutable QMutex m;
+ bool _use_system;
+ QString _roots_file;
+ QStringList _skip_plugins;
+ QStringList _plugin_priorities;
public:
- DefaultShared() : _use_system(true)
- {
- }
-
- bool use_system() const
- {
- QMutexLocker locker(&m);
- return _use_system;
- }
-
- QString roots_file() const
- {
- QMutexLocker locker(&m);
- return _roots_file;
- }
-
- QStringList skip_plugins() const
- {
- QMutexLocker locker(&m);
- return _skip_plugins;
- }
-
- QStringList plugin_priorities() const
- {
- QMutexLocker locker(&m);
- return _plugin_priorities;
- }
-
- void set(bool use_system, const QString &roots_file, const QStringList &skip_plugins, const QStringList &plugin_priorities)
- {
- QMutexLocker locker(&m);
- _use_system = use_system;
- _roots_file = roots_file;
- _skip_plugins = skip_plugins;
- _plugin_priorities = plugin_priorities;
- }
+ DefaultShared() : _use_system(true)
+ {
+ }
+
+ bool use_system() const
+ {
+ QMutexLocker locker(&m);
+ return _use_system;
+ }
+
+ QString roots_file() const
+ {
+ QMutexLocker locker(&m);
+ return _roots_file;
+ }
+
+ QStringList skip_plugins() const
+ {
+ QMutexLocker locker(&m);
+ return _skip_plugins;
+ }
+
+ QStringList plugin_priorities() const
+ {
+ QMutexLocker locker(&m);
+ return _plugin_priorities;
+ }
+
+ void set(bool use_system, const QString &roots_file, const QStringList &skip_plugins, const QStringList &plugin_priorities)
+ {
+ QMutexLocker locker(&m);
+ _use_system = use_system;
+ _roots_file = roots_file;
+ _skip_plugins = skip_plugins;
+ _plugin_priorities = plugin_priorities;
+ }
};
//----------------------------------------------------------------------------
// DefaultRandomContext
//----------------------------------------------------------------------------
class DefaultRandomContext : public RandomContext
{
public:
- DefaultRandomContext(Provider *p) : RandomContext(p) {}
-
- virtual Provider::Context *clone() const
- {
- return new DefaultRandomContext(provider());
- }
-
- virtual SecureArray nextBytes(int size)
- {
- SecureArray buf(size);
- for(int n = 0; n < (int)buf.size(); ++n)
- buf[n] = (char)qrand();
- return buf;
- }
+ DefaultRandomContext(Provider *p) : RandomContext(p) {}
+
+ virtual Provider::Context *clone() const
+ {
+ return new DefaultRandomContext(provider());
+ }
+
+ virtual SecureArray nextBytes(int size)
+ {
+ SecureArray buf(size);
+ for (int n = 0; n < (int)buf.size(); ++n) {
+ buf[n] = (char)qrand();
+ }
+ return buf;
+ }
};
//----------------------------------------------------------------------------
// DefaultMD5Context
//----------------------------------------------------------------------------
/* NOTE: the following code was modified to not need BYTE_ORDER -- Justin */
/*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/* $Id$ */
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
- http://www.ietf.org/rfc/rfc1321.txt
+ http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
- either statically or dynamically; added missing #include <string.h>
- in library.
+ either statically or dynamically; added missing #include <string.h>
+ in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
- type, in test program and T value program.
+ type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
- unsigned in ANSI C, signed in traditional"; made test program
- self-checking.
+ unsigned in ANSI C, signed in traditional"; made test program
+ self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
/*
* This package supports both compile-time and run-time determination of CPU
* byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
* compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
* defined as non-zero, the code will be compiled to run only on big-endian
* CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
* run on either big- or little-endian CPUs, but will run slightly less
* efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
*/
typedef quint8 md5_byte_t; /* 8-bit byte */
typedef quint32 md5_word_t; /* 32-bit word */
/* Define the state of the MD5 Algorithm. */
struct md5_state_t {
md5_word_t count[2]; // 2 /* message length in bits, lsw first */
md5_word_t abcd[4]; // 4 /* digest buffer */
md5_byte_t buf[64]; // 64 /* accumulate block */
md5_state_t()
{
memset(count, 0, 2 * sizeof(md5_word_t));
memset(abcd, 0, 4 * sizeof(md5_word_t));
memset(buf, 0, 64 * sizeof(md5_byte_t));
}
md5_state_t(const md5_state_t &from)
{
*this = from;
}
- md5_state_t & operator=(const md5_state_t &from)
+ md5_state_t &operator=(const md5_state_t &from)
{
*this = from;
return *this;
}
};
/* Initialize the algorithm. */
void md5_init(md5_state_t *pms);
/* Append a string to the message. */
void md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes);
/* Finish the message and return the digest. */
void md5_finish(md5_state_t *pms, md5_byte_t digest[16]);
#define T_MASK ((md5_word_t)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
-
static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
- md5_word_t
- a = pms->abcd[0], b = pms->abcd[1],
- c = pms->abcd[2], d = pms->abcd[3];
- md5_word_t t;
-
- /* Define storage for little-endian or both types of CPUs. */
- md5_word_t xbuf[16];
- const md5_word_t *X;
-
- {
- if(QSysInfo::ByteOrder == QSysInfo::BigEndian)
- {
- /*
- * On big-endian machines, we must arrange the bytes in the
- * right order.
- */
- const md5_byte_t *xp = data;
- int i;
-
- X = xbuf; /* (dynamic only) */
-
- for (i = 0; i < 16; ++i, xp += 4)
- xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
- }
- else /* dynamic big-endian */
- {
- /*
- * On little-endian machines, we can process properly aligned
- * data without copying it. On arm do copying always
- */
+ md5_word_t
+ a = pms->abcd[0], b = pms->abcd[1],
+ c = pms->abcd[2], d = pms->abcd[3];
+ md5_word_t t;
+
+ /* Define storage for little-endian or both types of CPUs. */
+ md5_word_t xbuf[16];
+ const md5_word_t *X;
+
+ {
+ if (QSysInfo::ByteOrder == QSysInfo::BigEndian) {
+ /*
+ * On big-endian machines, we must arrange the bytes in the
+ * right order.
+ */
+ const md5_byte_t *xp = data;
+ int i;
+
+ X = xbuf; /* (dynamic only) */
+
+ for (i = 0; i < 16; ++i, xp += 4) {
+ xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
+ }
+ } else { /* dynamic big-endian */
+ /*
+ * On little-endian machines, we can process properly aligned
+ * data without copying it. On arm do copying always
+ */
#ifndef Q_PROCESSOR_ARM
- if (!((data - static_cast<const md5_byte_t*>(0)) & 3)) {
- /* data are properly aligned */
- X = reinterpret_cast<const md5_word_t*>(data);
- } else
+ if (!((data - static_cast<const md5_byte_t *>(0)) & 3)) {
+ /* data are properly aligned */
+ X = reinterpret_cast<const md5_word_t *>(data);
+ } else
#endif
- {
- /* not aligned */
- memcpy(xbuf, data, 64);
- X = xbuf;
- }
- }
- }
+ {
+ /* not aligned */
+ memcpy(xbuf, data, 64);
+ X = xbuf;
+ }
+ }
+ }
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti)\
- t = a + F(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
+ t = a + F(b,c,d) + X[k] + Ti;\
+ a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
- /* Round 2. */
- /* Let [abcd k s i] denote the operation
- a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
+ /* Round 2. */
+ /* Let [abcd k s i] denote the operation
+ a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
- t = a + G(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
+ t = a + G(b,c,d) + X[k] + Ti;\
+ a = ROTATE_LEFT(t, s) + b
+ /* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
- /* Round 3. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
+ /* Round 3. */
+ /* Let [abcd k s t] denote the operation
+ a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti)\
- t = a + H(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
+ t = a + H(b,c,d) + X[k] + Ti;\
+ a = ROTATE_LEFT(t, s) + b
+ /* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
- /* Round 4. */
- /* Let [abcd k s t] denote the operation
- a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
+ /* Round 4. */
+ /* Let [abcd k s t] denote the operation
+ a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
- t = a + I(b,c,d) + X[k] + Ti;\
- a = ROTATE_LEFT(t, s) + b
- /* Do the following 16 operations. */
+ t = a + I(b,c,d) + X[k] + Ti;\
+ a = ROTATE_LEFT(t, s) + b
+ /* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
- /* Then perform the following additions. (That is increment each
- of the four registers by the value it had before this block
- was started.) */
+ /* Then perform the following additions. (That is increment each
+ of the four registers by the value it had before this block
+ was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
void
md5_init(md5_state_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
pms->abcd[3] = 0x10325476;
}
void
md5_append(md5_state_t *pms, const md5_byte_t *data, int nbytes)
{
const md5_byte_t *p = data;
int left = nbytes;
int offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t)(nbytes << 3);
- if (nbytes <= 0)
- return;
+ if (nbytes <= 0) {
+ return;
+ }
/* Update the message length. */
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
- if (pms->count[0] < nbits)
- pms->count[1]++;
+ if (pms->count[0] < nbits) {
+ pms->count[1]++;
+ }
/* Process an initial partial block. */
if (offset) {
- int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
- memcpy(pms->buf + offset, p, copy);
- if (offset + copy < 64)
- return;
- p += copy;
- left -= copy;
- md5_process(pms, pms->buf);
+ int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+
+ memcpy(pms->buf + offset, p, copy);
+ if (offset + copy < 64) {
+ return;
+ }
+ p += copy;
+ left -= copy;
+ md5_process(pms, pms->buf);
}
/* Process full blocks. */
- for (; left >= 64; p += 64, left -= 64)
- md5_process(pms, p);
+ for (; left >= 64; p += 64, left -= 64) {
+ md5_process(pms, p);
+ }
/* Process a final partial block. */
- if (left)
- memcpy(pms->buf, p, left);
+ if (left) {
+ memcpy(pms->buf, p, left);
+ }
}
void
md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
- 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
- for (i = 0; i < 8; ++i)
- data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+ for (i = 0; i < 8; ++i) {
+ data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+ }
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
- for (i = 0; i < 16; ++i)
- digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+ for (i = 0; i < 16; ++i) {
+ digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+ }
}
class DefaultMD5Context : public HashContext
{
public:
- DefaultMD5Context(Provider *p) : HashContext(p, "md5")
- {
- clear();
- }
-
- virtual Provider::Context *clone() const
- {
- return new DefaultMD5Context(*this);
- }
-
- virtual void clear()
- {
- secure = true;
- md5_init(&md5);
- }
-
- virtual void update(const MemoryRegion &in)
- {
- if(!in.isSecure())
- secure = false;
- md5_append(&md5, (const md5_byte_t *)in.data(), in.size());
- }
-
- virtual MemoryRegion final()
- {
- if(secure)
- {
- SecureArray b(16, 0);
- md5_finish(&md5, (md5_byte_t *)b.data());
- return b;
- }
- else
- {
- QByteArray b(16, 0);
- md5_finish(&md5, (md5_byte_t *)b.data());
- return b;
- }
- }
-
- bool secure;
- md5_state_t md5;
+ DefaultMD5Context(Provider *p) : HashContext(p, "md5")
+ {
+ clear();
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new DefaultMD5Context(*this);
+ }
+
+ virtual void clear()
+ {
+ secure = true;
+ md5_init(&md5);
+ }
+
+ virtual void update(const MemoryRegion &in)
+ {
+ if (!in.isSecure()) {
+ secure = false;
+ }
+ md5_append(&md5, (const md5_byte_t *)in.data(), in.size());
+ }
+
+ virtual MemoryRegion final()
+ {
+ if (secure) {
+ SecureArray b(16, 0);
+ md5_finish(&md5, (md5_byte_t *)b.data());
+ return b;
+ } else {
+ QByteArray b(16, 0);
+ md5_finish(&md5, (md5_byte_t *)b.data());
+ return b;
+ }
+ }
+
+ bool secure;
+ md5_state_t md5;
};
//----------------------------------------------------------------------------
// DefaultSHA1Context
//----------------------------------------------------------------------------
// SHA1 - from a public domain implementation by Steve Reid (steve@edmweb.com)
#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
#ifdef Q_PROCESSOR_ARM
#define blk(i) (block.l[i&15] = rol(block.l[(i+13)&15]^block.l[(i+8)&15]^block.l[(i+2)&15]^block.l[i&15],1))
#else
#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15]^block->l[(i+2)&15]^block->l[i&15],1))
#endif
/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
-struct SHA1_CONTEXT
-{
- quint32 state[5]; // 5
- quint32 count[2]; // 2
- unsigned char buffer[64]; // 64
-
- SHA1_CONTEXT()
- {
- memset(state, 0, 5 * sizeof(quint32));
- memset(count, 0, 2 * sizeof(quint32));
- memset(buffer, 0, 64 * sizeof(unsigned char));
- }
-
- SHA1_CONTEXT(const SHA1_CONTEXT &from)
- {
- *this = from;
- }
-
- SHA1_CONTEXT & operator=(const SHA1_CONTEXT &from)
- {
- *this = from;
- return *this;
- }
+struct SHA1_CONTEXT {
+ quint32 state[5]; // 5
+ quint32 count[2]; // 2
+ unsigned char buffer[64]; // 64
+
+ SHA1_CONTEXT()
+ {
+ memset(state, 0, 5 * sizeof(quint32));
+ memset(count, 0, 2 * sizeof(quint32));
+ memset(buffer, 0, 64 * sizeof(unsigned char));
+ }
+
+ SHA1_CONTEXT(const SHA1_CONTEXT &from)
+ {
+ *this = from;
+ }
+
+ SHA1_CONTEXT &operator=(const SHA1_CONTEXT &from)
+ {
+ *this = from;
+ return *this;
+ }
};
typedef union {
- unsigned char c[64];
- quint32 l[16];
+ unsigned char c[64];
+ quint32 l[16];
} CHAR64LONG16;
class DefaultSHA1Context : public HashContext
{
public:
- SHA1_CONTEXT _context;
+ SHA1_CONTEXT _context;
#ifdef Q_PROCESSOR_ARM
- CHAR64LONG16 block;
+ CHAR64LONG16 block;
#else
- CHAR64LONG16 *block;
+ CHAR64LONG16 *block;
#endif
- bool secure;
-
- DefaultSHA1Context(Provider *p) : HashContext(p, "sha1")
- {
- clear();
- }
-
- virtual Provider::Context *clone() const
- {
- return new DefaultSHA1Context(*this);
- }
-
- virtual void clear()
- {
- secure = true;
- sha1_init(&_context);
- }
-
- virtual void update(const MemoryRegion &in)
- {
- if(!in.isSecure())
- secure = false;
- sha1_update(&_context, (unsigned char *)in.data(), (unsigned int)in.size());
- }
-
- virtual MemoryRegion final()
- {
- if(secure)
- {
- SecureArray b(20, 0);
- sha1_final((unsigned char *)b.data(), &_context);
- return b;
- }
- else
- {
- QByteArray b(20, 0);
- sha1_final((unsigned char *)b.data(), &_context);
- return b;
- }
- }
-
- inline unsigned long blk0(quint32 i)
- {
- if(QSysInfo::ByteOrder == QSysInfo::BigEndian)
+ bool secure;
+
+ DefaultSHA1Context(Provider *p) : HashContext(p, "sha1")
+ {
+ clear();
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new DefaultSHA1Context(*this);
+ }
+
+ virtual void clear()
+ {
+ secure = true;
+ sha1_init(&_context);
+ }
+
+ virtual void update(const MemoryRegion &in)
+ {
+ if (!in.isSecure()) {
+ secure = false;
+ }
+ sha1_update(&_context, (unsigned char *)in.data(), (unsigned int)in.size());
+ }
+
+ virtual MemoryRegion final()
+ {
+ if (secure) {
+ SecureArray b(20, 0);
+ sha1_final((unsigned char *)b.data(), &_context);
+ return b;
+ } else {
+ QByteArray b(20, 0);
+ sha1_final((unsigned char *)b.data(), &_context);
+ return b;
+ }
+ }
+
+ inline unsigned long blk0(quint32 i)
+ {
+ if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
#ifdef Q_PROCESSOR_ARM
- return block.l[i];
+ return block.l[i];
#else
- return block->l[i];
+ return block->l[i];
#endif
- else
+ else
#ifdef Q_PROCESSOR_ARM
- return (block.l[i] = (rol(block.l[i],24)&0xFF00FF00) | (rol(block.l[i],8)&0x00FF00FF));
+ return (block.l[i] = (rol(block.l[i], 24) & 0xFF00FF00) | (rol(block.l[i], 8) & 0x00FF00FF));
#else
- return (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) | (rol(block->l[i],8)&0x00FF00FF));
+ return (block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) | (rol(block->l[i], 8) & 0x00FF00FF));
#endif
- }
+ }
- // Hash a single 512-bit block. This is the core of the algorithm.
- void transform(quint32 state[5], unsigned char buffer[64])
- {
- quint32 a, b, c, d, e;
+ // Hash a single 512-bit block. This is the core of the algorithm.
+ void transform(quint32 state[5], unsigned char buffer[64])
+ {
+ quint32 a, b, c, d, e;
#ifdef Q_PROCESSOR_ARM
- memcpy(&block, buffer, sizeof(block));
+ memcpy(&block, buffer, sizeof(block));
#else
- block = reinterpret_cast<CHAR64LONG16*>(buffer);
+ block = reinterpret_cast<CHAR64LONG16 *>(buffer);
#endif
- // Copy context->state[] to working vars
- a = state[0];
- b = state[1];
- c = state[2];
- d = state[3];
- e = state[4];
-
- // 4 rounds of 20 operations each. Loop unrolled.
- R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
- R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
- R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
- R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
- R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
- R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
- R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
- R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
- R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
- R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
- R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
- R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
- R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
- R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
- R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
- R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
- R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
- R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
- R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
- R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
-
- // Add the working vars back into context.state[]
- state[0] += a;
- state[1] += b;
- state[2] += c;
- state[3] += d;
- state[4] += e;
-
- // Wipe variables
- a = b = c = d = e = 0;
- }
-
- // SHA1Init - Initialize new context
- void sha1_init(SHA1_CONTEXT* context)
- {
- // SHA1 initialization constants
- context->state[0] = 0x67452301;
- context->state[1] = 0xEFCDAB89;
- context->state[2] = 0x98BADCFE;
- context->state[3] = 0x10325476;
- context->state[4] = 0xC3D2E1F0;
- context->count[0] = context->count[1] = 0;
- }
-
- // Run your data through this
- void sha1_update(SHA1_CONTEXT* context, unsigned char* data, quint32 len)
- {
- quint32 i, j;
-
- j = (context->count[0] >> 3) & 63;
- if((context->count[0] += len << 3) < (len << 3))
- context->count[1]++;
-
- context->count[1] += (len >> 29);
-
- if((j + len) > 63) {
- memcpy(&context->buffer[j], data, (i = 64-j));
- transform(context->state, context->buffer);
- for ( ; i + 63 < len; i += 64) {
- transform(context->state, &data[i]);
- }
- j = 0;
- }
- else i = 0;
- memcpy(&context->buffer[j], &data[i], len - i);
- }
-
- // Add padding and return the message digest
- void sha1_final(unsigned char digest[20], SHA1_CONTEXT* context)
- {
- quint32 i;
- unsigned char finalcount[8];
-
- for (i = 0; i < 8; i++) {
- finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
- >> ((3-(i & 3)) * 8) ) & 255); // Endian independent
- }
- sha1_update(context, (unsigned char *)"\200", 1);
- while ((context->count[0] & 504) != 448) {
- sha1_update(context, (unsigned char *)"\0", 1);
- }
- sha1_update(context, finalcount, 8); // Should cause a transform()
- for (i = 0; i < 20; i++) {
- digest[i] = (unsigned char) ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
- }
-
- // Wipe variables
- i = 0;
- memset(context->buffer, 0, 64);
- memset(context->state, 0, 20);
- memset(context->count, 0, 8);
- memset(&finalcount, 0, 8);
- }
+ // Copy context->state[] to working vars
+ a = state[0];
+ b = state[1];
+ c = state[2];
+ d = state[3];
+ e = state[4];
+
+ // 4 rounds of 20 operations each. Loop unrolled.
+ R0(a, b, c, d, e, 0); R0(e, a, b, c, d, 1); R0(d, e, a, b, c, 2); R0(c, d, e, a, b, 3);
+ R0(b, c, d, e, a, 4); R0(a, b, c, d, e, 5); R0(e, a, b, c, d, 6); R0(d, e, a, b, c, 7);
+ R0(c, d, e, a, b, 8); R0(b, c, d, e, a, 9); R0(a, b, c, d, e, 10); R0(e, a, b, c, d, 11);
+ R0(d, e, a, b, c, 12); R0(c, d, e, a, b, 13); R0(b, c, d, e, a, 14); R0(a, b, c, d, e, 15);
+ R1(e, a, b, c, d, 16); R1(d, e, a, b, c, 17); R1(c, d, e, a, b, 18); R1(b, c, d, e, a, 19);
+ R2(a, b, c, d, e, 20); R2(e, a, b, c, d, 21); R2(d, e, a, b, c, 22); R2(c, d, e, a, b, 23);
+ R2(b, c, d, e, a, 24); R2(a, b, c, d, e, 25); R2(e, a, b, c, d, 26); R2(d, e, a, b, c, 27);
+ R2(c, d, e, a, b, 28); R2(b, c, d, e, a, 29); R2(a, b, c, d, e, 30); R2(e, a, b, c, d, 31);
+ R2(d, e, a, b, c, 32); R2(c, d, e, a, b, 33); R2(b, c, d, e, a, 34); R2(a, b, c, d, e, 35);
+ R2(e, a, b, c, d, 36); R2(d, e, a, b, c, 37); R2(c, d, e, a, b, 38); R2(b, c, d, e, a, 39);
+ R3(a, b, c, d, e, 40); R3(e, a, b, c, d, 41); R3(d, e, a, b, c, 42); R3(c, d, e, a, b, 43);
+ R3(b, c, d, e, a, 44); R3(a, b, c, d, e, 45); R3(e, a, b, c, d, 46); R3(d, e, a, b, c, 47);
+ R3(c, d, e, a, b, 48); R3(b, c, d, e, a, 49); R3(a, b, c, d, e, 50); R3(e, a, b, c, d, 51);
+ R3(d, e, a, b, c, 52); R3(c, d, e, a, b, 53); R3(b, c, d, e, a, 54); R3(a, b, c, d, e, 55);
+ R3(e, a, b, c, d, 56); R3(d, e, a, b, c, 57); R3(c, d, e, a, b, 58); R3(b, c, d, e, a, 59);
+ R4(a, b, c, d, e, 60); R4(e, a, b, c, d, 61); R4(d, e, a, b, c, 62); R4(c, d, e, a, b, 63);
+ R4(b, c, d, e, a, 64); R4(a, b, c, d, e, 65); R4(e, a, b, c, d, 66); R4(d, e, a, b, c, 67);
+ R4(c, d, e, a, b, 68); R4(b, c, d, e, a, 69); R4(a, b, c, d, e, 70); R4(e, a, b, c, d, 71);
+ R4(d, e, a, b, c, 72); R4(c, d, e, a, b, 73); R4(b, c, d, e, a, 74); R4(a, b, c, d, e, 75);
+ R4(e, a, b, c, d, 76); R4(d, e, a, b, c, 77); R4(c, d, e, a, b, 78); R4(b, c, d, e, a, 79);
+
+ // Add the working vars back into context.state[]
+ state[0] += a;
+ state[1] += b;
+ state[2] += c;
+ state[3] += d;
+ state[4] += e;
+
+ // Wipe variables
+ a = b = c = d = e = 0;
+ }
+
+ // SHA1Init - Initialize new context
+ void sha1_init(SHA1_CONTEXT *context)
+ {
+ // SHA1 initialization constants
+ context->state[0] = 0x67452301;
+ context->state[1] = 0xEFCDAB89;
+ context->state[2] = 0x98BADCFE;
+ context->state[3] = 0x10325476;
+ context->state[4] = 0xC3D2E1F0;
+ context->count[0] = context->count[1] = 0;
+ }
+
+ // Run your data through this
+ void sha1_update(SHA1_CONTEXT *context, unsigned char *data, quint32 len)
+ {
+ quint32 i, j;
+
+ j = (context->count[0] >> 3) & 63;
+ if ((context->count[0] += len << 3) < (len << 3)) {
+ context->count[1]++;
+ }
+
+ context->count[1] += (len >> 29);
+
+ if ((j + len) > 63) {
+ memcpy(&context->buffer[j], data, (i = 64 - j));
+ transform(context->state, context->buffer);
+ for (; i + 63 < len; i += 64) {
+ transform(context->state, &data[i]);
+ }
+ j = 0;
+ } else {
+ i = 0;
+ }
+ memcpy(&context->buffer[j], &data[i], len - i);
+ }
+
+ // Add padding and return the message digest
+ void sha1_final(unsigned char digest[20], SHA1_CONTEXT *context)
+ {
+ quint32 i;
+ unsigned char finalcount[8];
+
+ for (i = 0; i < 8; i++) {
+ finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
+ >> ((3 - (i & 3)) * 8)) & 255); // Endian independent
+ }
+ sha1_update(context, (unsigned char *)"\200", 1);
+ while ((context->count[0] & 504) != 448) {
+ sha1_update(context, (unsigned char *)"\0", 1);
+ }
+ sha1_update(context, finalcount, 8); // Should cause a transform()
+ for (i = 0; i < 20; i++) {
+ digest[i] = (unsigned char)((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
+ }
+
+ // Wipe variables
+ i = 0;
+ memset(context->buffer, 0, 64);
+ memset(context->state, 0, 20);
+ memset(context->count, 0, 8);
+ memset(&finalcount, 0, 8);
+ }
};
//----------------------------------------------------------------------------
// DefaultKeyStoreEntry
//----------------------------------------------------------------------------
// this escapes colons, commas, and newlines. colons and commas so that they
// are available as delimiters, and newlines so that our output can be a
// single line of text.
static QString escape_string(const QString &in)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- out += "\\\\";
- else if(in[n] == ':')
- out += "\\c";
- else if(in[n] == ',')
- out += "\\o";
- else if(in[n] == '\n')
- out += "\\n";
- else
- out += in[n];
- }
- return out;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ out += "\\\\";
+ } else if (in[n] == ':') {
+ out += "\\c";
+ } else if (in[n] == ',') {
+ out += "\\o";
+ } else if (in[n] == '\n') {
+ out += "\\n";
+ } else {
+ out += in[n];
+ }
+ }
+ return out;
}
static bool unescape_string(const QString &in, QString *_out)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- {
- if(n + 1 >= in.length())
- return false;
-
- if(in[n + 1] == '\\')
- out += '\\';
- else if(in[n + 1] == 'c')
- out += ':';
- else if(in[n + 1] == 'o')
- out += ',';
- else if(in[n + 1] == 'n')
- out += '\n';
- else
- return false;
- ++n;
- }
- else
- out += in[n];
- }
- *_out = out;
- return true;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ if (n + 1 >= in.length()) {
+ return false;
+ }
+
+ if (in[n + 1] == '\\') {
+ out += '\\';
+ } else if (in[n + 1] == 'c') {
+ out += ':';
+ } else if (in[n + 1] == 'o') {
+ out += ',';
+ } else if (in[n + 1] == 'n') {
+ out += '\n';
+ } else {
+ return false;
+ }
+ ++n;
+ } else {
+ out += in[n];
+ }
+ }
+ *_out = out;
+ return true;
}
static QString escape_stringlist(const QStringList &in)
{
- QStringList list;
- for(int n = 0; n < in.count(); ++n)
- list += escape_string(in[n]);
- return list.join(":");
+ QStringList list;
+ for (int n = 0; n < in.count(); ++n) {
+ list += escape_string(in[n]);
+ }
+ return list.join(":");
}
static bool unescape_stringlist(const QString &in, QStringList *_out)
{
- QStringList out;
- QStringList list = in.split(':');
- for(int n = 0; n < list.count(); ++n)
- {
- QString str;
- if(!unescape_string(list[n], &str))
- return false;
- out += str;
- }
- *_out = out;
- return true;
+ QStringList out;
+ QStringList list = in.split(':');
+ for (int n = 0; n < list.count(); ++n) {
+ QString str;
+ if (!unescape_string(list[n], &str)) {
+ return false;
+ }
+ out += str;
+ }
+ *_out = out;
+ return true;
}
// serialization format is a colon separated list of 7 escaped strings
// 0 - "qca_def_1" (header)
// 1 - store id
// 2 - store name
// 3 - entry id
// 4 - entry name
// 5 - entry type (e.g. "cert")
// 6 - string encoding of object (e.g. DER encoded in Base64)
static QString entry_serialize(const QString &storeId, const QString &storeName, const QString &entryId, const QString &entryName, const QString &entryType, const QString &data)
{
- QStringList out;
- out += "qca_def";
- out += storeId;
- out += storeName;
- out += entryId;
- out += entryName;
- out += entryType;
- out += data;
- return escape_stringlist(out);
+ QStringList out;
+ out += "qca_def";
+ out += storeId;
+ out += storeName;
+ out += entryId;
+ out += entryName;
+ out += entryType;
+ out += data;
+ return escape_stringlist(out);
}
static bool entry_deserialize(const QString &in, QString *storeId, QString *storeName, QString *entryId, QString *entryName, QString *entryType, QString *data)
{
- QStringList list;
- if(!unescape_stringlist(in, &list))
- return false;
- if(list.count() != 7)
- return false;
- if(list[0] != "qca_def")
- return false;
- *storeId = list[1];
- *storeName = list[2];
- *entryId = list[3];
- *entryName = list[4];
- *entryType = list[5];
- *data = list[6];
- return true;
+ QStringList list;
+ if (!unescape_stringlist(in, &list)) {
+ return false;
+ }
+ if (list.count() != 7) {
+ return false;
+ }
+ if (list[0] != "qca_def") {
+ return false;
+ }
+ *storeId = list[1];
+ *storeName = list[2];
+ *entryId = list[3];
+ *entryName = list[4];
+ *entryType = list[5];
+ *data = list[6];
+ return true;
}
class DefaultKeyStoreEntry : public KeyStoreEntryContext
{
public:
- KeyStoreEntry::Type _type;
- QString _id, _name, _storeId, _storeName;
- Certificate _cert;
- CRL _crl;
- mutable QString _serialized;
-
- DefaultKeyStoreEntry(const Certificate &cert, const QString &storeId, const QString &storeName, Provider *p) : KeyStoreEntryContext(p)
- {
- _type = KeyStoreEntry::TypeCertificate;
- _storeId = storeId;
- _storeName = storeName;
- _cert = cert;
- }
-
- DefaultKeyStoreEntry(const CRL &crl, const QString &storeId, const QString &storeName, Provider *p) : KeyStoreEntryContext(p)
- {
- _type = KeyStoreEntry::TypeCRL;
- _storeId = storeId;
- _storeName = storeName;
- _crl = crl;
- }
-
- virtual Provider::Context *clone() const
- {
- return new DefaultKeyStoreEntry(*this);
- }
-
- virtual KeyStoreEntry::Type type() const
- {
- return _type;
- }
-
- virtual QString id() const
- {
- return _id;
- }
-
- virtual QString name() const
- {
- return _name;
- }
-
- virtual QString storeId() const
- {
- return _storeId;
- }
-
- virtual QString storeName() const
- {
- return _storeName;
- }
-
- virtual Certificate certificate() const
- {
- return _cert;
- }
-
- virtual CRL crl() const
- {
- return _crl;
- }
-
- virtual QString serialize() const
- {
- if(_serialized.isEmpty())
- {
- QString typestr;
- QString datastr;
-
- if(_type == KeyStoreEntry::TypeCertificate)
- {
- typestr = "cert";
- datastr = Base64().arrayToString(_cert.toDER());
- }
- else
- {
- typestr = "crl";
- datastr = Base64().arrayToString(_crl.toDER());
- }
-
- _serialized = entry_serialize(_storeId, _storeName, _id, _name, typestr, datastr);
- }
-
- return _serialized;
- }
-
- static DefaultKeyStoreEntry *deserialize(const QString &in, Provider *provider)
- {
- QString storeId, storeName, id, name, typestr, datastr;
-
- if(entry_deserialize(in, &storeId, &storeName, &id, &name, &typestr, &datastr))
- {
- QByteArray data = Base64().stringToArray(datastr).toByteArray();
- DefaultKeyStoreEntry *c;
-
- if(typestr == "cert")
- {
- Certificate cert = Certificate::fromDER(data);
- if(cert.isNull())
- return 0;
- c = new DefaultKeyStoreEntry(cert, storeId, storeName, provider);
- }
- else if(typestr == "crl")
- {
- CRL crl = CRL::fromDER(data);
- if(crl.isNull())
- return 0;
- c = new DefaultKeyStoreEntry(crl, storeId, storeName, provider);
- }
- else
- return 0;
-
- c->_id = id;
- c->_name = name;
- c->_serialized = in;
- return c;
- }
- return 0;
- }
-
- QString simpleId() const
- {
- if(_type == KeyStoreEntry::TypeCertificate)
- return QString::number(qHash(_cert.toDER()));
- else
- return QString::number(qHash(_crl.toDER()));
- }
-
- QString simpleName() const
- {
- // use the common name, else orgname
- if(_type == KeyStoreEntry::TypeCertificate)
- {
- QString str = _cert.commonName();
- if(str.isEmpty())
- str = _cert.subjectInfo().value(Organization);
- return str;
- }
- else
- return _crl.issuerInfo().value(CommonName);
- }
+ KeyStoreEntry::Type _type;
+ QString _id, _name, _storeId, _storeName;
+ Certificate _cert;
+ CRL _crl;
+ mutable QString _serialized;
+
+ DefaultKeyStoreEntry(const Certificate &cert, const QString &storeId, const QString &storeName, Provider *p) : KeyStoreEntryContext(p)
+ {
+ _type = KeyStoreEntry::TypeCertificate;
+ _storeId = storeId;
+ _storeName = storeName;
+ _cert = cert;
+ }
+
+ DefaultKeyStoreEntry(const CRL &crl, const QString &storeId, const QString &storeName, Provider *p) : KeyStoreEntryContext(p)
+ {
+ _type = KeyStoreEntry::TypeCRL;
+ _storeId = storeId;
+ _storeName = storeName;
+ _crl = crl;
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return new DefaultKeyStoreEntry(*this);
+ }
+
+ virtual KeyStoreEntry::Type type() const
+ {
+ return _type;
+ }
+
+ virtual QString id() const
+ {
+ return _id;
+ }
+
+ virtual QString name() const
+ {
+ return _name;
+ }
+
+ virtual QString storeId() const
+ {
+ return _storeId;
+ }
+
+ virtual QString storeName() const
+ {
+ return _storeName;
+ }
+
+ virtual Certificate certificate() const
+ {
+ return _cert;
+ }
+
+ virtual CRL crl() const
+ {
+ return _crl;
+ }
+
+ virtual QString serialize() const
+ {
+ if (_serialized.isEmpty()) {
+ QString typestr;
+ QString datastr;
+
+ if (_type == KeyStoreEntry::TypeCertificate) {
+ typestr = "cert";
+ datastr = Base64().arrayToString(_cert.toDER());
+ } else {
+ typestr = "crl";
+ datastr = Base64().arrayToString(_crl.toDER());
+ }
+
+ _serialized = entry_serialize(_storeId, _storeName, _id, _name, typestr, datastr);
+ }
+
+ return _serialized;
+ }
+
+ static DefaultKeyStoreEntry *deserialize(const QString &in, Provider *provider)
+ {
+ QString storeId, storeName, id, name, typestr, datastr;
+
+ if (entry_deserialize(in, &storeId, &storeName, &id, &name, &typestr, &datastr)) {
+ QByteArray data = Base64().stringToArray(datastr).toByteArray();
+ DefaultKeyStoreEntry *c;
+
+ if (typestr == "cert") {
+ Certificate cert = Certificate::fromDER(data);
+ if (cert.isNull()) {
+ return 0;
+ }
+ c = new DefaultKeyStoreEntry(cert, storeId, storeName, provider);
+ } else if (typestr == "crl") {
+ CRL crl = CRL::fromDER(data);
+ if (crl.isNull()) {
+ return 0;
+ }
+ c = new DefaultKeyStoreEntry(crl, storeId, storeName, provider);
+ } else {
+ return 0;
+ }
+
+ c->_id = id;
+ c->_name = name;
+ c->_serialized = in;
+ return c;
+ }
+ return 0;
+ }
+
+ QString simpleId() const
+ {
+ if (_type == KeyStoreEntry::TypeCertificate) {
+ return QString::number(qHash(_cert.toDER()));
+ } else {
+ return QString::number(qHash(_crl.toDER()));
+ }
+ }
+
+ QString simpleName() const
+ {
+ // use the common name, else orgname
+ if (_type == KeyStoreEntry::TypeCertificate) {
+ QString str = _cert.commonName();
+ if (str.isEmpty()) {
+ str = _cert.subjectInfo().value(Organization);
+ }
+ return str;
+ } else {
+ return _crl.issuerInfo().value(CommonName);
+ }
+ }
};
//----------------------------------------------------------------------------
// DefaultKeyStoreList
//----------------------------------------------------------------------------
class DefaultKeyStoreList : public KeyStoreListContext
{
- Q_OBJECT
+ Q_OBJECT
public:
- bool x509_supported;
- DefaultShared *shared;
-
- DefaultKeyStoreList(Provider *p, DefaultShared *_shared) : KeyStoreListContext(p), shared(_shared)
- {
- }
-
- ~DefaultKeyStoreList()
- {
- }
-
- virtual Provider::Context *clone() const
- {
- return 0;
- }
-
- virtual void start()
- {
- x509_supported = false;
-
- QMetaObject::invokeMethod(this, "busyEnd", Qt::QueuedConnection);
- }
-
- virtual QList<int> keyStores()
- {
- if(!x509_supported)
- {
- if(isSupported("cert") && isSupported("crl"))
- x509_supported = true;
- }
-
- bool have_systemstore = false;
+ bool x509_supported;
+ DefaultShared *shared;
+
+ DefaultKeyStoreList(Provider *p, DefaultShared *_shared) : KeyStoreListContext(p), shared(_shared)
+ {
+ }
+
+ ~DefaultKeyStoreList()
+ {
+ }
+
+ virtual Provider::Context *clone() const
+ {
+ return 0;
+ }
+
+ virtual void start()
+ {
+ x509_supported = false;
+
+ QMetaObject::invokeMethod(this, "busyEnd", Qt::QueuedConnection);
+ }
+
+ virtual QList<int> keyStores()
+ {
+ if (!x509_supported) {
+ if (isSupported("cert") && isSupported("crl")) {
+ x509_supported = true;
+ }
+ }
+
+ bool have_systemstore = false;
#ifndef QCA_NO_SYSTEMSTORE
- if(shared->use_system())
- have_systemstore = qca_have_systemstore();
+ if (shared->use_system()) {
+ have_systemstore = qca_have_systemstore();
+ }
#endif
- QList<int> list;
-
- // system store only shows up if the OS store is available or
- // there is a configured store file
- if(x509_supported && (have_systemstore || !shared->roots_file().isEmpty()))
- list += 0;
-
- return list;
- }
-
- virtual KeyStore::Type type(int) const
- {
- return KeyStore::System;
- }
-
- virtual QString storeId(int) const
- {
- return "qca-default-systemstore";
- }
-
- virtual QString name(int) const
- {
- return "System Trusted Certificates";
- }
-
- virtual QList<KeyStoreEntry::Type> entryTypes(int) const
- {
- QList<KeyStoreEntry::Type> list;
- list += KeyStoreEntry::TypeCertificate;
- list += KeyStoreEntry::TypeCRL;
- return list;
- }
-
- virtual QList<KeyStoreEntryContext*> entryList(int)
- {
- QList<KeyStoreEntryContext*> out;
-
- QList<Certificate> certs;
- QList<CRL> crls;
-
- if(shared->use_system())
- {
- CertificateCollection col;
+ QList<int> list;
+
+ // system store only shows up if the OS store is available or
+ // there is a configured store file
+ if (x509_supported && (have_systemstore || !shared->roots_file().isEmpty())) {
+ list += 0;
+ }
+
+ return list;
+ }
+
+ virtual KeyStore::Type type(int) const
+ {
+ return KeyStore::System;
+ }
+
+ virtual QString storeId(int) const
+ {
+ return "qca-default-systemstore";
+ }
+
+ virtual QString name(int) const
+ {
+ return "System Trusted Certificates";
+ }
+
+ virtual QList<KeyStoreEntry::Type> entryTypes(int) const
+ {
+ QList<KeyStoreEntry::Type> list;
+ list += KeyStoreEntry::TypeCertificate;
+ list += KeyStoreEntry::TypeCRL;
+ return list;
+ }
+
+ virtual QList<KeyStoreEntryContext *> entryList(int)
+ {
+ QList<KeyStoreEntryContext *> out;
+
+ QList<Certificate> certs;
+ QList<CRL> crls;
+
+ if (shared->use_system()) {
+ CertificateCollection col;
#ifndef QCA_NO_SYSTEMSTORE
- col = qca_get_systemstore(QString());
+ col = qca_get_systemstore(QString());
#endif
- certs += col.certificates();
- crls += col.crls();
- }
-
- QString roots = shared->roots_file();
- if(!roots.isEmpty())
- {
- CertificateCollection col = CertificateCollection::fromFlatTextFile(roots);
- certs += col.certificates();
- crls += col.crls();
- }
+ certs += col.certificates();
+ crls += col.crls();
+ }
+
+ QString roots = shared->roots_file();
+ if (!roots.isEmpty()) {
+ CertificateCollection col = CertificateCollection::fromFlatTextFile(roots);
+ certs += col.certificates();
+ crls += col.crls();
+ }
#ifdef FRIENDLY_NAMES
- QStringList names = makeFriendlyNames(certs);
+ QStringList names = makeFriendlyNames(certs);
#endif
- for(int n = 0; n < certs.count(); ++n)
- {
- DefaultKeyStoreEntry *c = new DefaultKeyStoreEntry(certs[n], storeId(0), name(0), provider());
- c->_id = c->simpleId();
+ for (int n = 0; n < certs.count(); ++n) {
+ DefaultKeyStoreEntry *c = new DefaultKeyStoreEntry(certs[n], storeId(0), name(0), provider());
+ c->_id = c->simpleId();
#ifdef FRIENDLY_NAMES
- c->_name = names[n];
+ c->_name = names[n];
#else
- c->_name = c->simpleName();
+ c->_name = c->simpleName();
#endif
- out.append(c);
- }
-
- for(int n = 0; n < crls.count(); ++n)
- {
- DefaultKeyStoreEntry *c = new DefaultKeyStoreEntry(crls[n], storeId(0), name(0), provider());
- c->_id = c->simpleId();
- c->_name = c->simpleName();
- out.append(c);
- }
-
- return out;
- }
-
- virtual KeyStoreEntryContext *entryPassive(const QString &serialized)
- {
- return DefaultKeyStoreEntry::deserialize(serialized, provider());
- }
+ out.append(c);
+ }
+
+ for (int n = 0; n < crls.count(); ++n) {
+ DefaultKeyStoreEntry *c = new DefaultKeyStoreEntry(crls[n], storeId(0), name(0), provider());
+ c->_id = c->simpleId();
+ c->_name = c->simpleName();
+ out.append(c);
+ }
+
+ return out;
+ }
+
+ virtual KeyStoreEntryContext *entryPassive(const QString &serialized)
+ {
+ return DefaultKeyStoreEntry::deserialize(serialized, provider());
+ }
};
//----------------------------------------------------------------------------
// DefaultProvider
//----------------------------------------------------------------------------
static bool unescape_config_stringlist(const QString &in, QStringList *_out)
{
- QStringList out;
- QStringList list = in.split(',');
- for(int n = 0; n < list.count(); ++n)
- {
- QString str;
- if(!unescape_string(list[n], &str))
- return false;
- out += str.trimmed();
- }
- *_out = out;
- return true;
+ QStringList out;
+ QStringList list = in.split(',');
+ for (int n = 0; n < list.count(); ++n) {
+ QString str;
+ if (!unescape_string(list[n], &str)) {
+ return false;
+ }
+ out += str.trimmed();
+ }
+ *_out = out;
+ return true;
}
class DefaultProvider : public Provider
{
public:
- DefaultShared shared;
-
- virtual void init()
- {
- QDateTime now = QDateTime::currentDateTime();
-
- uint t = now.toTime_t();
- if(now.time().msec() > 0)
- t /= now.time().msec();
- qsrand(t);
- }
-
- virtual int version() const
- {
- return QCA_VERSION;
- }
-
- virtual int qcaVersion() const
- {
- return QCA_VERSION;
- }
-
- virtual QString name() const
- {
- return "default";
- }
-
- virtual QStringList features() const
- {
- QStringList list;
- list += "random";
- list += "md5";
- list += "sha1";
- list += "keystorelist";
- return list;
- }
-
- virtual Provider::Context *createContext(const QString &type)
- {
- if(type == "random")
- return new DefaultRandomContext(this);
- else if(type == "md5")
- return new DefaultMD5Context(this);
- else if(type == "sha1")
- return new DefaultSHA1Context(this);
- else if(type == "keystorelist")
- return new DefaultKeyStoreList(this, &shared);
- else
- return 0;
- }
-
- virtual QVariantMap defaultConfig() const
- {
- QVariantMap config;
- config["formtype"] = "http://affinix.com/qca/forms/default#1.0";
- config["use_system"] = true;
- config["roots_file"] = QString();
- config["skip_plugins"] = QString();
- config["plugin_priorities"] = QString();
- return config;
- }
-
- virtual void configChanged(const QVariantMap &config)
- {
- bool use_system = config["use_system"].toBool();
- QString roots_file = config["roots_file"].toString();
- QString skip_plugins_str = config["skip_plugins"].toString();
- QString plugin_priorities_str = config["plugin_priorities"].toString();
-
- QStringList tmp;
-
- QStringList skip_plugins;
- if(unescape_config_stringlist(skip_plugins_str, &tmp))
- skip_plugins = tmp;
-
- QStringList plugin_priorities;
- if(unescape_config_stringlist(plugin_priorities_str, &tmp))
- plugin_priorities = tmp;
-
- for(int n = 0; n < plugin_priorities.count(); ++n)
- {
- QString &s = plugin_priorities[n];
-
- // make sure the entry ends with ":number"
- int x = s.indexOf(':');
- bool ok = false;
- if(x != -1)
- s.mid(x + 1).toInt(&ok);
- if(!ok)
- {
- plugin_priorities.removeAt(n);
- --n;
- }
- }
-
- shared.set(use_system, roots_file, skip_plugins, plugin_priorities);
- }
+ DefaultShared shared;
+
+ virtual void init()
+ {
+ QDateTime now = QDateTime::currentDateTime();
+
+ uint t = now.toTime_t();
+ if (now.time().msec() > 0) {
+ t /= now.time().msec();
+ }
+ qsrand(t);
+ }
+
+ virtual int version() const
+ {
+ return QCA_VERSION;
+ }
+
+ virtual int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ virtual QString name() const
+ {
+ return "default";
+ }
+
+ virtual QStringList features() const
+ {
+ QStringList list;
+ list += "random";
+ list += "md5";
+ list += "sha1";
+ list += "keystorelist";
+ return list;
+ }
+
+ virtual Provider::Context *createContext(const QString &type)
+ {
+ if (type == "random") {
+ return new DefaultRandomContext(this);
+ } else if (type == "md5") {
+ return new DefaultMD5Context(this);
+ } else if (type == "sha1") {
+ return new DefaultSHA1Context(this);
+ } else if (type == "keystorelist") {
+ return new DefaultKeyStoreList(this, &shared);
+ } else {
+ return 0;
+ }
+ }
+
+ virtual QVariantMap defaultConfig() const
+ {
+ QVariantMap config;
+ config["formtype"] = "http://affinix.com/qca/forms/default#1.0";
+ config["use_system"] = true;
+ config["roots_file"] = QString();
+ config["skip_plugins"] = QString();
+ config["plugin_priorities"] = QString();
+ return config;
+ }
+
+ virtual void configChanged(const QVariantMap &config)
+ {
+ bool use_system = config["use_system"].toBool();
+ QString roots_file = config["roots_file"].toString();
+ QString skip_plugins_str = config["skip_plugins"].toString();
+ QString plugin_priorities_str = config["plugin_priorities"].toString();
+
+ QStringList tmp;
+
+ QStringList skip_plugins;
+ if (unescape_config_stringlist(skip_plugins_str, &tmp)) {
+ skip_plugins = tmp;
+ }
+
+ QStringList plugin_priorities;
+ if (unescape_config_stringlist(plugin_priorities_str, &tmp)) {
+ plugin_priorities = tmp;
+ }
+
+ for (int n = 0; n < plugin_priorities.count(); ++n) {
+ QString &s = plugin_priorities[n];
+
+ // make sure the entry ends with ":number"
+ int x = s.indexOf(':');
+ bool ok = false;
+ if (x != -1) {
+ s.mid(x + 1).toInt(&ok);
+ }
+ if (!ok) {
+ plugin_priorities.removeAt(n);
+ --n;
+ }
+ }
+
+ shared.set(use_system, roots_file, skip_plugins, plugin_priorities);
+ }
};
Provider *create_default_provider()
{
- return new DefaultProvider;
+ return new DefaultProvider;
}
QStringList skip_plugins(Provider *defaultProvider)
{
- DefaultProvider *that = (DefaultProvider *)defaultProvider;
- return that->shared.skip_plugins();
+ DefaultProvider *that = (DefaultProvider *)defaultProvider;
+ return that->shared.skip_plugins();
}
QStringList plugin_priorities(Provider *defaultProvider)
{
- DefaultProvider *that = (DefaultProvider *)defaultProvider;
- return that->shared.plugin_priorities();
+ DefaultProvider *that = (DefaultProvider *)defaultProvider;
+ return that->shared.plugin_priorities();
}
#include "qca_default.moc"
}
diff --git a/src/qca_keystore.cpp b/src/qca_keystore.cpp
index e7d3ee6d..23f3ec74 100644
--- a/src/qca_keystore.cpp
+++ b/src/qca_keystore.cpp
@@ -1,1773 +1,1743 @@
/*
* Copyright (C) 2003-2008 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_keystore.h"
#include <QCoreApplication>
#include <QAbstractEventDispatcher>
#include <QPointer>
#include <QSet>
#include <QMutex>
#include <QWaitCondition>
#include <stdlib.h> // abort
#include <stdio.h> // fprintf
#include "qcaprovider.h"
Q_DECLARE_METATYPE(QCA::KeyStoreEntry)
Q_DECLARE_METATYPE(QList<QCA::KeyStoreEntry>)
Q_DECLARE_METATYPE(QList<QCA::KeyStoreEntry::Type>)
Q_DECLARE_METATYPE(QCA::KeyBundle)
Q_DECLARE_METATYPE(QCA::Certificate)
Q_DECLARE_METATYPE(QCA::CRL)
Q_DECLARE_METATYPE(QCA::PGPKey)
-namespace QCA {
+namespace QCA
+{
Provider::Context *getContext(const QString &type, Provider *p);
// from qca_plugin.cpp
QString truncate_log(const QString &in, int size);
/*
How this stuff works:
KeyStoreListContext is queried for a list of store context ids. A signal
is used to indicate when the list may have changed, so polling for changes
is not necessary. Context ids change for every new presence of a store.
Even if a user removes and inserts the same smart card device, which has
the same storeId, the context id will ALWAYS be different. If a previously
known context id is missing from a later queried list, then it means the
associated store is unavailable. It is recommended that the provider just
use a counter for the contextId, incrementing the value anytime a new
context is made.
KeyStoreTracker manages all of the keystore stuff, and exists in its own
thread (called the tracker thread). All of the KeyStoreListContext
objects exist in the tracker thread.
*/
/*
scenarios to handle:
- ksm.start shouldn't block
- keystore in available list, but gone by the time it is requested
- keystore is unavailable during a call to a keystoreentry method
- keystore/keystoreentry methods called simultaneously from different threads
- and of course, objects from keystores should work, despite being created
in the keystore thread
*/
//----------------------------------------------------------------------------
// KeyStoreTracker
//----------------------------------------------------------------------------
static int tracker_id_at = 0;
class KeyStoreTracker : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- static KeyStoreTracker *self;
-
- class Item
- {
- public:
- // combine keystore owner and contextid into a single id
- int trackerId;
-
- // number of times the keystore has been updated
- int updateCount;
-
- // keystore context
- KeyStoreListContext *owner;
- int storeContextId;
-
- // properties
- QString storeId;
- QString name;
- KeyStore::Type type;
- bool isReadOnly;
-
- Item()
- : trackerId(-1)
- , updateCount(0)
- , owner(0)
- , storeContextId(-1)
- , storeId("")
- , name("")
- , type(KeyStore::System)
- , isReadOnly(false)
- {
- }
- };
-
- QMutex m;
- QSet<KeyStoreListContext*> sources;
- QSet<KeyStoreListContext*> busySources;
- QList<Item> items;
- QString dtext;
- bool startedAll;
- bool busy;
-
- QMutex updateMutex;
-
- KeyStoreTracker()
- {
- self = this;
-
- qRegisterMetaType<KeyStoreEntry>();
- qRegisterMetaType< QList<KeyStoreEntry> >();
- qRegisterMetaType< QList<KeyStoreEntry::Type> >();
- qRegisterMetaType<KeyBundle>();
- qRegisterMetaType<Certificate>();
- qRegisterMetaType<CRL>();
- qRegisterMetaType<PGPKey>();
-
- connect(this, SIGNAL(updated_p()), SLOT(updated_locked()), Qt::QueuedConnection);
-
- startedAll = false;
- busy = true; // we start out busy
- }
-
- ~KeyStoreTracker()
- {
- qDeleteAll(sources);
- self = 0;
- }
-
- static KeyStoreTracker *instance()
- {
- return self;
- }
-
- // thread-safe
- bool isBusy()
- {
- QMutexLocker locker(&m);
- return busy;
- }
-
- // thread-safe
- QList<Item> getItems()
- {
- QMutexLocker locker(&m);
- return items;
- }
-
- // thread-safe
- QString getDText()
- {
- QMutexLocker locker(&m);
- return dtext;
- }
-
- // thread-safe
- void clearDText()
- {
- QMutexLocker locker(&m);
- dtext.clear();
- }
-
- // thread-safe
- void addTarget(QObject *ksm)
- {
- QMutexLocker locker(&updateMutex);
- ksm->connect(this, SIGNAL(updated()), SLOT(tracker_updated()), Qt::DirectConnection);
- }
-
- // thread-safe
- void removeTarget(QObject *ksm)
- {
- QMutexLocker locker(&updateMutex);
- disconnect(ksm);
- }
+ static KeyStoreTracker *self;
+
+ class Item
+ {
+ public:
+ // combine keystore owner and contextid into a single id
+ int trackerId;
+
+ // number of times the keystore has been updated
+ int updateCount;
+
+ // keystore context
+ KeyStoreListContext *owner;
+ int storeContextId;
+
+ // properties
+ QString storeId;
+ QString name;
+ KeyStore::Type type;
+ bool isReadOnly;
+
+ Item()
+ : trackerId(-1)
+ , updateCount(0)
+ , owner(0)
+ , storeContextId(-1)
+ , storeId("")
+ , name("")
+ , type(KeyStore::System)
+ , isReadOnly(false)
+ {
+ }
+ };
+
+ QMutex m;
+ QSet<KeyStoreListContext *> sources;
+ QSet<KeyStoreListContext *> busySources;
+ QList<Item> items;
+ QString dtext;
+ bool startedAll;
+ bool busy;
+
+ QMutex updateMutex;
+
+ KeyStoreTracker()
+ {
+ self = this;
+
+ qRegisterMetaType<KeyStoreEntry>();
+ qRegisterMetaType< QList<KeyStoreEntry> >();
+ qRegisterMetaType< QList<KeyStoreEntry::Type> >();
+ qRegisterMetaType<KeyBundle>();
+ qRegisterMetaType<Certificate>();
+ qRegisterMetaType<CRL>();
+ qRegisterMetaType<PGPKey>();
+
+ connect(this, SIGNAL(updated_p()), SLOT(updated_locked()), Qt::QueuedConnection);
+
+ startedAll = false;
+ busy = true; // we start out busy
+ }
+
+ ~KeyStoreTracker()
+ {
+ qDeleteAll(sources);
+ self = 0;
+ }
+
+ static KeyStoreTracker *instance()
+ {
+ return self;
+ }
+
+ // thread-safe
+ bool isBusy()
+ {
+ QMutexLocker locker(&m);
+ return busy;
+ }
+
+ // thread-safe
+ QList<Item> getItems()
+ {
+ QMutexLocker locker(&m);
+ return items;
+ }
+
+ // thread-safe
+ QString getDText()
+ {
+ QMutexLocker locker(&m);
+ return dtext;
+ }
+
+ // thread-safe
+ void clearDText()
+ {
+ QMutexLocker locker(&m);
+ dtext.clear();
+ }
+
+ // thread-safe
+ void addTarget(QObject *ksm)
+ {
+ QMutexLocker locker(&updateMutex);
+ ksm->connect(this, SIGNAL(updated()), SLOT(tracker_updated()), Qt::DirectConnection);
+ }
+
+ // thread-safe
+ void removeTarget(QObject *ksm)
+ {
+ QMutexLocker locker(&updateMutex);
+ disconnect(ksm);
+ }
public slots:
- void spinEventLoop()
- {
- QAbstractEventDispatcher::instance()->processEvents(QEventLoop::AllEvents);
- }
-
- void start()
- {
- // grab providers (and default)
- ProviderList list = providers();
- list.append(defaultProvider());
-
- for(int n = 0; n < list.count(); ++n)
- {
- Provider *p = list[n];
- if(p->features().contains("keystorelist") && !haveProviderSource(p))
- startProvider(p);
- }
-
- startedAll = true;
- }
-
- void start(const QString &provider)
- {
- // grab providers (and default)
- ProviderList list = providers();
- list.append(defaultProvider());
-
- Provider *p = 0;
- for(int n = 0; n < list.count(); ++n)
- {
- if(list[n]->name() == provider)
- {
- p = list[n];
- break;
- }
- }
-
- if(p && p->features().contains("keystorelist") && !haveProviderSource(p))
- startProvider(p);
- }
-
- void scan()
- {
- if(startedAll)
- start();
- }
-
- QList<QCA::KeyStoreEntry> entryList(int trackerId)
- {
- QList<KeyStoreEntry> out;
- int at = findItem(trackerId);
- if(at == -1)
- return out;
- Item &i = items[at];
- QList<KeyStoreEntryContext*> list = i.owner->entryList(i.storeContextId);
- for(int n = 0; n < list.count(); ++n)
- {
- KeyStoreEntry entry;
- entry.change(list[n]);
- out.append(entry);
- }
- return out;
- }
-
- QList<QCA::KeyStoreEntry::Type> entryTypes(int trackerId)
- {
- QList<KeyStoreEntry::Type> out;
- int at = findItem(trackerId);
- if(at == -1)
- return out;
- Item &i = items[at];
- return i.owner->entryTypes(i.storeContextId);
- }
-
- // hack with void *
- void *entry(const QString &storeId, const QString &entryId)
- {
- KeyStoreListContext *c = 0;
- int contextId = -1;
- m.lock();
- foreach(const Item &i, items)
- {
- if(i.storeId == storeId)
- {
- c = i.owner;
- contextId = i.storeContextId;
- break;
- }
- }
- m.unlock();
- if(!c)
- return 0;
-
- return c->entry(contextId, entryId);
- }
-
- // hack with void *
- void *entryPassive(const QString &serialized)
- {
- foreach(KeyStoreListContext *ksl, sources)
- {
- // "is this yours?"
- KeyStoreEntryContext *e = ksl->entryPassive(serialized);
- if(e)
- return e;
- }
- return 0;
- }
-
- QString writeEntry(int trackerId, const QVariant &v)
- {
- int at = findItem(trackerId);
- if(at == -1)
- return QString();
- Item &i = items[at];
+ void spinEventLoop()
+ {
+ QAbstractEventDispatcher::instance()->processEvents(QEventLoop::AllEvents);
+ }
+
+ void start()
+ {
+ // grab providers (and default)
+ ProviderList list = providers();
+ list.append(defaultProvider());
+
+ for (int n = 0; n < list.count(); ++n) {
+ Provider *p = list[n];
+ if (p->features().contains("keystorelist") && !haveProviderSource(p)) {
+ startProvider(p);
+ }
+ }
+
+ startedAll = true;
+ }
+
+ void start(const QString &provider)
+ {
+ // grab providers (and default)
+ ProviderList list = providers();
+ list.append(defaultProvider());
+
+ Provider *p = 0;
+ for (int n = 0; n < list.count(); ++n) {
+ if (list[n]->name() == provider) {
+ p = list[n];
+ break;
+ }
+ }
+
+ if (p && p->features().contains("keystorelist") && !haveProviderSource(p)) {
+ startProvider(p);
+ }
+ }
+
+ void scan()
+ {
+ if (startedAll) {
+ start();
+ }
+ }
+
+ QList<QCA::KeyStoreEntry> entryList(int trackerId)
+ {
+ QList<KeyStoreEntry> out;
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return out;
+ }
+ Item &i = items[at];
+ QList<KeyStoreEntryContext *> list = i.owner->entryList(i.storeContextId);
+ for (int n = 0; n < list.count(); ++n) {
+ KeyStoreEntry entry;
+ entry.change(list[n]);
+ out.append(entry);
+ }
+ return out;
+ }
+
+ QList<QCA::KeyStoreEntry::Type> entryTypes(int trackerId)
+ {
+ QList<KeyStoreEntry::Type> out;
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return out;
+ }
+ Item &i = items[at];
+ return i.owner->entryTypes(i.storeContextId);
+ }
+
+ // hack with void *
+ void *entry(const QString &storeId, const QString &entryId)
+ {
+ KeyStoreListContext *c = 0;
+ int contextId = -1;
+ m.lock();
+ foreach (const Item &i, items) {
+ if (i.storeId == storeId) {
+ c = i.owner;
+ contextId = i.storeContextId;
+ break;
+ }
+ }
+ m.unlock();
+ if (!c) {
+ return 0;
+ }
+
+ return c->entry(contextId, entryId);
+ }
+
+ // hack with void *
+ void *entryPassive(const QString &serialized)
+ {
+ foreach (KeyStoreListContext *ksl, sources) {
+ // "is this yours?"
+ KeyStoreEntryContext *e = ksl->entryPassive(serialized);
+ if (e) {
+ return e;
+ }
+ }
+ return 0;
+ }
+
+ QString writeEntry(int trackerId, const QVariant &v)
+ {
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return QString();
+ }
+ Item &i = items[at];
#if QT_VERSION >= 0x050000
- if(v.canConvert<KeyBundle>())
- return i.owner->writeEntry(i.storeContextId, v.value<KeyBundle>());
- else if(v.canConvert<Certificate>())
- return i.owner->writeEntry(i.storeContextId, v.value<Certificate>());
- else if(v.canConvert<CRL>())
- return i.owner->writeEntry(i.storeContextId, v.value<CRL>());
- else if(v.canConvert<PGPKey>())
- return i.owner->writeEntry(i.storeContextId, v.value<PGPKey>());
+ if (v.canConvert<KeyBundle>()) {
+ return i.owner->writeEntry(i.storeContextId, v.value<KeyBundle>());
+ } else if (v.canConvert<Certificate>()) {
+ return i.owner->writeEntry(i.storeContextId, v.value<Certificate>());
+ } else if (v.canConvert<CRL>()) {
+ return i.owner->writeEntry(i.storeContextId, v.value<CRL>());
+ } else if (v.canConvert<PGPKey>()) {
+ return i.owner->writeEntry(i.storeContextId, v.value<PGPKey>());
+ }
#else
- if(qVariantCanConvert<KeyBundle>(v))
- return i.owner->writeEntry(i.storeContextId, qVariantValue<KeyBundle>(v));
- else if(qVariantCanConvert<Certificate>(v))
- return i.owner->writeEntry(i.storeContextId, qVariantValue<Certificate>(v));
- else if(qVariantCanConvert<CRL>(v))
- return i.owner->writeEntry(i.storeContextId, qVariantValue<CRL>(v));
- else if(qVariantCanConvert<PGPKey>(v))
- return i.owner->writeEntry(i.storeContextId, qVariantValue<PGPKey>(v));
+ if (qVariantCanConvert<KeyBundle>(v)) {
+ return i.owner->writeEntry(i.storeContextId, qVariantValue<KeyBundle>(v));
+ } else if (qVariantCanConvert<Certificate>(v)) {
+ return i.owner->writeEntry(i.storeContextId, qVariantValue<Certificate>(v));
+ } else if (qVariantCanConvert<CRL>(v)) {
+ return i.owner->writeEntry(i.storeContextId, qVariantValue<CRL>(v));
+ } else if (qVariantCanConvert<PGPKey>(v)) {
+ return i.owner->writeEntry(i.storeContextId, qVariantValue<PGPKey>(v));
+ }
#endif
- else
- return QString();
- }
-
- QString writeEntry(int trackerId, const QCA::KeyBundle &v)
- {
- int at = findItem(trackerId);
- if(at == -1)
- return QString();
- Item &i = items[at];
-
- return i.owner->writeEntry(i.storeContextId, v);
- }
-
- QString writeEntry(int trackerId, const QCA::Certificate &v)
- {
- int at = findItem(trackerId);
- if(at == -1)
- return QString();
- Item &i = items[at];
-
- return i.owner->writeEntry(i.storeContextId, v);
- }
-
- QString writeEntry(int trackerId, const QCA::CRL &v)
- {
- int at = findItem(trackerId);
- if(at == -1)
- return QString();
- Item &i = items[at];
-
- return i.owner->writeEntry(i.storeContextId, v);
- }
-
- QString writeEntry(int trackerId, const QCA::PGPKey &v)
- {
- int at = findItem(trackerId);
- if(at == -1)
- return QString();
- Item &i = items[at];
-
- return i.owner->writeEntry(i.storeContextId, v);
- }
-
- bool removeEntry(int trackerId, const QString &entryId)
- {
- int at = findItem(trackerId);
- if(at == -1)
- return false;
- Item &i = items[at];
- return i.owner->removeEntry(i.storeContextId, entryId);
- }
+ else {
+ return QString();
+ }
+ }
+
+ QString writeEntry(int trackerId, const QCA::KeyBundle &v)
+ {
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return QString();
+ }
+ Item &i = items[at];
+
+ return i.owner->writeEntry(i.storeContextId, v);
+ }
+
+ QString writeEntry(int trackerId, const QCA::Certificate &v)
+ {
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return QString();
+ }
+ Item &i = items[at];
+
+ return i.owner->writeEntry(i.storeContextId, v);
+ }
+
+ QString writeEntry(int trackerId, const QCA::CRL &v)
+ {
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return QString();
+ }
+ Item &i = items[at];
+
+ return i.owner->writeEntry(i.storeContextId, v);
+ }
+
+ QString writeEntry(int trackerId, const QCA::PGPKey &v)
+ {
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return QString();
+ }
+ Item &i = items[at];
+
+ return i.owner->writeEntry(i.storeContextId, v);
+ }
+
+ bool removeEntry(int trackerId, const QString &entryId)
+ {
+ int at = findItem(trackerId);
+ if (at == -1) {
+ return false;
+ }
+ Item &i = items[at];
+ return i.owner->removeEntry(i.storeContextId, entryId);
+ }
signals:
- // emit this when items or busy state changes
- void updated();
- void updated_p();
+ // emit this when items or busy state changes
+ void updated();
+ void updated_p();
private slots:
- void updated_locked()
- {
- QMutexLocker locker(&updateMutex);
- emit updated();
- }
+ void updated_locked()
+ {
+ QMutexLocker locker(&updateMutex);
+ emit updated();
+ }
private:
- bool haveProviderSource(Provider *p) const
- {
- foreach(KeyStoreListContext *ksl, sources)
- {
- if(ksl->provider() == p)
- return true;
- }
- return false;
- }
-
- int findItem(int trackerId)
- {
- for(int n = 0; n < items.count(); ++n)
- {
- if(items[n].trackerId == trackerId)
- return n;
- }
- return -1;
- }
-
- void startProvider(Provider *p)
- {
- KeyStoreListContext *c = static_cast<KeyStoreListContext *>(getContext("keystorelist", p));
- if(!c)
- return;
-
- sources += c;
- busySources += c;
- connect(c, SIGNAL(busyStart()), SLOT(ksl_busyStart()));
- connect(c, SIGNAL(busyEnd()), SLOT(ksl_busyEnd()));
- connect(c, SIGNAL(updated()), SLOT(ksl_updated()));
- connect(c, SIGNAL(diagnosticText(const QString &)), SLOT(ksl_diagnosticText(const QString &)));
- connect(c, SIGNAL(storeUpdated(int)), SLOT(ksl_storeUpdated(int)));
- c->start();
- c->setUpdatesEnabled(true);
-
- QCA_logTextMessage(QString("keystore: startProvider %1").arg(p->name()), Logger::Information);
- }
-
- bool updateStores(KeyStoreListContext *c)
- {
- bool changed = false;
-
- QMutexLocker locker(&m);
-
- QList<int> keyStores = c->keyStores();
-
- // remove any contexts that are gone
- for(int n = 0; n < items.count(); ++n)
- {
- if(items[n].owner == c && !keyStores.contains(items[n].storeContextId))
- {
- QCA_logTextMessage(QString("keystore: updateStores remove %1").arg(items[n].storeContextId), Logger::Information);
-
- items.removeAt(n);
- --n; // adjust position
-
- changed = true;
- }
- }
-
- // handle add/updates
- foreach(int id, keyStores)
- {
- // do we have it already?
- int at = -1;
- for(int n = 0; n < items.count(); ++n)
- {
- if(items[n].owner == c && items[n].storeContextId == id)
- {
- at = n;
- break;
- }
- }
-
- // if so, update it
- if(at != -1)
- {
- Item &i = items[at];
-
- QString name = c->name(id);
- bool isReadOnly = c->isReadOnly(id);
- if(i.name != name || i.isReadOnly != isReadOnly)
- {
- QCA_logTextMessage(QString("keystore: updateStores update %1").arg(id), Logger::Information);
- i.name = name;
- i.isReadOnly = isReadOnly;
- changed = true;
- }
- }
- // otherwise, add it
- else
- {
- QCA_logTextMessage(QString("keystore: updateStores add %1").arg(id), Logger::Information);
-
- Item i;
- i.trackerId = tracker_id_at++;
- i.updateCount = 0;
- i.owner = c;
- i.storeContextId = id;
- i.storeId = c->storeId(id);
- i.name = c->name(id);
- i.type = c->type(id);
- i.isReadOnly = c->isReadOnly(id);
- items += i;
-
- changed = true;
- }
- }
-
- return changed;
- }
+ bool haveProviderSource(Provider *p) const
+ {
+ foreach (KeyStoreListContext *ksl, sources) {
+ if (ksl->provider() == p) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ int findItem(int trackerId)
+ {
+ for (int n = 0; n < items.count(); ++n) {
+ if (items[n].trackerId == trackerId) {
+ return n;
+ }
+ }
+ return -1;
+ }
+
+ void startProvider(Provider *p)
+ {
+ KeyStoreListContext *c = static_cast<KeyStoreListContext *>(getContext("keystorelist", p));
+ if (!c) {
+ return;
+ }
+
+ sources += c;
+ busySources += c;
+ connect(c, SIGNAL(busyStart()), SLOT(ksl_busyStart()));
+ connect(c, SIGNAL(busyEnd()), SLOT(ksl_busyEnd()));
+ connect(c, SIGNAL(updated()), SLOT(ksl_updated()));
+ connect(c, SIGNAL(diagnosticText(QString)), SLOT(ksl_diagnosticText(QString)));
+ connect(c, SIGNAL(storeUpdated(int)), SLOT(ksl_storeUpdated(int)));
+ c->start();
+ c->setUpdatesEnabled(true);
+
+ QCA_logTextMessage(QString("keystore: startProvider %1").arg(p->name()), Logger::Information);
+ }
+
+ bool updateStores(KeyStoreListContext *c)
+ {
+ bool changed = false;
+
+ QMutexLocker locker(&m);
+
+ QList<int> keyStores = c->keyStores();
+
+ // remove any contexts that are gone
+ for (int n = 0; n < items.count(); ++n) {
+ if (items[n].owner == c && !keyStores.contains(items[n].storeContextId)) {
+ QCA_logTextMessage(QString("keystore: updateStores remove %1").arg(items[n].storeContextId), Logger::Information);
+
+ items.removeAt(n);
+ --n; // adjust position
+
+ changed = true;
+ }
+ }
+
+ // handle add/updates
+ foreach (int id, keyStores) {
+ // do we have it already?
+ int at = -1;
+ for (int n = 0; n < items.count(); ++n) {
+ if (items[n].owner == c && items[n].storeContextId == id) {
+ at = n;
+ break;
+ }
+ }
+
+ // if so, update it
+ if (at != -1) {
+ Item &i = items[at];
+
+ QString name = c->name(id);
+ bool isReadOnly = c->isReadOnly(id);
+ if (i.name != name || i.isReadOnly != isReadOnly) {
+ QCA_logTextMessage(QString("keystore: updateStores update %1").arg(id), Logger::Information);
+ i.name = name;
+ i.isReadOnly = isReadOnly;
+ changed = true;
+ }
+ }
+ // otherwise, add it
+ else {
+ QCA_logTextMessage(QString("keystore: updateStores add %1").arg(id), Logger::Information);
+
+ Item i;
+ i.trackerId = tracker_id_at++;
+ i.updateCount = 0;
+ i.owner = c;
+ i.storeContextId = id;
+ i.storeId = c->storeId(id);
+ i.name = c->name(id);
+ i.type = c->type(id);
+ i.isReadOnly = c->isReadOnly(id);
+ items += i;
+
+ changed = true;
+ }
+ }
+
+ return changed;
+ }
private slots:
- void ksl_busyStart()
- {
- KeyStoreListContext *c = (KeyStoreListContext *)sender();
-
- QCA_logTextMessage(QString("keystore: ksl_busyStart %1").arg(c->provider()->name()), Logger::Information);
-
- if(!busySources.contains(c))
- {
- busySources += c;
-
- QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
- emit updated_p();
- }
- }
-
- void ksl_busyEnd()
- {
- KeyStoreListContext *c = (KeyStoreListContext *)sender();
-
- QCA_logTextMessage(QString("keystore: ksl_busyEnd %1").arg(c->provider()->name()), Logger::Information);
-
- busySources.remove(c);
- bool changed = updateStores(c);
- bool any_busy = !busySources.isEmpty();
-
- if(!any_busy)
- {
- m.lock();
- busy = false;
- m.unlock();
- }
-
- if(!any_busy || changed)
- {
- QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
- emit updated_p();
- }
- }
-
- void ksl_updated()
- {
- KeyStoreListContext *c = (KeyStoreListContext *)sender();
-
- QCA_logTextMessage(QString("keystore: ksl_updated %1").arg(c->provider()->name()), Logger::Information);
-
- bool changed = updateStores(c);
- if(changed)
- {
- QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
- emit updated_p();
- }
- }
-
- void ksl_diagnosticText(const QString &str)
- {
- QMutexLocker locker(&m);
- dtext += str;
- dtext = truncate_log(dtext, 100000);
- }
-
- void ksl_storeUpdated(int id)
- {
- KeyStoreListContext *c = (KeyStoreListContext *)sender();
-
- QCA_logTextMessage(QString("keystore: ksl_storeUpdated %1 %2").arg(c->provider()->name(), QString::number(id)), Logger::Information);
-
- QMutexLocker locker(&m);
- for(int n = 0; n < items.count(); ++n)
- {
- Item &i = items[n];
- if(i.owner == c && i.storeContextId == id)
- {
- ++i.updateCount;
-
- QCA_logTextMessage(QString("keystore: %1 updateCount = %2").arg(i.name, QString::number(i.updateCount)), Logger::Information);
-
- QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
- emit updated_p();
- return;
- }
- }
- }
+ void ksl_busyStart()
+ {
+ KeyStoreListContext *c = (KeyStoreListContext *)sender();
+
+ QCA_logTextMessage(QString("keystore: ksl_busyStart %1").arg(c->provider()->name()), Logger::Information);
+
+ if (!busySources.contains(c)) {
+ busySources += c;
+
+ QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
+ emit updated_p();
+ }
+ }
+
+ void ksl_busyEnd()
+ {
+ KeyStoreListContext *c = (KeyStoreListContext *)sender();
+
+ QCA_logTextMessage(QString("keystore: ksl_busyEnd %1").arg(c->provider()->name()), Logger::Information);
+
+ busySources.remove(c);
+ bool changed = updateStores(c);
+ bool any_busy = !busySources.isEmpty();
+
+ if (!any_busy) {
+ m.lock();
+ busy = false;
+ m.unlock();
+ }
+
+ if (!any_busy || changed) {
+ QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
+ emit updated_p();
+ }
+ }
+
+ void ksl_updated()
+ {
+ KeyStoreListContext *c = (KeyStoreListContext *)sender();
+
+ QCA_logTextMessage(QString("keystore: ksl_updated %1").arg(c->provider()->name()), Logger::Information);
+
+ bool changed = updateStores(c);
+ if (changed) {
+ QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
+ emit updated_p();
+ }
+ }
+
+ void ksl_diagnosticText(const QString &str)
+ {
+ QMutexLocker locker(&m);
+ dtext += str;
+ dtext = truncate_log(dtext, 100000);
+ }
+
+ void ksl_storeUpdated(int id)
+ {
+ KeyStoreListContext *c = (KeyStoreListContext *)sender();
+
+ QCA_logTextMessage(QString("keystore: ksl_storeUpdated %1 %2").arg(c->provider()->name(), QString::number(id)), Logger::Information);
+
+ QMutexLocker locker(&m);
+ for (int n = 0; n < items.count(); ++n) {
+ Item &i = items[n];
+ if (i.owner == c && i.storeContextId == id) {
+ ++i.updateCount;
+
+ QCA_logTextMessage(QString("keystore: %1 updateCount = %2").arg(i.name, QString::number(i.updateCount)), Logger::Information);
+
+ QCA_logTextMessage(QString("keystore: emitting updated"), Logger::Information);
+ emit updated_p();
+ return;
+ }
+ }
+ }
};
KeyStoreTracker *KeyStoreTracker::self = 0;
//----------------------------------------------------------------------------
// KeyStoreThread
//----------------------------------------------------------------------------
class KeyStoreThread : public SyncThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeyStoreTracker *tracker;
- QMutex call_mutex;
-
- KeyStoreThread(QObject *parent = 0) : SyncThread(parent)
- {
- }
-
- ~KeyStoreThread()
- {
- stop();
- }
-
- void atStart()
- {
- tracker = new KeyStoreTracker;
- }
-
- void atEnd()
- {
- delete tracker;
- }
+ KeyStoreTracker *tracker;
+ QMutex call_mutex;
+
+ KeyStoreThread(QObject *parent = 0) : SyncThread(parent)
+ {
+ }
+
+ ~KeyStoreThread()
+ {
+ stop();
+ }
+
+ void atStart()
+ {
+ tracker = new KeyStoreTracker;
+ }
+
+ void atEnd()
+ {
+ delete tracker;
+ }
};
//----------------------------------------------------------------------------
// KeyStoreGlobal
//----------------------------------------------------------------------------
class KeyStoreManagerGlobal;
Q_GLOBAL_STATIC(QMutex, ksm_mutex)
static KeyStoreManagerGlobal *g_ksm = 0;
class KeyStoreManagerGlobal
{
public:
- KeyStoreThread *thread;
-
- KeyStoreManagerGlobal()
- {
- thread = new KeyStoreThread;
- thread->moveToThread(QCoreApplication::instance()->thread());
- thread->start();
- }
-
- ~KeyStoreManagerGlobal()
- {
- delete thread;
- }
+ KeyStoreThread *thread;
+
+ KeyStoreManagerGlobal()
+ {
+ thread = new KeyStoreThread;
+ thread->moveToThread(QCoreApplication::instance()->thread());
+ thread->start();
+ }
+
+ ~KeyStoreManagerGlobal()
+ {
+ delete thread;
+ }
};
// this function is thread-safe
static QVariant trackercall(const char *method, const QVariantList &args = QVariantList())
{
- QVariant ret;
- bool ok;
+ QVariant ret;
+ bool ok;
- g_ksm->thread->call_mutex.lock();
- ret = g_ksm->thread->call(KeyStoreTracker::instance(), method, args, &ok);
- g_ksm->thread->call_mutex.unlock();
+ g_ksm->thread->call_mutex.lock();
+ ret = g_ksm->thread->call(KeyStoreTracker::instance(), method, args, &ok);
+ g_ksm->thread->call_mutex.unlock();
- Q_ASSERT(ok);
- if(!ok)
- {
- fprintf(stderr, "QCA: KeyStoreTracker call [%s] failed.\n", method);
- abort();
- return QVariant();
- }
- return ret;
+ Q_ASSERT(ok);
+ if (!ok) {
+ fprintf(stderr, "QCA: KeyStoreTracker call [%s] failed.\n", method);
+ abort();
+ return QVariant();
+ }
+ return ret;
}
//----------------------------------------------------------------------------
// KeyStoreEntry
//----------------------------------------------------------------------------
class KeyStoreEntry::Private
{
public:
- bool accessible;
+ bool accessible;
- Private()
- {
- accessible = false;
- }
+ Private()
+ {
+ accessible = false;
+ }
};
KeyStoreEntry::KeyStoreEntry()
-:d(new Private)
+ : d(new Private)
{
}
KeyStoreEntry::KeyStoreEntry(const QString &serialized)
-:d(new Private)
+ : d(new Private)
{
- *this = fromString(serialized);
+ *this = fromString(serialized);
}
KeyStoreEntry::KeyStoreEntry(const KeyStoreEntry &from)
-:Algorithm(from), d(new Private(*from.d))
+ : Algorithm(from), d(new Private(*from.d))
{
}
KeyStoreEntry::~KeyStoreEntry()
{
- delete d;
+ delete d;
}
-KeyStoreEntry & KeyStoreEntry::operator=(const KeyStoreEntry &from)
+KeyStoreEntry &KeyStoreEntry::operator=(const KeyStoreEntry &from)
{
- Algorithm::operator=(from);
- *d = *from.d;
- return *this;
+ Algorithm::operator=(from);
+ *d = *from.d;
+ return *this;
}
bool KeyStoreEntry::isNull() const
{
- return (!context() ? true : false);
+ return (!context() ? true : false);
}
bool KeyStoreEntry::isAvailable() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->isAvailable();
+ return static_cast<const KeyStoreEntryContext *>(context())->isAvailable();
}
bool KeyStoreEntry::isAccessible() const
{
- return d->accessible;
+ return d->accessible;
}
KeyStoreEntry::Type KeyStoreEntry::type() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->type();
+ return static_cast<const KeyStoreEntryContext *>(context())->type();
}
QString KeyStoreEntry::name() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->name();
+ return static_cast<const KeyStoreEntryContext *>(context())->name();
}
QString KeyStoreEntry::id() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->id();
+ return static_cast<const KeyStoreEntryContext *>(context())->id();
}
QString KeyStoreEntry::storeName() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->storeName();
+ return static_cast<const KeyStoreEntryContext *>(context())->storeName();
}
QString KeyStoreEntry::storeId() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->storeId();
+ return static_cast<const KeyStoreEntryContext *>(context())->storeId();
}
QString KeyStoreEntry::toString() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->serialize();
+ return static_cast<const KeyStoreEntryContext *>(context())->serialize();
}
KeyStoreEntry KeyStoreEntry::fromString(const QString &serialized)
{
- KeyStoreEntry e;
- KeyStoreEntryContext *c = (KeyStoreEntryContext *)KeyStoreTracker::instance()->entryPassive(serialized);
- if(c)
- e.change(c);
- return e;
+ KeyStoreEntry e;
+ KeyStoreEntryContext *c = (KeyStoreEntryContext *)KeyStoreTracker::instance()->entryPassive(serialized);
+ if (c) {
+ e.change(c);
+ }
+ return e;
}
KeyBundle KeyStoreEntry::keyBundle() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->keyBundle();
+ return static_cast<const KeyStoreEntryContext *>(context())->keyBundle();
}
Certificate KeyStoreEntry::certificate() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->certificate();
+ return static_cast<const KeyStoreEntryContext *>(context())->certificate();
}
CRL KeyStoreEntry::crl() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->crl();
+ return static_cast<const KeyStoreEntryContext *>(context())->crl();
}
PGPKey KeyStoreEntry::pgpSecretKey() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->pgpSecretKey();
+ return static_cast<const KeyStoreEntryContext *>(context())->pgpSecretKey();
}
PGPKey KeyStoreEntry::pgpPublicKey() const
{
- return static_cast<const KeyStoreEntryContext *>(context())->pgpPublicKey();
+ return static_cast<const KeyStoreEntryContext *>(context())->pgpPublicKey();
}
bool KeyStoreEntry::ensureAvailable()
{
- QString storeId = this->storeId();
- QString entryId = id();
+ QString storeId = this->storeId();
+ QString entryId = id();
#if QT_VERSION >= 0x050000
- KeyStoreEntryContext *c = (KeyStoreEntryContext *)trackercall("entry", QVariantList() << storeId << entryId).value<void*>();
+ KeyStoreEntryContext *c = (KeyStoreEntryContext *)trackercall("entry", QVariantList() << storeId << entryId).value<void *>();
#else
- KeyStoreEntryContext *c = (KeyStoreEntryContext *)qVariantValue<void*>(trackercall("entry", QVariantList() << storeId << entryId));
+ KeyStoreEntryContext *c = (KeyStoreEntryContext *)qVariantValue<void *>(trackercall("entry", QVariantList() << storeId << entryId));
#endif
- if(c)
- change(c);
- return isAvailable();
+ if (c) {
+ change(c);
+ }
+ return isAvailable();
}
bool KeyStoreEntry::ensureAccess()
{
- if(!ensureAvailable())
- {
- d->accessible = false;
- return false;
- }
- bool ok = static_cast<KeyStoreEntryContext *>(context())->ensureAccess();
- d->accessible = ok;
- return d->accessible;
+ if (!ensureAvailable()) {
+ d->accessible = false;
+ return false;
+ }
+ bool ok = static_cast<KeyStoreEntryContext *>(context())->ensureAccess();
+ d->accessible = ok;
+ return d->accessible;
}
//----------------------------------------------------------------------------
// KeyStoreEntryWatcher
//----------------------------------------------------------------------------
class KeyStoreEntryWatcher::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeyStoreEntryWatcher *q;
- KeyStoreManager ksm;
- KeyStoreEntry entry;
- QString storeId, entryId;
- KeyStore *ks;
- bool avail;
-
- Private(KeyStoreEntryWatcher *_q) : QObject(_q), q(_q), ksm(this)
- {
- ks = 0;
- avail = false;
- connect(&ksm, SIGNAL(keyStoreAvailable(const QString &)), SLOT(ksm_available(const QString &)));
- }
-
- ~Private()
- {
- delete ks;
- }
-
- void start()
- {
- QStringList list = ksm.keyStores();
- foreach(const QString &storeId, list)
- ksm_available(storeId);
- }
+ KeyStoreEntryWatcher *q;
+ KeyStoreManager ksm;
+ KeyStoreEntry entry;
+ QString storeId, entryId;
+ KeyStore *ks;
+ bool avail;
+
+ Private(KeyStoreEntryWatcher *_q) : QObject(_q), q(_q), ksm(this)
+ {
+ ks = 0;
+ avail = false;
+ connect(&ksm, SIGNAL(keyStoreAvailable(QString)), SLOT(ksm_available(QString)));
+ }
+
+ ~Private()
+ {
+ delete ks;
+ }
+
+ void start()
+ {
+ QStringList list = ksm.keyStores();
+ foreach (const QString &storeId, list) {
+ ksm_available(storeId);
+ }
+ }
private slots:
- void ksm_available(const QString &_storeId)
- {
- // we only care about one store
- if(_storeId == storeId)
- {
- ks = new KeyStore(storeId, &ksm);
- connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
- ks->startAsynchronousMode();
- }
- }
-
- void ks_updated()
- {
- bool found = false;
- QList<KeyStoreEntry> list = ks->entryList();
- foreach(const KeyStoreEntry &e, list)
- {
- if(e.id() == entryId && e.isAvailable())
- {
- found = true;
- if(!avail)
- entry = e;
- break;
- }
- }
-
- if(found && !avail)
- {
- avail = true;
- emit q->available();
- }
- else if(!found && avail)
- {
- avail = false;
- emit q->unavailable();
- }
- }
-
- void ks_unavailable()
- {
- delete ks;
- ks = 0;
-
- if(avail)
- {
- avail = false;
- emit q->unavailable();
- }
- }
+ void ksm_available(const QString &_storeId)
+ {
+ // we only care about one store
+ if (_storeId == storeId) {
+ ks = new KeyStore(storeId, &ksm);
+ connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
+ ks->startAsynchronousMode();
+ }
+ }
+
+ void ks_updated()
+ {
+ bool found = false;
+ QList<KeyStoreEntry> list = ks->entryList();
+ foreach (const KeyStoreEntry &e, list) {
+ if (e.id() == entryId && e.isAvailable()) {
+ found = true;
+ if (!avail) {
+ entry = e;
+ }
+ break;
+ }
+ }
+
+ if (found && !avail) {
+ avail = true;
+ emit q->available();
+ } else if (!found && avail) {
+ avail = false;
+ emit q->unavailable();
+ }
+ }
+
+ void ks_unavailable()
+ {
+ delete ks;
+ ks = 0;
+
+ if (avail) {
+ avail = false;
+ emit q->unavailable();
+ }
+ }
};
KeyStoreEntryWatcher::KeyStoreEntryWatcher(const KeyStoreEntry &e, QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
- if(!e.isNull())
- {
- d->entry = e;
- d->storeId = e.storeId();
- d->entryId = e.id();
- d->start();
- }
+ d = new Private(this);
+ if (!e.isNull()) {
+ d->entry = e;
+ d->storeId = e.storeId();
+ d->entryId = e.id();
+ d->start();
+ }
}
KeyStoreEntryWatcher::~KeyStoreEntryWatcher()
{
- delete d;
+ delete d;
}
KeyStoreEntry KeyStoreEntryWatcher::entry() const
{
- return d->entry;
+ return d->entry;
}
//----------------------------------------------------------------------------
// KeyStore
//----------------------------------------------------------------------------
// union thingy
class KeyStoreWriteEntry
{
public:
- enum Type { TypeKeyBundle, TypeCertificate, TypeCRL, TypePGPKey };
-
- Type type;
- KeyBundle keyBundle;
- Certificate cert;
- CRL crl;
- PGPKey pgpKey;
-
- KeyStoreWriteEntry()
- {
- }
-
- KeyStoreWriteEntry(const KeyBundle &_keyBundle)
- :type(TypeKeyBundle), keyBundle(_keyBundle)
- {
- }
-
- KeyStoreWriteEntry(const Certificate &_cert)
- :type(TypeCertificate), cert(_cert)
- {
- }
-
- KeyStoreWriteEntry(const CRL &_crl)
- :type(TypeCRL), crl(_crl)
- {
- }
-
- KeyStoreWriteEntry(const PGPKey &_pgpKey)
- :type(TypePGPKey), pgpKey(_pgpKey)
- {
- }
+ enum Type { TypeKeyBundle, TypeCertificate, TypeCRL, TypePGPKey };
+
+ Type type;
+ KeyBundle keyBundle;
+ Certificate cert;
+ CRL crl;
+ PGPKey pgpKey;
+
+ KeyStoreWriteEntry()
+ {
+ }
+
+ KeyStoreWriteEntry(const KeyBundle &_keyBundle)
+ : type(TypeKeyBundle), keyBundle(_keyBundle)
+ {
+ }
+
+ KeyStoreWriteEntry(const Certificate &_cert)
+ : type(TypeCertificate), cert(_cert)
+ {
+ }
+
+ KeyStoreWriteEntry(const CRL &_crl)
+ : type(TypeCRL), crl(_crl)
+ {
+ }
+
+ KeyStoreWriteEntry(const PGPKey &_pgpKey)
+ : type(TypePGPKey), pgpKey(_pgpKey)
+ {
+ }
};
class KeyStoreOperation : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum Type { EntryList, WriteEntry, RemoveEntry };
+ enum Type { EntryList, WriteEntry, RemoveEntry };
- Type type;
- int trackerId;
+ Type type;
+ int trackerId;
- KeyStoreWriteEntry wentry; // in: WriteEntry
- QList<KeyStoreEntry> entryList; // out: EntryList
- QString entryId; // in: RemoveEntry, out: WriteEntry
- bool success; // out: RemoveEntry
+ KeyStoreWriteEntry wentry; // in: WriteEntry
+ QList<KeyStoreEntry> entryList; // out: EntryList
+ QString entryId; // in: RemoveEntry, out: WriteEntry
+ bool success; // out: RemoveEntry
- KeyStoreOperation(QObject *parent = 0)
- :QThread(parent)
- {
- }
+ KeyStoreOperation(QObject *parent = 0)
+ : QThread(parent)
+ {
+ }
- ~KeyStoreOperation()
- {
- wait();
- }
+ ~KeyStoreOperation()
+ {
+ wait();
+ }
protected:
- virtual void run()
- {
- if(type == EntryList)
+ virtual void run()
+ {
+ if (type == EntryList)
#if QT_VERSION >= 0x050000
- entryList = trackercall("entryList", QVariantList() << trackerId).value< QList<KeyStoreEntry> >();
+ entryList = trackercall("entryList", QVariantList() << trackerId).value< QList<KeyStoreEntry> >();
#else
- entryList = qVariantValue< QList<KeyStoreEntry> >(trackercall("entryList", QVariantList() << trackerId));
+ entryList = qVariantValue< QList<KeyStoreEntry> >(trackercall("entryList", QVariantList() << trackerId));
#endif
- else if(type == WriteEntry)
- {
- QVariant arg;
+ else if (type == WriteEntry) {
+ QVariant arg;
#if QT_VERSION >= 0x050000
- if(wentry.type == KeyStoreWriteEntry::TypeKeyBundle)
- arg.setValue<KeyBundle>(wentry.keyBundle);
- else if(wentry.type == KeyStoreWriteEntry::TypeCertificate)
- arg.setValue<Certificate>(wentry.cert);
- else if(wentry.type == KeyStoreWriteEntry::TypeCRL)
- arg.setValue<CRL>(wentry.crl);
- else if(wentry.type == KeyStoreWriteEntry::TypePGPKey)
- arg.setValue<PGPKey>(wentry.pgpKey);
+ if (wentry.type == KeyStoreWriteEntry::TypeKeyBundle) {
+ arg.setValue<KeyBundle>(wentry.keyBundle);
+ } else if (wentry.type == KeyStoreWriteEntry::TypeCertificate) {
+ arg.setValue<Certificate>(wentry.cert);
+ } else if (wentry.type == KeyStoreWriteEntry::TypeCRL) {
+ arg.setValue<CRL>(wentry.crl);
+ } else if (wentry.type == KeyStoreWriteEntry::TypePGPKey) {
+ arg.setValue<PGPKey>(wentry.pgpKey);
+ }
#else
- if(wentry.type == KeyStoreWriteEntry::TypeKeyBundle)
- qVariantSetValue<KeyBundle>(arg, wentry.keyBundle);
- else if(wentry.type == KeyStoreWriteEntry::TypeCertificate)
- qVariantSetValue<Certificate>(arg, wentry.cert);
- else if(wentry.type == KeyStoreWriteEntry::TypeCRL)
- qVariantSetValue<CRL>(arg, wentry.crl);
- else if(wentry.type == KeyStoreWriteEntry::TypePGPKey)
- qVariantSetValue<PGPKey>(arg, wentry.pgpKey);
+ if (wentry.type == KeyStoreWriteEntry::TypeKeyBundle) {
+ qVariantSetValue<KeyBundle>(arg, wentry.keyBundle);
+ } else if (wentry.type == KeyStoreWriteEntry::TypeCertificate) {
+ qVariantSetValue<Certificate>(arg, wentry.cert);
+ } else if (wentry.type == KeyStoreWriteEntry::TypeCRL) {
+ qVariantSetValue<CRL>(arg, wentry.crl);
+ } else if (wentry.type == KeyStoreWriteEntry::TypePGPKey) {
+ qVariantSetValue<PGPKey>(arg, wentry.pgpKey);
+ }
#endif
- // note: each variant in the argument list is resolved
- // to its native type. so even though it looks like
- // we're attempting to call a method named
- // writeEntry(QString,QVariant), we're actually
- // calling one of many possible methods, such as
- // writeEntry(QString,PGPKey) or
- // writeEntry(QString,Certificate), etc, depending
- // on the type of object we put in the variant.
- entryId = trackercall("writeEntry", QVariantList() << trackerId << arg).toString();
- }
- else // RemoveEntry
- {
- success = trackercall("removeEntry", QVariantList() << trackerId << entryId).toBool();
- }
- }
+ // note: each variant in the argument list is resolved
+ // to its native type. so even though it looks like
+ // we're attempting to call a method named
+ // writeEntry(QString,QVariant), we're actually
+ // calling one of many possible methods, such as
+ // writeEntry(QString,PGPKey) or
+ // writeEntry(QString,Certificate), etc, depending
+ // on the type of object we put in the variant.
+ entryId = trackercall("writeEntry", QVariantList() << trackerId << arg).toString();
+ } else { // RemoveEntry
+ success = trackercall("removeEntry", QVariantList() << trackerId << entryId).toBool();
+ }
+ }
};
class KeyStorePrivate : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeyStore *q;
- KeyStoreManager *ksm;
- int trackerId;
- KeyStoreTracker::Item item;
- bool async;
- bool need_update;
- QList<KeyStoreEntry> latestEntryList;
- QList<KeyStoreOperation*> ops;
-
- KeyStorePrivate(KeyStore *_q) : QObject(_q), q(_q), async(false)
- {
- }
-
- ~KeyStorePrivate()
- {
- qDeleteAll(ops);
- }
-
- // implemented below, after KeyStorePrivate is declared
- void reg();
- void unreg();
- KeyStoreTracker::Item *getItem(const QString &storeId);
- KeyStoreTracker::Item *getItem(int trackerId);
-
- void invalidate()
- {
- trackerId = -1;
- unreg();
- }
-
- bool have_entryList_op() const
- {
- foreach(KeyStoreOperation *op, ops)
- {
- if(op->type == KeyStoreOperation::EntryList)
- return true;
- }
- return false;
- }
-
- void handle_updated()
- {
- if(async)
- {
- if(!have_entryList_op())
- async_entryList();
- else
- need_update = true;
- }
- else
- emit q->updated();
- }
-
- void async_entryList()
- {
- KeyStoreOperation *op = new KeyStoreOperation(this);
- // use queued for signal-safety
- connect(op, SIGNAL(finished()), SLOT(op_finished()), Qt::QueuedConnection);
- op->type = KeyStoreOperation::EntryList;
- op->trackerId = trackerId;
- ops += op;
- op->start();
- }
-
- void async_writeEntry(const KeyStoreWriteEntry &wentry)
- {
- KeyStoreOperation *op = new KeyStoreOperation(this);
- // use queued for signal-safety
- connect(op, SIGNAL(finished()), SLOT(op_finished()), Qt::QueuedConnection);
- op->type = KeyStoreOperation::WriteEntry;
- op->trackerId = trackerId;
- op->wentry = wentry;
- ops += op;
- op->start();
- }
-
- void async_removeEntry(const QString &entryId)
- {
- KeyStoreOperation *op = new KeyStoreOperation(this);
- // use queued for signal-safety
- connect(op, SIGNAL(finished()), SLOT(op_finished()), Qt::QueuedConnection);
- op->type = KeyStoreOperation::RemoveEntry;
- op->trackerId = trackerId;
- op->entryId = entryId;
- ops += op;
- op->start();
- }
+ KeyStore *q;
+ KeyStoreManager *ksm;
+ int trackerId;
+ KeyStoreTracker::Item item;
+ bool async;
+ bool need_update;
+ QList<KeyStoreEntry> latestEntryList;
+ QList<KeyStoreOperation *> ops;
+
+ KeyStorePrivate(KeyStore *_q) : QObject(_q), q(_q), async(false)
+ {
+ }
+
+ ~KeyStorePrivate()
+ {
+ qDeleteAll(ops);
+ }
+
+ // implemented below, after KeyStorePrivate is declared
+ void reg();
+ void unreg();
+ KeyStoreTracker::Item *getItem(const QString &storeId);
+ KeyStoreTracker::Item *getItem(int trackerId);
+
+ void invalidate()
+ {
+ trackerId = -1;
+ unreg();
+ }
+
+ bool have_entryList_op() const
+ {
+ foreach (KeyStoreOperation *op, ops) {
+ if (op->type == KeyStoreOperation::EntryList) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ void handle_updated()
+ {
+ if (async) {
+ if (!have_entryList_op()) {
+ async_entryList();
+ } else {
+ need_update = true;
+ }
+ } else {
+ emit q->updated();
+ }
+ }
+
+ void async_entryList()
+ {
+ KeyStoreOperation *op = new KeyStoreOperation(this);
+ // use queued for signal-safety
+ connect(op, SIGNAL(finished()), SLOT(op_finished()), Qt::QueuedConnection);
+ op->type = KeyStoreOperation::EntryList;
+ op->trackerId = trackerId;
+ ops += op;
+ op->start();
+ }
+
+ void async_writeEntry(const KeyStoreWriteEntry &wentry)
+ {
+ KeyStoreOperation *op = new KeyStoreOperation(this);
+ // use queued for signal-safety
+ connect(op, SIGNAL(finished()), SLOT(op_finished()), Qt::QueuedConnection);
+ op->type = KeyStoreOperation::WriteEntry;
+ op->trackerId = trackerId;
+ op->wentry = wentry;
+ ops += op;
+ op->start();
+ }
+
+ void async_removeEntry(const QString &entryId)
+ {
+ KeyStoreOperation *op = new KeyStoreOperation(this);
+ // use queued for signal-safety
+ connect(op, SIGNAL(finished()), SLOT(op_finished()), Qt::QueuedConnection);
+ op->type = KeyStoreOperation::RemoveEntry;
+ op->trackerId = trackerId;
+ op->entryId = entryId;
+ ops += op;
+ op->start();
+ }
private slots:
- void op_finished()
- {
- KeyStoreOperation *op = (KeyStoreOperation *)sender();
-
- if(op->type == KeyStoreOperation::EntryList)
- {
- latestEntryList = op->entryList;
- ops.removeAll(op);
- delete op;
-
- if(need_update)
- {
- need_update = false;
- async_entryList();
- }
-
- emit q->updated();
- }
- else if(op->type == KeyStoreOperation::WriteEntry)
- {
- QString entryId = op->entryId;
- ops.removeAll(op);
- delete op;
-
- emit q->entryWritten(entryId);
- }
- else // RemoveEntry
- {
- bool success = op->success;
- ops.removeAll(op);
- delete op;
-
- emit q->entryRemoved(success);
- }
- }
+ void op_finished()
+ {
+ KeyStoreOperation *op = (KeyStoreOperation *)sender();
+
+ if (op->type == KeyStoreOperation::EntryList) {
+ latestEntryList = op->entryList;
+ ops.removeAll(op);
+ delete op;
+
+ if (need_update) {
+ need_update = false;
+ async_entryList();
+ }
+
+ emit q->updated();
+ } else if (op->type == KeyStoreOperation::WriteEntry) {
+ QString entryId = op->entryId;
+ ops.removeAll(op);
+ delete op;
+
+ emit q->entryWritten(entryId);
+ } else { // RemoveEntry
+ bool success = op->success;
+ ops.removeAll(op);
+ delete op;
+
+ emit q->entryRemoved(success);
+ }
+ }
};
KeyStore::KeyStore(const QString &id, KeyStoreManager *keyStoreManager)
-:QObject(keyStoreManager)
+ : QObject(keyStoreManager)
{
- d = new KeyStorePrivate(this);
- d->ksm = keyStoreManager;
+ d = new KeyStorePrivate(this);
+ d->ksm = keyStoreManager;
- KeyStoreTracker::Item *i = d->getItem(id);
- if(i)
- {
- d->trackerId = i->trackerId;
- d->item = *i;
- d->reg();
- }
- else
- d->trackerId = -1;
+ KeyStoreTracker::Item *i = d->getItem(id);
+ if (i) {
+ d->trackerId = i->trackerId;
+ d->item = *i;
+ d->reg();
+ } else {
+ d->trackerId = -1;
+ }
}
KeyStore::~KeyStore()
{
- if(d->trackerId != -1)
- d->unreg();
- delete d;
+ if (d->trackerId != -1) {
+ d->unreg();
+ }
+ delete d;
}
bool KeyStore::isValid() const
{
- return (d->getItem(d->trackerId) ? true : false);
+ return (d->getItem(d->trackerId) ? true : false);
}
KeyStore::Type KeyStore::type() const
{
- return d->item.type;
+ return d->item.type;
}
QString KeyStore::name() const
{
- return d->item.name;
+ return d->item.name;
}
QString KeyStore::id() const
{
- return d->item.storeId;
+ return d->item.storeId;
}
bool KeyStore::isReadOnly() const
{
- return d->item.isReadOnly;
+ return d->item.isReadOnly;
}
void KeyStore::startAsynchronousMode()
{
- if(d->async)
- return;
+ if (d->async) {
+ return;
+ }
- d->async = true;
+ d->async = true;
- // initial entrylist
- d->need_update = false;
- d->async_entryList();
+ // initial entrylist
+ d->need_update = false;
+ d->async_entryList();
}
QList<KeyStoreEntry> KeyStore::entryList() const
{
- if(d->async)
- return d->latestEntryList;
+ if (d->async) {
+ return d->latestEntryList;
+ }
- if(d->trackerId == -1)
- return QList<KeyStoreEntry>();
+ if (d->trackerId == -1) {
+ return QList<KeyStoreEntry>();
+ }
#if QT_VERSION >= 0x050000
- return trackercall("entryList", QVariantList() << d->trackerId).value< QList<KeyStoreEntry> >();
+ return trackercall("entryList", QVariantList() << d->trackerId).value< QList<KeyStoreEntry> >();
#else
- return qVariantValue< QList<KeyStoreEntry> >(trackercall("entryList", QVariantList() << d->trackerId));
+ return qVariantValue< QList<KeyStoreEntry> >(trackercall("entryList", QVariantList() << d->trackerId));
#endif
}
bool KeyStore::holdsTrustedCertificates() const
{
- QList<KeyStoreEntry::Type> list;
- if(d->trackerId == -1)
- return false;
+ QList<KeyStoreEntry::Type> list;
+ if (d->trackerId == -1) {
+ return false;
+ }
#if QT_VERSION >= 0x050000
- list = trackercall("entryTypes", QVariantList() << d->trackerId).value< QList<KeyStoreEntry::Type> >();
+ list = trackercall("entryTypes", QVariantList() << d->trackerId).value< QList<KeyStoreEntry::Type> >();
#else
- list = qVariantValue< QList<KeyStoreEntry::Type> >(trackercall("entryTypes", QVariantList() << d->trackerId));
+ list = qVariantValue< QList<KeyStoreEntry::Type> >(trackercall("entryTypes", QVariantList() << d->trackerId));
#endif
- if(list.contains(KeyStoreEntry::TypeCertificate) || list.contains(KeyStoreEntry::TypeCRL))
- return true;
- return false;
+ if (list.contains(KeyStoreEntry::TypeCertificate) || list.contains(KeyStoreEntry::TypeCRL)) {
+ return true;
+ }
+ return false;
}
bool KeyStore::holdsIdentities() const
{
- QList<KeyStoreEntry::Type> list;
- if(d->trackerId == -1)
- return false;
+ QList<KeyStoreEntry::Type> list;
+ if (d->trackerId == -1) {
+ return false;
+ }
#if QT_VERSION >= 0x050000
- list = trackercall("entryTypes", QVariantList() << d->trackerId).value< QList<KeyStoreEntry::Type> >();
+ list = trackercall("entryTypes", QVariantList() << d->trackerId).value< QList<KeyStoreEntry::Type> >();
#else
- list = qVariantValue< QList<KeyStoreEntry::Type> >(trackercall("entryTypes", QVariantList() << d->trackerId));
+ list = qVariantValue< QList<KeyStoreEntry::Type> >(trackercall("entryTypes", QVariantList() << d->trackerId));
#endif
- if(list.contains(KeyStoreEntry::TypeKeyBundle) || list.contains(KeyStoreEntry::TypePGPSecretKey))
- return true;
- return false;
+ if (list.contains(KeyStoreEntry::TypeKeyBundle) || list.contains(KeyStoreEntry::TypePGPSecretKey)) {
+ return true;
+ }
+ return false;
}
bool KeyStore::holdsPGPPublicKeys() const
{
- QList<KeyStoreEntry::Type> list;
- if(d->trackerId == -1)
- return false;
+ QList<KeyStoreEntry::Type> list;
+ if (d->trackerId == -1) {
+ return false;
+ }
#if QT_VERSION >= 0x050000
- list = trackercall("entryTypes", QVariantList() << d->trackerId).value< QList<KeyStoreEntry::Type> >();
+ list = trackercall("entryTypes", QVariantList() << d->trackerId).value< QList<KeyStoreEntry::Type> >();
#else
- list = qVariantValue< QList<KeyStoreEntry::Type> >(trackercall("entryTypes", QVariantList() << d->trackerId));
+ list = qVariantValue< QList<KeyStoreEntry::Type> >(trackercall("entryTypes", QVariantList() << d->trackerId));
#endif
- if(list.contains(KeyStoreEntry::TypePGPPublicKey))
- return true;
- return false;
+ if (list.contains(KeyStoreEntry::TypePGPPublicKey)) {
+ return true;
+ }
+ return false;
}
QString KeyStore::writeEntry(const KeyBundle &kb)
{
- if(d->async)
- {
- d->async_writeEntry(KeyStoreWriteEntry(kb));
- return QString();
- }
- else
- {
- QVariant arg;
- qVariantSetValue<KeyBundle>(arg, kb);
- return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
- }
+ if (d->async) {
+ d->async_writeEntry(KeyStoreWriteEntry(kb));
+ return QString();
+ } else {
+ QVariant arg;
+ qVariantSetValue<KeyBundle>(arg, kb);
+ return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
+ }
}
QString KeyStore::writeEntry(const Certificate &cert)
{
- if(d->async)
- {
- d->async_writeEntry(KeyStoreWriteEntry(cert));
- return QString();
- }
- else
- {
- QVariant arg;
- qVariantSetValue<Certificate>(arg, cert);
- return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
- }
+ if (d->async) {
+ d->async_writeEntry(KeyStoreWriteEntry(cert));
+ return QString();
+ } else {
+ QVariant arg;
+ qVariantSetValue<Certificate>(arg, cert);
+ return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
+ }
}
QString KeyStore::writeEntry(const CRL &crl)
{
- if(d->async)
- {
- d->async_writeEntry(KeyStoreWriteEntry(crl));
- return QString();
- }
- else
- {
- QVariant arg;
- qVariantSetValue<CRL>(arg, crl);
- return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
- }
+ if (d->async) {
+ d->async_writeEntry(KeyStoreWriteEntry(crl));
+ return QString();
+ } else {
+ QVariant arg;
+ qVariantSetValue<CRL>(arg, crl);
+ return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
+ }
}
QString KeyStore::writeEntry(const PGPKey &key)
{
- if(d->async)
- {
- d->async_writeEntry(KeyStoreWriteEntry(key));
- return QString();
- }
- else
- {
- QVariant arg;
- qVariantSetValue<PGPKey>(arg, key);
- return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
- }
+ if (d->async) {
+ d->async_writeEntry(KeyStoreWriteEntry(key));
+ return QString();
+ } else {
+ QVariant arg;
+ qVariantSetValue<PGPKey>(arg, key);
+ return trackercall("writeEntry", QVariantList() << d->trackerId << arg).toString();
+ }
}
bool KeyStore::removeEntry(const QString &id)
{
- if(d->async)
- {
- d->async_removeEntry(id);
- return false;
- }
- else
- {
- return trackercall("removeEntry", QVariantList() << d->trackerId << id).toBool();
- }
+ if (d->async) {
+ d->async_removeEntry(id);
+ return false;
+ } else {
+ return trackercall("removeEntry", QVariantList() << d->trackerId << id).toBool();
+ }
}
//----------------------------------------------------------------------------
// KeyStoreManager
//----------------------------------------------------------------------------
static void ensure_init()
{
- QMutexLocker locker(ksm_mutex());
- if(!g_ksm)
- g_ksm = new KeyStoreManagerGlobal;
+ QMutexLocker locker(ksm_mutex());
+ if (!g_ksm) {
+ g_ksm = new KeyStoreManagerGlobal;
+ }
}
// static functions
void KeyStoreManager::start()
{
- ensure_init();
- QMetaObject::invokeMethod(KeyStoreTracker::instance(), "start", Qt::QueuedConnection);
- trackercall("spinEventLoop");
+ ensure_init();
+ QMetaObject::invokeMethod(KeyStoreTracker::instance(), "start", Qt::QueuedConnection);
+ trackercall("spinEventLoop");
}
void KeyStoreManager::start(const QString &provider)
{
- ensure_init();
- QMetaObject::invokeMethod(KeyStoreTracker::instance(), "start", Qt::QueuedConnection, Q_ARG(QString, provider));
- trackercall("spinEventLoop");
+ ensure_init();
+ QMetaObject::invokeMethod(KeyStoreTracker::instance(), "start", Qt::QueuedConnection, Q_ARG(QString, provider));
+ trackercall("spinEventLoop");
}
QString KeyStoreManager::diagnosticText()
{
- ensure_init();
+ ensure_init();
- // spin one event cycle in the tracker, to receive any pending text.
- // note that since trackercall also goes through the eventloop,
- // this may end up doing two rounds. probably no big deal.
- trackercall("spinEventLoop");
+ // spin one event cycle in the tracker, to receive any pending text.
+ // note that since trackercall also goes through the eventloop,
+ // this may end up doing two rounds. probably no big deal.
+ trackercall("spinEventLoop");
- return KeyStoreTracker::instance()->getDText();
+ return KeyStoreTracker::instance()->getDText();
}
void KeyStoreManager::clearDiagnosticText()
{
- ensure_init();
- KeyStoreTracker::instance()->clearDText();
+ ensure_init();
+ KeyStoreTracker::instance()->clearDText();
}
void KeyStoreManager::scan()
{
- ensure_init();
- QMetaObject::invokeMethod(KeyStoreTracker::instance(), "scan", Qt::QueuedConnection);
+ ensure_init();
+ QMetaObject::invokeMethod(KeyStoreTracker::instance(), "scan", Qt::QueuedConnection);
}
void KeyStoreManager::shutdown()
{
- QMutexLocker locker(ksm_mutex());
- delete g_ksm;
- g_ksm = 0;
+ QMutexLocker locker(ksm_mutex());
+ delete g_ksm;
+ g_ksm = 0;
}
// object
class KeyStoreManagerPrivate : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeyStoreManager *q;
-
- QMutex m;
- QWaitCondition w;
- bool busy;
- QList<KeyStoreTracker::Item> items;
- bool pending, waiting;
-
- QMultiHash<int,KeyStore*> keyStoreForTrackerId;
- QHash<KeyStore*,int> trackerIdForKeyStore;
-
- KeyStoreManagerPrivate(KeyStoreManager *_q) : QObject(_q), q(_q)
- {
- pending = false;
- waiting = false;
- }
-
- ~KeyStoreManagerPrivate()
- {
- // invalidate registered keystores
- QList<KeyStore*> list;
- QHashIterator<KeyStore*,int> it(trackerIdForKeyStore);
- while(it.hasNext())
- {
- it.next();
- list += it.key();
- }
- foreach(KeyStore *ks, list)
- ks->d->invalidate();
- }
-
- // for keystore
- void reg(KeyStore *ks, int trackerId)
- {
- keyStoreForTrackerId.insert(trackerId, ks);
- trackerIdForKeyStore.insert(ks, trackerId);
- }
-
- void unreg(KeyStore *ks)
- {
- int trackerId = trackerIdForKeyStore.take(ks);
-
- // this is the only way I know to remove one item from a multihash
- QList<KeyStore*> vals = keyStoreForTrackerId.values(trackerId);
- keyStoreForTrackerId.remove(trackerId);
- vals.removeAll(ks);
- foreach(KeyStore *i, vals)
- keyStoreForTrackerId.insert(trackerId, i);
- }
-
- KeyStoreTracker::Item *getItem(const QString &storeId)
- {
- for(int n = 0; n < items.count(); ++n)
- {
- KeyStoreTracker::Item *i = &items[n];
- if(i->storeId == storeId)
- return i;
- }
- return 0;
- }
-
- KeyStoreTracker::Item *getItem(int trackerId)
- {
- for(int n = 0; n < items.count(); ++n)
- {
- KeyStoreTracker::Item *i = &items[n];
- if(i->trackerId == trackerId)
- return i;
- }
- return 0;
- }
-
- void do_update()
- {
- // ksm doesn't have reset or state changes so we can
- // use QPointer here for full SS.
- QPointer<QObject> self(this);
-
- bool newbusy = KeyStoreTracker::instance()->isBusy();
- QList<KeyStoreTracker::Item> newitems = KeyStoreTracker::instance()->getItems();
-
- if(!busy && newbusy)
- {
- emit q->busyStarted();
- if(!self)
- return;
- }
- if(busy && !newbusy)
- {
- emit q->busyFinished();
- if(!self)
- return;
- }
-
- QStringList here;
- QList<int> changed;
- QList<int> gone;
-
- // removed
- for(int n = 0; n < items.count(); ++n)
- {
- KeyStoreTracker::Item &i = items[n];
- bool found = false;
- for(int k = 0; k < newitems.count(); ++k)
- {
- if(i.trackerId == newitems[k].trackerId)
- {
- found = true;
- break;
- }
- }
- if(!found)
- gone += i.trackerId;
- }
-
- // changed
- for(int n = 0; n < items.count(); ++n)
- {
- KeyStoreTracker::Item &i = items[n];
- for(int k = 0; k < newitems.count(); ++k)
- {
- if(i.trackerId == newitems[k].trackerId)
- {
- if(i.updateCount < newitems[k].updateCount)
- changed += i.trackerId;
- break;
- }
- }
- }
-
- // added
- for(int n = 0; n < newitems.count(); ++n)
- {
- KeyStoreTracker::Item &i = newitems[n];
- bool found = false;
- for(int k = 0; k < items.count(); ++k)
- {
- if(i.trackerId == items[k].trackerId)
- {
- found = true;
- break;
- }
- }
- if(!found)
- here += i.storeId;
- }
-
- busy = newbusy;
- items = newitems;
-
- // signals
- foreach(int trackerId, gone)
- {
- KeyStore *ks = keyStoreForTrackerId.value(trackerId);
- if(ks)
- {
- ks->d->invalidate();
- emit ks->unavailable();
- if(!self)
- return;
- }
- }
-
- foreach(int trackerId, changed)
- {
- KeyStore *ks = keyStoreForTrackerId.value(trackerId);
- if(ks)
- {
- ks->d->handle_updated();
- if(!self)
- return;
- }
- }
-
- foreach(const QString &storeId, here)
- {
- emit q->keyStoreAvailable(storeId);
- if(!self)
- return;
- }
- }
+ KeyStoreManager *q;
+
+ QMutex m;
+ QWaitCondition w;
+ bool busy;
+ QList<KeyStoreTracker::Item> items;
+ bool pending, waiting;
+
+ QMultiHash<int, KeyStore *> keyStoreForTrackerId;
+ QHash<KeyStore *, int> trackerIdForKeyStore;
+
+ KeyStoreManagerPrivate(KeyStoreManager *_q) : QObject(_q), q(_q)
+ {
+ pending = false;
+ waiting = false;
+ }
+
+ ~KeyStoreManagerPrivate()
+ {
+ // invalidate registered keystores
+ QList<KeyStore *> list;
+ QHashIterator<KeyStore *, int> it(trackerIdForKeyStore);
+ while (it.hasNext()) {
+ it.next();
+ list += it.key();
+ }
+ foreach (KeyStore *ks, list) {
+ ks->d->invalidate();
+ }
+ }
+
+ // for keystore
+ void reg(KeyStore *ks, int trackerId)
+ {
+ keyStoreForTrackerId.insert(trackerId, ks);
+ trackerIdForKeyStore.insert(ks, trackerId);
+ }
+
+ void unreg(KeyStore *ks)
+ {
+ int trackerId = trackerIdForKeyStore.take(ks);
+
+ // this is the only way I know to remove one item from a multihash
+ QList<KeyStore *> vals = keyStoreForTrackerId.values(trackerId);
+ keyStoreForTrackerId.remove(trackerId);
+ vals.removeAll(ks);
+ foreach (KeyStore *i, vals) {
+ keyStoreForTrackerId.insert(trackerId, i);
+ }
+ }
+
+ KeyStoreTracker::Item *getItem(const QString &storeId)
+ {
+ for (int n = 0; n < items.count(); ++n) {
+ KeyStoreTracker::Item *i = &items[n];
+ if (i->storeId == storeId) {
+ return i;
+ }
+ }
+ return 0;
+ }
+
+ KeyStoreTracker::Item *getItem(int trackerId)
+ {
+ for (int n = 0; n < items.count(); ++n) {
+ KeyStoreTracker::Item *i = &items[n];
+ if (i->trackerId == trackerId) {
+ return i;
+ }
+ }
+ return 0;
+ }
+
+ void do_update()
+ {
+ // ksm doesn't have reset or state changes so we can
+ // use QPointer here for full SS.
+ QPointer<QObject> self(this);
+
+ bool newbusy = KeyStoreTracker::instance()->isBusy();
+ QList<KeyStoreTracker::Item> newitems = KeyStoreTracker::instance()->getItems();
+
+ if (!busy && newbusy) {
+ emit q->busyStarted();
+ if (!self) {
+ return;
+ }
+ }
+ if (busy && !newbusy) {
+ emit q->busyFinished();
+ if (!self) {
+ return;
+ }
+ }
+
+ QStringList here;
+ QList<int> changed;
+ QList<int> gone;
+
+ // removed
+ for (int n = 0; n < items.count(); ++n) {
+ KeyStoreTracker::Item &i = items[n];
+ bool found = false;
+ for (int k = 0; k < newitems.count(); ++k) {
+ if (i.trackerId == newitems[k].trackerId) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ gone += i.trackerId;
+ }
+ }
+
+ // changed
+ for (int n = 0; n < items.count(); ++n) {
+ KeyStoreTracker::Item &i = items[n];
+ for (int k = 0; k < newitems.count(); ++k) {
+ if (i.trackerId == newitems[k].trackerId) {
+ if (i.updateCount < newitems[k].updateCount) {
+ changed += i.trackerId;
+ }
+ break;
+ }
+ }
+ }
+
+ // added
+ for (int n = 0; n < newitems.count(); ++n) {
+ KeyStoreTracker::Item &i = newitems[n];
+ bool found = false;
+ for (int k = 0; k < items.count(); ++k) {
+ if (i.trackerId == items[k].trackerId) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ here += i.storeId;
+ }
+ }
+
+ busy = newbusy;
+ items = newitems;
+
+ // signals
+ foreach (int trackerId, gone) {
+ KeyStore *ks = keyStoreForTrackerId.value(trackerId);
+ if (ks) {
+ ks->d->invalidate();
+ emit ks->unavailable();
+ if (!self) {
+ return;
+ }
+ }
+ }
+
+ foreach (int trackerId, changed) {
+ KeyStore *ks = keyStoreForTrackerId.value(trackerId);
+ if (ks) {
+ ks->d->handle_updated();
+ if (!self) {
+ return;
+ }
+ }
+ }
+
+ foreach (const QString &storeId, here) {
+ emit q->keyStoreAvailable(storeId);
+ if (!self) {
+ return;
+ }
+ }
+ }
public slots:
- void tracker_updated()
- {
- QCA_logTextMessage(QString().sprintf("keystore: %p: tracker_updated start", q), Logger::Information);
-
- QMutexLocker locker(&m);
- if(!pending)
- {
- QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
- pending = true;
- }
- if(waiting && !KeyStoreTracker::instance()->isBusy())
- {
- busy = false;
- items = KeyStoreTracker::instance()->getItems();
- w.wakeOne();
- }
-
- QCA_logTextMessage(QString().sprintf("keystore: %p: tracker_updated end", q), Logger::Information);
- }
-
- void update()
- {
- m.lock();
- pending = false;
- m.unlock();
-
- do_update();
- }
+ void tracker_updated()
+ {
+ QCA_logTextMessage(QString().sprintf("keystore: %p: tracker_updated start", q), Logger::Information);
+
+ QMutexLocker locker(&m);
+ if (!pending) {
+ QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
+ pending = true;
+ }
+ if (waiting && !KeyStoreTracker::instance()->isBusy()) {
+ busy = false;
+ items = KeyStoreTracker::instance()->getItems();
+ w.wakeOne();
+ }
+
+ QCA_logTextMessage(QString().sprintf("keystore: %p: tracker_updated end", q), Logger::Information);
+ }
+
+ void update()
+ {
+ m.lock();
+ pending = false;
+ m.unlock();
+
+ do_update();
+ }
};
// from KeyStorePrivate
void KeyStorePrivate::reg()
{
- ksm->d->reg(q, trackerId);
+ ksm->d->reg(q, trackerId);
}
void KeyStorePrivate::unreg()
{
- ksm->d->unreg(q);
+ ksm->d->unreg(q);
}
KeyStoreTracker::Item *KeyStorePrivate::getItem(const QString &storeId)
{
- return ksm->d->getItem(storeId);
+ return ksm->d->getItem(storeId);
}
KeyStoreTracker::Item *KeyStorePrivate::getItem(int trackerId)
{
- return ksm->d->getItem(trackerId);
+ return ksm->d->getItem(trackerId);
}
KeyStoreManager::KeyStoreManager(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- ensure_init();
- d = new KeyStoreManagerPrivate(this);
- KeyStoreTracker::instance()->addTarget(d);
- sync();
+ ensure_init();
+ d = new KeyStoreManagerPrivate(this);
+ KeyStoreTracker::instance()->addTarget(d);
+ sync();
}
KeyStoreManager::~KeyStoreManager()
{
- Q_ASSERT(KeyStoreTracker::instance());
- KeyStoreTracker::instance()->removeTarget(d);
- delete d;
+ Q_ASSERT(KeyStoreTracker::instance());
+ KeyStoreTracker::instance()->removeTarget(d);
+ delete d;
}
bool KeyStoreManager::isBusy() const
{
- return d->busy;
+ return d->busy;
}
void KeyStoreManager::waitForBusyFinished()
{
- d->m.lock();
- d->busy = KeyStoreTracker::instance()->isBusy();
- if(d->busy)
- {
- d->waiting = true;
- d->w.wait(&d->m);
- d->waiting = false;
- }
- d->m.unlock();
+ d->m.lock();
+ d->busy = KeyStoreTracker::instance()->isBusy();
+ if (d->busy) {
+ d->waiting = true;
+ d->w.wait(&d->m);
+ d->waiting = false;
+ }
+ d->m.unlock();
}
QStringList KeyStoreManager::keyStores() const
{
- QStringList out;
- for(int n = 0; n < d->items.count(); ++n)
- out += d->items[n].storeId;
- return out;
+ QStringList out;
+ for (int n = 0; n < d->items.count(); ++n) {
+ out += d->items[n].storeId;
+ }
+ return out;
}
void KeyStoreManager::sync()
{
- d->busy = KeyStoreTracker::instance()->isBusy();
- d->items = KeyStoreTracker::instance()->getItems();
+ d->busy = KeyStoreTracker::instance()->isBusy();
+ d->items = KeyStoreTracker::instance()->getItems();
}
//----------------------------------------------------------------------------
// KeyStoreInfo
//----------------------------------------------------------------------------
class KeyStoreInfo::Private : public QSharedData
{
public:
- KeyStore::Type type;
- QString id, name;
+ KeyStore::Type type;
+ QString id, name;
};
KeyStoreInfo::KeyStoreInfo()
{
}
KeyStoreInfo::KeyStoreInfo(KeyStore::Type type, const QString &id, const QString &name)
-:d(new Private)
+ : d(new Private)
{
- d->type = type;
- d->id = id;
- d->name = name;
+ d->type = type;
+ d->id = id;
+ d->name = name;
}
KeyStoreInfo::KeyStoreInfo(const KeyStoreInfo &from)
-:d(from.d)
+ : d(from.d)
{
}
KeyStoreInfo::~KeyStoreInfo()
{
}
-KeyStoreInfo & KeyStoreInfo::operator=(const KeyStoreInfo &from)
+KeyStoreInfo &KeyStoreInfo::operator=(const KeyStoreInfo &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
bool KeyStoreInfo::isNull() const
{
- return (d ? false: true);
+ return (d ? false : true);
}
KeyStore::Type KeyStoreInfo::type() const
{
- return d->type;
+ return d->type;
}
QString KeyStoreInfo::id() const
{
- return d->id;
+ return d->id;
}
QString KeyStoreInfo::name() const
{
- return d->name;
+ return d->name;
}
}
#include "qca_keystore.moc"
diff --git a/src/qca_plugin.cpp b/src/qca_plugin.cpp
index 35283371..8c0893ca 100644
--- a/src/qca_plugin.cpp
+++ b/src/qca_plugin.cpp
@@ -1,811 +1,791 @@
/*
* Copyright (C) 2004-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// Note: The basic thread-safety approach with the plugin manager is that
// it is safe to add/get providers, however it is unsafe to remove them.
// The expectation is that providers will almost always be unloaded on
// application shutdown. For safe provider unload, ensure no threads are
// using the manager, the provider in question, nor any sub-objects from
// the provider.
#include "qca_plugin.h"
#include "qcaprovider.h"
#include <QCoreApplication>
#include <QDir>
#include <QFileInfo>
#include <QLibrary>
#include <QPluginLoader>
#define PLUGIN_SUBDIR "crypto"
-namespace QCA {
+namespace QCA
+{
// from qca_core.cpp
QVariantMap getProviderConfig_internal(Provider *p);
// from qca_default.cpp
QStringList skip_plugins(Provider *defaultProvider);
QStringList plugin_priorities(Provider *defaultProvider);
// stupidly simple log truncation function. if the log exceeds size chars,
// then throw out the top half, to nearest line.
QString truncate_log(const QString &in, int size)
{
- if(size < 2 || in.length() < size)
- return in;
+ if (size < 2 || in.length() < size) {
+ return in;
+ }
- // start by pointing at the last chars
- int at = in.length() - (size / 2);
+ // start by pointing at the last chars
+ int at = in.length() - (size / 2);
- // if the previous char is a newline, then this is a perfect cut.
- // otherwise, we need to skip to after the next newline.
- if(in[at - 1] != '\n')
- {
- while(at < in.length() && in[at] != '\n')
- {
- ++at;
- }
+ // if the previous char is a newline, then this is a perfect cut.
+ // otherwise, we need to skip to after the next newline.
+ if (in[at - 1] != '\n') {
+ while (at < in.length() && in[at] != '\n') {
+ ++at;
+ }
- // at this point we either reached a newline, or end of
- // the entire buffer
+ // at this point we either reached a newline, or end of
+ // the entire buffer
- if(in[at] == '\n')
- ++at;
- }
+ if (in[at] == '\n') {
+ ++at;
+ }
+ }
- return in.mid(at);
+ return in.mid(at);
}
static ProviderManager *g_pluginman = 0;
static void logDebug(const QString &str)
{
- if(g_pluginman)
- g_pluginman->appendDiagnosticText(str + '\n');
+ if (g_pluginman) {
+ g_pluginman->appendDiagnosticText(str + '\n');
+ }
}
static bool validVersion(int ver)
{
- // major version must be equal, minor version must be equal or lesser
- if((ver & 0xff0000) == (QCA_VERSION & 0xff0000)
- && (ver & 0xff00) <= (QCA_VERSION & 0xff00))
- return true;
- return false;
+ // major version must be equal, minor version must be equal or lesser
+ if ((ver & 0xff0000) == (QCA_VERSION & 0xff0000)
+ && (ver & 0xff00) <= (QCA_VERSION & 0xff00)) {
+ return true;
+ }
+ return false;
}
class PluginInstance
{
private:
- QPluginLoader *_loader;
- QObject *_instance;
- bool _ownInstance;
+ QPluginLoader *_loader;
+ QObject *_instance;
+ bool _ownInstance;
- PluginInstance()
- {
- }
+ PluginInstance()
+ {
+ }
public:
- static PluginInstance *fromFile(const QString &fname, QString *errstr = 0)
- {
- QPluginLoader *loader = new QPluginLoader(fname);
- if(!loader->load())
- {
- if(errstr)
- *errstr = QString("failed to load: %1").arg(loader->errorString());
- delete loader;
- return 0;
- }
- QObject *obj = loader->instance();
- if(!obj)
- {
- if(errstr)
- *errstr = "failed to get instance";
- loader->unload();
- delete loader;
- return 0;
- }
- PluginInstance *i = new PluginInstance;
- i->_loader = loader;
- i->_instance = obj;
- i->_ownInstance = true;
- return i;
- }
-
- static PluginInstance *fromStatic(QObject *obj)
- {
- PluginInstance *i = new PluginInstance;
- i->_loader = 0;
- i->_instance = obj;
- i->_ownInstance = false;
- return i;
- }
-
- static PluginInstance *fromInstance(QObject *obj)
- {
- PluginInstance *i = new PluginInstance;
- i->_loader = 0;
- i->_instance = obj;
- i->_ownInstance = true;
- return i;
- }
-
- ~PluginInstance()
- {
- if(_ownInstance)
- delete _instance;
-
- if(_loader)
- {
- _loader->unload();
- delete _loader;
- }
- }
-
- void claim()
- {
- if(_loader)
- _loader->moveToThread(0);
- if(_ownInstance)
- _instance->moveToThread(0);
- }
-
- QObject *instance()
- {
- return _instance;
- }
+ static PluginInstance *fromFile(const QString &fname, QString *errstr = 0)
+ {
+ QPluginLoader *loader = new QPluginLoader(fname);
+ if (!loader->load()) {
+ if (errstr) {
+ *errstr = QString("failed to load: %1").arg(loader->errorString());
+ }
+ delete loader;
+ return 0;
+ }
+ QObject *obj = loader->instance();
+ if (!obj) {
+ if (errstr) {
+ *errstr = "failed to get instance";
+ }
+ loader->unload();
+ delete loader;
+ return 0;
+ }
+ PluginInstance *i = new PluginInstance;
+ i->_loader = loader;
+ i->_instance = obj;
+ i->_ownInstance = true;
+ return i;
+ }
+
+ static PluginInstance *fromStatic(QObject *obj)
+ {
+ PluginInstance *i = new PluginInstance;
+ i->_loader = 0;
+ i->_instance = obj;
+ i->_ownInstance = false;
+ return i;
+ }
+
+ static PluginInstance *fromInstance(QObject *obj)
+ {
+ PluginInstance *i = new PluginInstance;
+ i->_loader = 0;
+ i->_instance = obj;
+ i->_ownInstance = true;
+ return i;
+ }
+
+ ~PluginInstance()
+ {
+ if (_ownInstance) {
+ delete _instance;
+ }
+
+ if (_loader) {
+ _loader->unload();
+ delete _loader;
+ }
+ }
+
+ void claim()
+ {
+ if (_loader) {
+ _loader->moveToThread(0);
+ }
+ if (_ownInstance) {
+ _instance->moveToThread(0);
+ }
+ }
+
+ QObject *instance()
+ {
+ return _instance;
+ }
};
class ProviderItem
{
public:
- QString fname;
- Provider *p;
- int priority;
- QMutex m;
-
- static ProviderItem *load(const QString &fname, QString *out_errstr = 0)
- {
- QString errstr;
- PluginInstance *i = PluginInstance::fromFile(fname, &errstr);
- if(!i)
- {
- if(out_errstr)
- *out_errstr = errstr;
- return 0;
- }
- QCAPlugin *plugin = qobject_cast<QCAPlugin*>(i->instance());
- if(!plugin)
- {
- if(out_errstr)
- *out_errstr = "does not offer QCAPlugin interface";
- delete i;
- return 0;
- }
-
- Provider *p = plugin->createProvider();
- if(!p)
- {
- if(out_errstr)
- *out_errstr = "unable to create provider";
- delete i;
- return 0;
- }
-
- ProviderItem *pi = new ProviderItem(i, p);
- pi->fname = fname;
- return pi;
- }
-
- static ProviderItem *loadStatic(QObject *instance, QString *errstr = 0)
- {
- PluginInstance *i = PluginInstance::fromStatic(instance);
- QCAPlugin *plugin = qobject_cast<QCAPlugin*>(i->instance());
- if(!plugin)
- {
- if(errstr)
- *errstr = "does not offer QCAPlugin interface";
- delete i;
- return 0;
- }
-
- Provider *p = plugin->createProvider();
- if(!p)
- {
- if(errstr)
- *errstr = "unable to create provider";
- delete i;
- return 0;
- }
-
- ProviderItem *pi = new ProviderItem(i, p);
- return pi;
- }
-
- static ProviderItem *fromClass(Provider *p)
- {
- ProviderItem *pi = new ProviderItem(0, p);
- return pi;
- }
-
- ~ProviderItem()
- {
- delete p;
- delete instance;
- }
-
- void ensureInit()
- {
- QMutexLocker locker(&m);
- if(init_done)
- return;
- init_done = true;
-
- p->init();
-
- // load config
- QVariantMap conf = getProviderConfig_internal(p);
- if(!conf.isEmpty())
- p->configChanged(conf);
- }
-
- bool initted() const
- {
- return init_done;
- }
-
- // null if not a plugin
- QObject *objectInstance() const
- {
- if(instance)
- return instance->instance();
- else
- return 0;
- }
+ QString fname;
+ Provider *p;
+ int priority;
+ QMutex m;
+
+ static ProviderItem *load(const QString &fname, QString *out_errstr = 0)
+ {
+ QString errstr;
+ PluginInstance *i = PluginInstance::fromFile(fname, &errstr);
+ if (!i) {
+ if (out_errstr) {
+ *out_errstr = errstr;
+ }
+ return 0;
+ }
+ QCAPlugin *plugin = qobject_cast<QCAPlugin *>(i->instance());
+ if (!plugin) {
+ if (out_errstr) {
+ *out_errstr = "does not offer QCAPlugin interface";
+ }
+ delete i;
+ return 0;
+ }
+
+ Provider *p = plugin->createProvider();
+ if (!p) {
+ if (out_errstr) {
+ *out_errstr = "unable to create provider";
+ }
+ delete i;
+ return 0;
+ }
+
+ ProviderItem *pi = new ProviderItem(i, p);
+ pi->fname = fname;
+ return pi;
+ }
+
+ static ProviderItem *loadStatic(QObject *instance, QString *errstr = 0)
+ {
+ PluginInstance *i = PluginInstance::fromStatic(instance);
+ QCAPlugin *plugin = qobject_cast<QCAPlugin *>(i->instance());
+ if (!plugin) {
+ if (errstr) {
+ *errstr = "does not offer QCAPlugin interface";
+ }
+ delete i;
+ return 0;
+ }
+
+ Provider *p = plugin->createProvider();
+ if (!p) {
+ if (errstr) {
+ *errstr = "unable to create provider";
+ }
+ delete i;
+ return 0;
+ }
+
+ ProviderItem *pi = new ProviderItem(i, p);
+ return pi;
+ }
+
+ static ProviderItem *fromClass(Provider *p)
+ {
+ ProviderItem *pi = new ProviderItem(0, p);
+ return pi;
+ }
+
+ ~ProviderItem()
+ {
+ delete p;
+ delete instance;
+ }
+
+ void ensureInit()
+ {
+ QMutexLocker locker(&m);
+ if (init_done) {
+ return;
+ }
+ init_done = true;
+
+ p->init();
+
+ // load config
+ QVariantMap conf = getProviderConfig_internal(p);
+ if (!conf.isEmpty()) {
+ p->configChanged(conf);
+ }
+ }
+
+ bool initted() const
+ {
+ return init_done;
+ }
+
+ // null if not a plugin
+ QObject *objectInstance() const
+ {
+ if (instance) {
+ return instance->instance();
+ } else {
+ return 0;
+ }
+ }
private:
- PluginInstance *instance;
- bool init_done;
-
- ProviderItem(PluginInstance *_instance, Provider *_p)
- {
- instance = _instance;
- p = _p;
- init_done = false;
-
- // disassociate from threads
- if(instance)
- instance->claim();
- }
+ PluginInstance *instance;
+ bool init_done;
+
+ ProviderItem(PluginInstance *_instance, Provider *_p)
+ {
+ instance = _instance;
+ p = _p;
+ init_done = false;
+
+ // disassociate from threads
+ if (instance) {
+ instance->claim();
+ }
+ }
};
ProviderManager::ProviderManager()
{
- g_pluginman = this;
- def = 0;
- scanned_static = false;
+ g_pluginman = this;
+ def = 0;
+ scanned_static = false;
}
ProviderManager::~ProviderManager()
{
- if(def)
- def->deinit();
- unloadAll();
- delete def;
- g_pluginman = 0;
+ if (def) {
+ def->deinit();
+ }
+ unloadAll();
+ delete def;
+ g_pluginman = 0;
}
void ProviderManager::scan()
{
- QMutexLocker locker(&providerMutex);
-
- // check static first, but only once
- if(!scanned_static)
- {
- logDebug("Checking Qt static plugins:");
- QObjectList list = QPluginLoader::staticInstances();
- if(list.isEmpty())
- logDebug(" (none)");
- for(int n = 0; n < list.count(); ++n)
- {
- QObject *instance = list[n];
- QString className = QString::fromLatin1(instance->metaObject()->className());
-
- QString errstr;
- ProviderItem *i = ProviderItem::loadStatic(instance, &errstr);
- if(!i)
- {
- logDebug(QString(" %1: %2").arg(className, errstr));
- continue;
- }
-
- QString providerName = i->p->name();
- if(haveAlready(providerName))
- {
- logDebug(QString(" %1: (as %2) already loaded provider, skipping").arg(className, providerName));
- delete i;
- continue;
- }
-
- int ver = i->p->qcaVersion();
- if(!validVersion(ver))
- {
- errstr.sprintf("plugin version 0x%06x is in the future", ver);
- logDebug(QString(" %1: (as %2) %3").arg(className, providerName, errstr));
- delete i;
- continue;
- }
-
- addItem(i, get_default_priority(providerName));
- logDebug(QString(" %1: loaded as %2").arg(className, providerName));
- }
- scanned_static = true;
- }
+ QMutexLocker locker(&providerMutex);
+
+ // check static first, but only once
+ if (!scanned_static) {
+ logDebug("Checking Qt static plugins:");
+ QObjectList list = QPluginLoader::staticInstances();
+ if (list.isEmpty()) {
+ logDebug(" (none)");
+ }
+ for (int n = 0; n < list.count(); ++n) {
+ QObject *instance = list[n];
+ QString className = QString::fromLatin1(instance->metaObject()->className());
+
+ QString errstr;
+ ProviderItem *i = ProviderItem::loadStatic(instance, &errstr);
+ if (!i) {
+ logDebug(QString(" %1: %2").arg(className, errstr));
+ continue;
+ }
+
+ QString providerName = i->p->name();
+ if (haveAlready(providerName)) {
+ logDebug(QString(" %1: (as %2) already loaded provider, skipping").arg(className, providerName));
+ delete i;
+ continue;
+ }
+
+ int ver = i->p->qcaVersion();
+ if (!validVersion(ver)) {
+ errstr.sprintf("plugin version 0x%06x is in the future", ver);
+ logDebug(QString(" %1: (as %2) %3").arg(className, providerName, errstr));
+ delete i;
+ continue;
+ }
+
+ addItem(i, get_default_priority(providerName));
+ logDebug(QString(" %1: loaded as %2").arg(className, providerName));
+ }
+ scanned_static = true;
+ }
#ifndef QCA_NO_PLUGINS
- if(qgetenv("QCA_NO_PLUGINS") == "1")
- return;
-
- const QStringList dirs = pluginPaths();
- if(dirs.isEmpty())
- logDebug("No Qt Library Paths");
- for(QStringList::ConstIterator it = dirs.begin(); it != dirs.end(); ++it)
- {
+ if (qgetenv("QCA_NO_PLUGINS") == "1") {
+ return;
+ }
+
+ const QStringList dirs = pluginPaths();
+ if (dirs.isEmpty()) {
+ logDebug("No Qt Library Paths");
+ }
+ for (QStringList::ConstIterator it = dirs.begin(); it != dirs.end(); ++it) {
#ifdef DEVELOPER_MODE
- logDebug(QString("Checking QCA build tree Path: %1").arg(QDir::toNativeSeparators(*it)));
+ logDebug(QString("Checking QCA build tree Path: %1").arg(QDir::toNativeSeparators(*it)));
#else
- logDebug(QString("Checking Qt Library Path: %1").arg(QDir::toNativeSeparators(*it)));
+ logDebug(QString("Checking Qt Library Path: %1").arg(QDir::toNativeSeparators(*it)));
#endif
- QDir libpath(*it);
- QDir dir(libpath.filePath(PLUGIN_SUBDIR));
- if(!dir.exists())
- {
- logDebug(" (No 'crypto' subdirectory)");
- continue;
- }
-
- QStringList entryList = dir.entryList(QDir::Files);
- if(entryList.isEmpty())
- {
- logDebug(" (No files in 'crypto' subdirectory)");
- continue;
- }
-
- foreach(const QString &maybeFile, entryList)
- {
- QFileInfo fi(dir.filePath(maybeFile));
-
- QString filePath = fi.filePath(); // file name with path
- QString fileName = fi.fileName(); // just file name
-
- if(!QLibrary::isLibrary(filePath))
- {
- logDebug(QString(" %1: not a library, skipping").arg(fileName));
- continue;
- }
-
- // make sure we haven't loaded this file before
- bool haveFile = false;
- for(int n = 0; n < providerItemList.count(); ++n)
- {
- ProviderItem *pi = providerItemList[n];
- if(!pi->fname.isEmpty() && pi->fname == filePath)
- {
- haveFile = true;
- break;
- }
- }
- if(haveFile)
- {
- logDebug(QString(" %1: already loaded file, skipping").arg(fileName));
- continue;
- }
-
- QString errstr;
- ProviderItem *i = ProviderItem::load(filePath, &errstr);
- if(!i)
- {
- logDebug(QString(" %1: %2").arg(fileName, errstr));
- continue;
- }
-
- QString className = QString::fromLatin1(i->objectInstance()->metaObject()->className());
-
- QString providerName = i->p->name();
- if(haveAlready(providerName))
- {
- logDebug(QString(" %1: (class: %2, as %3) already loaded provider, skipping").arg(fileName, className, providerName));
- delete i;
- continue;
- }
-
- int ver = i->p->qcaVersion();
- if(!validVersion(ver))
- {
- errstr.sprintf("plugin version 0x%06x is in the future", ver);
- logDebug(QString(" %1: (class: %2, as %3) %4").arg(fileName, className, providerName, errstr));
- delete i;
- continue;
- }
-
- if(skip_plugins(def).contains(providerName))
- {
- logDebug(QString(" %1: (class: %2, as %3) explicitly disabled, skipping").arg(fileName, className, providerName));
- delete i;
- continue;
- }
-
- addItem(i, get_default_priority(providerName));
- logDebug(QString(" %1: (class: %2) loaded as %3").arg(fileName, className, providerName));
- }
- }
+ QDir libpath(*it);
+ QDir dir(libpath.filePath(PLUGIN_SUBDIR));
+ if (!dir.exists()) {
+ logDebug(" (No 'crypto' subdirectory)");
+ continue;
+ }
+
+ QStringList entryList = dir.entryList(QDir::Files);
+ if (entryList.isEmpty()) {
+ logDebug(" (No files in 'crypto' subdirectory)");
+ continue;
+ }
+
+ foreach (const QString &maybeFile, entryList) {
+ QFileInfo fi(dir.filePath(maybeFile));
+
+ QString filePath = fi.filePath(); // file name with path
+ QString fileName = fi.fileName(); // just file name
+
+ if (!QLibrary::isLibrary(filePath)) {
+ logDebug(QString(" %1: not a library, skipping").arg(fileName));
+ continue;
+ }
+
+ // make sure we haven't loaded this file before
+ bool haveFile = false;
+ for (int n = 0; n < providerItemList.count(); ++n) {
+ ProviderItem *pi = providerItemList[n];
+ if (!pi->fname.isEmpty() && pi->fname == filePath) {
+ haveFile = true;
+ break;
+ }
+ }
+ if (haveFile) {
+ logDebug(QString(" %1: already loaded file, skipping").arg(fileName));
+ continue;
+ }
+
+ QString errstr;
+ ProviderItem *i = ProviderItem::load(filePath, &errstr);
+ if (!i) {
+ logDebug(QString(" %1: %2").arg(fileName, errstr));
+ continue;
+ }
+
+ QString className = QString::fromLatin1(i->objectInstance()->metaObject()->className());
+
+ QString providerName = i->p->name();
+ if (haveAlready(providerName)) {
+ logDebug(QString(" %1: (class: %2, as %3) already loaded provider, skipping").arg(fileName, className, providerName));
+ delete i;
+ continue;
+ }
+
+ int ver = i->p->qcaVersion();
+ if (!validVersion(ver)) {
+ errstr.sprintf("plugin version 0x%06x is in the future", ver);
+ logDebug(QString(" %1: (class: %2, as %3) %4").arg(fileName, className, providerName, errstr));
+ delete i;
+ continue;
+ }
+
+ if (skip_plugins(def).contains(providerName)) {
+ logDebug(QString(" %1: (class: %2, as %3) explicitly disabled, skipping").arg(fileName, className, providerName));
+ delete i;
+ continue;
+ }
+
+ addItem(i, get_default_priority(providerName));
+ logDebug(QString(" %1: (class: %2) loaded as %3").arg(fileName, className, providerName));
+ }
+ }
#endif
}
bool ProviderManager::add(Provider *p, int priority)
{
- QMutexLocker locker(&providerMutex);
-
- QString providerName = p->name();
-
- if(haveAlready(providerName))
- {
- logDebug(QString("Directly adding: %1: already loaded provider, skipping").arg(providerName));
- return false;
- }
-
- int ver = p->qcaVersion();
- if(!validVersion(ver))
- {
- QString errstr;
- errstr.sprintf("plugin version 0x%06x is in the future", ver);
- logDebug(QString("Directly adding: %1: %2").arg(providerName, errstr));
- return false;
- }
-
- ProviderItem *i = ProviderItem::fromClass(p);
- addItem(i, priority);
- logDebug(QString("Directly adding: %1: loaded").arg(providerName));
- return true;
+ QMutexLocker locker(&providerMutex);
+
+ QString providerName = p->name();
+
+ if (haveAlready(providerName)) {
+ logDebug(QString("Directly adding: %1: already loaded provider, skipping").arg(providerName));
+ return false;
+ }
+
+ int ver = p->qcaVersion();
+ if (!validVersion(ver)) {
+ QString errstr;
+ errstr.sprintf("plugin version 0x%06x is in the future", ver);
+ logDebug(QString("Directly adding: %1: %2").arg(providerName, errstr));
+ return false;
+ }
+
+ ProviderItem *i = ProviderItem::fromClass(p);
+ addItem(i, priority);
+ logDebug(QString("Directly adding: %1: loaded").arg(providerName));
+ return true;
}
bool ProviderManager::unload(const QString &name)
{
- for(int n = 0; n < providerItemList.count(); ++n)
- {
- ProviderItem *i = providerItemList[n];
- if(i->p && i->p->name() == name)
- {
- if(i->initted())
- i->p->deinit();
-
- delete i;
- providerItemList.removeAt(n);
- providerList.removeAt(n);
-
- logDebug(QString("Unloaded: %1").arg(name));
- return true;
- }
- }
-
- return false;
+ for (int n = 0; n < providerItemList.count(); ++n) {
+ ProviderItem *i = providerItemList[n];
+ if (i->p && i->p->name() == name) {
+ if (i->initted()) {
+ i->p->deinit();
+ }
+
+ delete i;
+ providerItemList.removeAt(n);
+ providerList.removeAt(n);
+
+ logDebug(QString("Unloaded: %1").arg(name));
+ return true;
+ }
+ }
+
+ return false;
}
void ProviderManager::unloadAll()
{
- foreach(ProviderItem *i, providerItemList)
- {
- if(i->initted())
- i->p->deinit();
- }
-
- while(!providerItemList.isEmpty())
- {
- ProviderItem *i = providerItemList.first();
- QString name = i->p->name();
- delete i;
- providerItemList.removeFirst();
- providerList.removeFirst();
-
- logDebug(QString("Unloaded: %1").arg(name));
- }
+ foreach (ProviderItem *i, providerItemList) {
+ if (i->initted()) {
+ i->p->deinit();
+ }
+ }
+
+ while (!providerItemList.isEmpty()) {
+ ProviderItem *i = providerItemList.first();
+ QString name = i->p->name();
+ delete i;
+ providerItemList.removeFirst();
+ providerList.removeFirst();
+
+ logDebug(QString("Unloaded: %1").arg(name));
+ }
}
void ProviderManager::setDefault(Provider *p)
{
- QMutexLocker locker(&providerMutex);
-
- if(def)
- delete def;
- def = p;
- if(def)
- {
- def->init();
- QVariantMap conf = getProviderConfig_internal(def);
- if(!conf.isEmpty())
- def->configChanged(conf);
- }
+ QMutexLocker locker(&providerMutex);
+
+ if (def) {
+ delete def;
+ }
+ def = p;
+ if (def) {
+ def->init();
+ QVariantMap conf = getProviderConfig_internal(def);
+ if (!conf.isEmpty()) {
+ def->configChanged(conf);
+ }
+ }
}
Provider *ProviderManager::find(Provider *_p) const
{
- ProviderItem *i = 0;
- Provider *p = 0;
-
- providerMutex.lock();
- if(_p == def)
- {
- p = def;
- }
- else
- {
- for(int n = 0; n < providerItemList.count(); ++n)
- {
- ProviderItem *pi = providerItemList[n];
- if(pi->p && pi->p == _p)
- {
- i = pi;
- p = pi->p;
- break;
- }
- }
- }
- providerMutex.unlock();
-
- if(i)
- i->ensureInit();
- return p;
+ ProviderItem *i = 0;
+ Provider *p = 0;
+
+ providerMutex.lock();
+ if (_p == def) {
+ p = def;
+ } else {
+ for (int n = 0; n < providerItemList.count(); ++n) {
+ ProviderItem *pi = providerItemList[n];
+ if (pi->p && pi->p == _p) {
+ i = pi;
+ p = pi->p;
+ break;
+ }
+ }
+ }
+ providerMutex.unlock();
+
+ if (i) {
+ i->ensureInit();
+ }
+ return p;
}
Provider *ProviderManager::find(const QString &name) const
{
- ProviderItem *i = 0;
- Provider *p = 0;
-
- providerMutex.lock();
- if(def && name == def->name())
- {
- p = def;
- }
- else
- {
- for(int n = 0; n < providerItemList.count(); ++n)
- {
- ProviderItem *pi = providerItemList[n];
- if(pi->p && pi->p->name() == name)
- {
- i = pi;
- p = pi->p;
- break;
- }
- }
- }
- providerMutex.unlock();
-
- if(i)
- i->ensureInit();
- return p;
+ ProviderItem *i = 0;
+ Provider *p = 0;
+
+ providerMutex.lock();
+ if (def && name == def->name()) {
+ p = def;
+ } else {
+ for (int n = 0; n < providerItemList.count(); ++n) {
+ ProviderItem *pi = providerItemList[n];
+ if (pi->p && pi->p->name() == name) {
+ i = pi;
+ p = pi->p;
+ break;
+ }
+ }
+ }
+ providerMutex.unlock();
+
+ if (i) {
+ i->ensureInit();
+ }
+ return p;
}
Provider *ProviderManager::findFor(const QString &name, const QString &type) const
{
- if(name.isEmpty())
- {
- providerMutex.lock();
- QList<ProviderItem*> list = providerItemList;
- providerMutex.unlock();
-
- // find the first one that can do it
- for(int n = 0; n < list.count(); ++n)
- {
- ProviderItem *pi = list[n];
- pi->ensureInit();
- if(pi->p && pi->p->features().contains(type))
- return pi->p;
- }
-
- // try the default provider as a last resort
- providerMutex.lock();
- Provider *p = def;
- providerMutex.unlock();
- if(p && p->features().contains(type))
- return p;
-
- return 0;
- }
- else
- {
- Provider *p = find(name);
- if(p && p->features().contains(type))
- return p;
- return 0;
- }
+ if (name.isEmpty()) {
+ providerMutex.lock();
+ QList<ProviderItem *> list = providerItemList;
+ providerMutex.unlock();
+
+ // find the first one that can do it
+ for (int n = 0; n < list.count(); ++n) {
+ ProviderItem *pi = list[n];
+ pi->ensureInit();
+ if (pi->p && pi->p->features().contains(type)) {
+ return pi->p;
+ }
+ }
+
+ // try the default provider as a last resort
+ providerMutex.lock();
+ Provider *p = def;
+ providerMutex.unlock();
+ if (p && p->features().contains(type)) {
+ return p;
+ }
+
+ return 0;
+ } else {
+ Provider *p = find(name);
+ if (p && p->features().contains(type)) {
+ return p;
+ }
+ return 0;
+ }
}
void ProviderManager::changePriority(const QString &name, int priority)
{
- QMutexLocker locker(&providerMutex);
-
- ProviderItem *i = 0;
- int n = 0;
- for(; n < providerItemList.count(); ++n)
- {
- ProviderItem *pi = providerItemList[n];
- if(pi->p && pi->p->name() == name)
- {
- i = pi;
- break;
- }
- }
- if(!i)
- return;
-
- providerItemList.removeAt(n);
- providerList.removeAt(n);
-
- addItem(i, priority);
+ QMutexLocker locker(&providerMutex);
+
+ ProviderItem *i = 0;
+ int n = 0;
+ for (; n < providerItemList.count(); ++n) {
+ ProviderItem *pi = providerItemList[n];
+ if (pi->p && pi->p->name() == name) {
+ i = pi;
+ break;
+ }
+ }
+ if (!i) {
+ return;
+ }
+
+ providerItemList.removeAt(n);
+ providerList.removeAt(n);
+
+ addItem(i, priority);
}
int ProviderManager::getPriority(const QString &name)
{
- QMutexLocker locker(&providerMutex);
-
- ProviderItem *i = 0;
- for(int n = 0; n < providerItemList.count(); ++n)
- {
- ProviderItem *pi = providerItemList[n];
- if(pi->p && pi->p->name() == name)
- {
- i = pi;
- break;
- }
- }
- if(!i)
- return -1;
-
- return i->priority;
+ QMutexLocker locker(&providerMutex);
+
+ ProviderItem *i = 0;
+ for (int n = 0; n < providerItemList.count(); ++n) {
+ ProviderItem *pi = providerItemList[n];
+ if (pi->p && pi->p->name() == name) {
+ i = pi;
+ break;
+ }
+ }
+ if (!i) {
+ return -1;
+ }
+
+ return i->priority;
}
QStringList ProviderManager::allFeatures() const
{
- QStringList featureList;
-
- providerMutex.lock();
- Provider *p = def;
- providerMutex.unlock();
- if(p)
- featureList = p->features();
-
- providerMutex.lock();
- QList<ProviderItem*> list = providerItemList;
- providerMutex.unlock();
- for(int n = 0; n < list.count(); ++n)
- {
- ProviderItem *i = list[n];
- if(i->p)
- mergeFeatures(&featureList, i->p->features());
- }
-
- return featureList;
+ QStringList featureList;
+
+ providerMutex.lock();
+ Provider *p = def;
+ providerMutex.unlock();
+ if (p) {
+ featureList = p->features();
+ }
+
+ providerMutex.lock();
+ QList<ProviderItem *> list = providerItemList;
+ providerMutex.unlock();
+ for (int n = 0; n < list.count(); ++n) {
+ ProviderItem *i = list[n];
+ if (i->p) {
+ mergeFeatures(&featureList, i->p->features());
+ }
+ }
+
+ return featureList;
}
ProviderList ProviderManager::providers() const
{
- QMutexLocker locker(&providerMutex);
+ QMutexLocker locker(&providerMutex);
- return providerList;
+ return providerList;
}
QString ProviderManager::diagnosticText() const
{
- QMutexLocker locker(&logMutex);
+ QMutexLocker locker(&logMutex);
- return dtext;
+ return dtext;
}
void ProviderManager::appendDiagnosticText(const QString &str)
{
- QMutexLocker locker(&logMutex);
+ QMutexLocker locker(&logMutex);
- dtext += str;
- dtext = truncate_log(dtext, 20000);
+ dtext += str;
+ dtext = truncate_log(dtext, 20000);
}
void ProviderManager::clearDiagnosticText()
{
- QMutexLocker locker(&logMutex);
+ QMutexLocker locker(&logMutex);
- dtext = QString();
+ dtext = QString();
}
void ProviderManager::addItem(ProviderItem *item, int priority)
{
- if(priority < 0)
- {
- // for -1, make the priority the same as the last item
- if(!providerItemList.isEmpty())
- {
- ProviderItem *last = providerItemList.last();
- item->priority = last->priority;
- }
- else
- item->priority = 0;
-
- providerItemList.append(item);
- providerList.append(item->p);
- }
- else
- {
- // place the item before any other items with same or greater priority
- int n = 0;
- for(; n < providerItemList.count(); ++n)
- {
- ProviderItem *i = providerItemList[n];
- if(i->priority >= priority)
- break;
- }
-
- item->priority = priority;
- providerItemList.insert(n, item);
- providerList.insert(n, item->p);
- }
+ if (priority < 0) {
+ // for -1, make the priority the same as the last item
+ if (!providerItemList.isEmpty()) {
+ ProviderItem *last = providerItemList.last();
+ item->priority = last->priority;
+ } else {
+ item->priority = 0;
+ }
+
+ providerItemList.append(item);
+ providerList.append(item->p);
+ } else {
+ // place the item before any other items with same or greater priority
+ int n = 0;
+ for (; n < providerItemList.count(); ++n) {
+ ProviderItem *i = providerItemList[n];
+ if (i->priority >= priority) {
+ break;
+ }
+ }
+
+ item->priority = priority;
+ providerItemList.insert(n, item);
+ providerList.insert(n, item->p);
+ }
}
bool ProviderManager::haveAlready(const QString &name) const
{
- if(def && name == def->name())
- return true;
-
- for(int n = 0; n < providerItemList.count(); ++n)
- {
- ProviderItem *pi = providerItemList[n];
- if(pi->p && pi->p->name() == name)
- return true;
- }
-
- return false;
+ if (def && name == def->name()) {
+ return true;
+ }
+
+ for (int n = 0; n < providerItemList.count(); ++n) {
+ ProviderItem *pi = providerItemList[n];
+ if (pi->p && pi->p->name() == name) {
+ return true;
+ }
+ }
+
+ return false;
}
void ProviderManager::mergeFeatures(QStringList *a, const QStringList &b)
{
- for(QStringList::ConstIterator it = b.begin(); it != b.end(); ++it)
- {
- if(!a->contains(*it))
- a->append(*it);
- }
+ for (QStringList::ConstIterator it = b.begin(); it != b.end(); ++it) {
+ if (!a->contains(*it)) {
+ a->append(*it);
+ }
+ }
}
int ProviderManager::get_default_priority(const QString &name) const
{
- QStringList list = plugin_priorities(def);
- foreach(const QString &s, list)
- {
- // qca_default already sanity checks the strings
- int n = s.indexOf(':');
- QString sname = s.mid(0, n);
- int spriority = s.mid(n + 1).toInt();
- if(sname == name)
- return spriority;
- }
- return -1;
+ QStringList list = plugin_priorities(def);
+ foreach (const QString &s, list) {
+ // qca_default already sanity checks the strings
+ int n = s.indexOf(':');
+ QString sname = s.mid(0, n);
+ int spriority = s.mid(n + 1).toInt();
+ if (sname == name) {
+ return spriority;
+ }
+ }
+ return -1;
}
}
diff --git a/src/qca_plugin.h b/src/qca_plugin.h
index f497d91b..4fa469ae 100644
--- a/src/qca_plugin.h
+++ b/src/qca_plugin.h
@@ -1,74 +1,75 @@
/*
* qca_plugin.h - Qt Cryptographic Architecture
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#ifndef QCA_PLUGIN_H
#define QCA_PLUGIN_H
// NOTE: this API is private to QCA
#include "qca_core.h"
#include <QMutex>
-namespace QCA {
+namespace QCA
+{
class ProviderItem;
class ProviderManager
{
public:
- ProviderManager();
- ~ProviderManager();
+ ProviderManager();
+ ~ProviderManager();
- void scan();
- bool add(Provider *p, int priority);
- bool 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);
+ bool 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;
- int get_default_priority(const QString &name) const;
+ 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;
+ int get_default_priority(const QString &name) const;
};
}
#endif
diff --git a/src/qca_publickey.cpp b/src/qca_publickey.cpp
index 3cd8383e..e4633d2d 100644
--- a/src/qca_publickey.cpp
+++ b/src/qca_publickey.cpp
@@ -1,1557 +1,1586 @@
/*
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_publickey.h"
#include "qcaprovider.h"
#include <QFile>
#include <QTextStream>
-namespace QCA {
+namespace QCA
+{
Provider::Context *getContext(const QString &type, const QString &provider);
Provider::Context *getContext(const QString &type, Provider *p);
bool stringToFile(const QString &fileName, const QString &content)
{
- QFile f(fileName);
- if(!f.open(QFile::WriteOnly))
- return false;
- QTextStream ts(&f);
- ts << content;
- return true;
+ QFile f(fileName);
+ if (!f.open(QFile::WriteOnly)) {
+ return false;
+ }
+ QTextStream ts(&f);
+ ts << content;
+ return true;
}
bool stringFromFile(const QString &fileName, QString *s)
{
- QFile f(fileName);
- if(!f.open(QFile::ReadOnly))
- return false;
- QTextStream ts(&f);
- *s = ts.readAll();
- return true;
+ QFile f(fileName);
+ if (!f.open(QFile::ReadOnly)) {
+ return false;
+ }
+ QTextStream ts(&f);
+ *s = ts.readAll();
+ return true;
}
bool arrayToFile(const QString &fileName, const QByteArray &content)
{
- QFile f(fileName);
- if(!f.open(QFile::WriteOnly))
- return false;
- f.write(content.data(), content.size());
- return true;
+ QFile f(fileName);
+ if (!f.open(QFile::WriteOnly)) {
+ return false;
+ }
+ f.write(content.data(), content.size());
+ return true;
}
bool arrayFromFile(const QString &fileName, QByteArray *a)
{
- QFile f(fileName);
- if(!f.open(QFile::ReadOnly))
- return false;
- *a = f.readAll();
- return true;
+ QFile f(fileName);
+ if (!f.open(QFile::ReadOnly)) {
+ return false;
+ }
+ *a = f.readAll();
+ return true;
}
bool ask_passphrase(const QString &fname, void *ptr, SecureArray *answer)
{
- PasswordAsker asker;
- asker.ask(Event::StylePassphrase, fname, ptr);
- asker.waitForResponse();
- if(!asker.accepted())
- return false;
- *answer = asker.password();
- return true;
+ PasswordAsker asker;
+ asker.ask(Event::StylePassphrase, fname, ptr);
+ asker.waitForResponse();
+ if (!asker.accepted()) {
+ return false;
+ }
+ *answer = asker.password();
+ return true;
}
ProviderList allProviders()
{
- ProviderList pl = providers();
- pl += defaultProvider();
- return pl;
+ ProviderList pl = providers();
+ pl += defaultProvider();
+ return pl;
}
Provider *providerForName(const QString &name)
{
- ProviderList pl = allProviders();
- for(int n = 0; n < pl.count(); ++n)
- {
- if(pl[n]->name() == name)
- return pl[n];
- }
- return 0;
+ ProviderList pl = allProviders();
+ for (int n = 0; n < pl.count(); ++n) {
+ if (pl[n]->name() == name) {
+ return pl[n];
+ }
+ }
+ return 0;
}
bool use_asker_fallback(ConvertResult r)
{
- // FIXME: we should only do this if we get ErrorPassphrase?
- //if(r == ErrorPassphrase)
- if(r != ConvertGood)
- return true;
- return false;
+ // FIXME: we should only do this if we get ErrorPassphrase?
+ //if(r == ErrorPassphrase)
+ if (r != ConvertGood) {
+ return true;
+ }
+ return false;
}
class Getter_GroupSet
{
public:
- static QList<DLGroupSet> getList(Provider *p)
- {
- QList<DLGroupSet> list;
- const DLGroupContext *c = static_cast<const DLGroupContext *>(getContext("dlgroup", p));
- if(!c)
- return list;
- list = c->supportedGroupSets();
- delete c;
- return list;
- }
+ static QList<DLGroupSet> getList(Provider *p)
+ {
+ QList<DLGroupSet> list;
+ const DLGroupContext *c = static_cast<const DLGroupContext *>(getContext("dlgroup", p));
+ if (!c) {
+ return list;
+ }
+ list = c->supportedGroupSets();
+ delete c;
+ return list;
+ }
};
class Getter_PBE
{
public:
- static QList<PBEAlgorithm> getList(Provider *p)
- {
- QList<PBEAlgorithm> list;
- const PKeyContext *c = static_cast<const PKeyContext *>(getContext("pkey", p));
- if(!c)
- return list;
- list = c->supportedPBEAlgorithms();
- delete c;
- return list;
- }
+ static QList<PBEAlgorithm> getList(Provider *p)
+ {
+ QList<PBEAlgorithm> list;
+ const PKeyContext *c = static_cast<const PKeyContext *>(getContext("pkey", p));
+ if (!c) {
+ return list;
+ }
+ list = c->supportedPBEAlgorithms();
+ delete c;
+ return list;
+ }
};
class Getter_Type
{
public:
- static QList<PKey::Type> getList(Provider *p)
- {
- QList<PKey::Type> list;
- const PKeyContext *c = static_cast<const PKeyContext *>(getContext("pkey", p));
- if(!c)
- return list;
- list = c->supportedTypes();
- delete c;
- return list;
- }
+ static QList<PKey::Type> getList(Provider *p)
+ {
+ QList<PKey::Type> list;
+ const PKeyContext *c = static_cast<const PKeyContext *>(getContext("pkey", p));
+ if (!c) {
+ return list;
+ }
+ list = c->supportedTypes();
+ delete c;
+ return list;
+ }
};
class Getter_IOType
{
public:
- static QList<PKey::Type> getList(Provider *p)
- {
- QList<PKey::Type> list;
- const PKeyContext *c = static_cast<const PKeyContext *>(getContext("pkey", p));
- if(!c)
- return list;
- list = c->supportedIOTypes();
- delete c;
- return list;
- }
+ static QList<PKey::Type> getList(Provider *p)
+ {
+ QList<PKey::Type> list;
+ const PKeyContext *c = static_cast<const PKeyContext *>(getContext("pkey", p));
+ if (!c) {
+ return list;
+ }
+ list = c->supportedIOTypes();
+ delete c;
+ return list;
+ }
};
template <typename I>
class Getter_PublicKey
{
public:
- // DER
- static ConvertResult fromData(PKeyContext *c, const QByteArray &in)
- {
- return c->publicFromDER(in);
- }
-
- // PEM
- static ConvertResult fromData(PKeyContext *c, const QString &in)
- {
- return c->publicFromPEM(in);
- }
-
- static PublicKey getKey(Provider *p, const I &in, const SecureArray &, ConvertResult *result)
- {
- PublicKey k;
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", p));
- if(!c)
- {
- if(result)
- *result = ErrorDecode;
- return k;
- }
- ConvertResult r = fromData(c, in);
- if(result)
- *result = r;
- if(r == ConvertGood)
- k.change(c);
- else
- delete c;
- return k;
- }
+ // DER
+ static ConvertResult fromData(PKeyContext *c, const QByteArray &in)
+ {
+ return c->publicFromDER(in);
+ }
+
+ // PEM
+ static ConvertResult fromData(PKeyContext *c, const QString &in)
+ {
+ return c->publicFromPEM(in);
+ }
+
+ static PublicKey getKey(Provider *p, const I &in, const SecureArray &, ConvertResult *result)
+ {
+ PublicKey k;
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", p));
+ if (!c) {
+ if (result) {
+ *result = ErrorDecode;
+ }
+ return k;
+ }
+ ConvertResult r = fromData(c, in);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ k.change(c);
+ } else {
+ delete c;
+ }
+ return k;
+ }
};
template <typename I>
class Getter_PrivateKey
{
public:
- // DER
- static ConvertResult fromData(PKeyContext *c, const SecureArray &in, const SecureArray &passphrase)
- {
- return c->privateFromDER(in, passphrase);
- }
-
- // PEM
- static ConvertResult fromData(PKeyContext *c, const QString &in, const SecureArray &passphrase)
- {
- return c->privateFromPEM(in, passphrase);
- }
-
- static PrivateKey getKey(Provider *p, const I &in, const SecureArray &passphrase, ConvertResult *result)
- {
- PrivateKey k;
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", p));
- if(!c)
- {
- if(result)
- *result = ErrorDecode;
- return k;
- }
- ConvertResult r = fromData(c, in, passphrase);
- if(result)
- *result = r;
- if(r == ConvertGood)
- k.change(c);
- else
- delete c;
- return k;
- }
+ // DER
+ static ConvertResult fromData(PKeyContext *c, const SecureArray &in, const SecureArray &passphrase)
+ {
+ return c->privateFromDER(in, passphrase);
+ }
+
+ // PEM
+ static ConvertResult fromData(PKeyContext *c, const QString &in, const SecureArray &passphrase)
+ {
+ return c->privateFromPEM(in, passphrase);
+ }
+
+ static PrivateKey getKey(Provider *p, const I &in, const SecureArray &passphrase, ConvertResult *result)
+ {
+ PrivateKey k;
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", p));
+ if (!c) {
+ if (result) {
+ *result = ErrorDecode;
+ }
+ return k;
+ }
+ ConvertResult r = fromData(c, in, passphrase);
+ if (result) {
+ *result = r;
+ }
+ if (r == ConvertGood) {
+ k.change(c);
+ } else {
+ delete c;
+ }
+ return k;
+ }
};
Provider *providerForGroupSet(DLGroupSet set)
{
- ProviderList pl = allProviders();
- for(int n = 0; n < pl.count(); ++n)
- {
- if(Getter_GroupSet::getList(pl[n]).contains(set))
- return pl[n];
- }
- return 0;
+ ProviderList pl = allProviders();
+ for (int n = 0; n < pl.count(); ++n) {
+ if (Getter_GroupSet::getList(pl[n]).contains(set)) {
+ return pl[n];
+ }
+ }
+ return 0;
}
Provider *providerForPBE(PBEAlgorithm alg, PKey::Type ioType, const PKeyContext *prefer = 0)
{
- Provider *preferProvider = 0;
- if(prefer)
- {
- preferProvider = prefer->provider();
- if(prefer->supportedPBEAlgorithms().contains(alg) && prefer->supportedIOTypes().contains(ioType))
- return preferProvider;
- }
+ Provider *preferProvider = 0;
+ if (prefer) {
+ preferProvider = prefer->provider();
+ if (prefer->supportedPBEAlgorithms().contains(alg) && prefer->supportedIOTypes().contains(ioType)) {
+ return preferProvider;
+ }
+ }
- ProviderList pl = allProviders();
- for(int n = 0; n < pl.count(); ++n)
- {
- if(preferProvider && pl[n] == preferProvider)
- continue;
+ ProviderList pl = allProviders();
+ for (int n = 0; n < pl.count(); ++n) {
+ if (preferProvider && pl[n] == preferProvider) {
+ continue;
+ }
- if(Getter_PBE::getList(pl[n]).contains(alg) && Getter_IOType::getList(pl[n]).contains(ioType))
- return pl[n];
- }
- return 0;
+ if (Getter_PBE::getList(pl[n]).contains(alg) && Getter_IOType::getList(pl[n]).contains(ioType)) {
+ return pl[n];
+ }
+ }
+ return 0;
}
Provider *providerForIOType(PKey::Type type, const PKeyContext *prefer = 0)
{
- Provider *preferProvider = 0;
- if(prefer)
- {
- preferProvider = prefer->provider();
- if(prefer && prefer->supportedIOTypes().contains(type))
- return preferProvider;
- }
+ Provider *preferProvider = 0;
+ if (prefer) {
+ preferProvider = prefer->provider();
+ if (prefer && prefer->supportedIOTypes().contains(type)) {
+ return preferProvider;
+ }
+ }
- ProviderList pl = allProviders();
- for(int n = 0; n < pl.count(); ++n)
- {
- if(preferProvider && pl[n] == preferProvider)
- continue;
+ ProviderList pl = allProviders();
+ for (int n = 0; n < pl.count(); ++n) {
+ if (preferProvider && pl[n] == preferProvider) {
+ continue;
+ }
- if(Getter_IOType::getList(pl[n]).contains(type))
- return pl[n];
- }
- return 0;
+ if (Getter_IOType::getList(pl[n]).contains(type)) {
+ return pl[n];
+ }
+ }
+ return 0;
}
template <typename T, typename G>
QList<T> getList(const QString &provider)
{
- QList<T> list;
-
- // single
- if(!provider.isEmpty())
- {
- Provider *p = providerForName(provider);
- if(p)
- list = G::getList(p);
- }
- // all
- else
- {
- ProviderList pl = allProviders();
- for(int n = 0; n < pl.count(); ++n)
- {
- QList<T> other = G::getList(pl[n]);
- for(int k = 0; k < other.count(); ++k)
- {
- // only add what we don't have in the list
- if(!list.contains(other[k]))
- list += other[k];
- }
- }
- }
-
- return list;
+ QList<T> list;
+
+ // single
+ if (!provider.isEmpty()) {
+ Provider *p = providerForName(provider);
+ if (p) {
+ list = G::getList(p);
+ }
+ }
+ // all
+ else {
+ ProviderList pl = allProviders();
+ for (int n = 0; n < pl.count(); ++n) {
+ QList<T> other = G::getList(pl[n]);
+ for (int k = 0; k < other.count(); ++k) {
+ // only add what we don't have in the list
+ if (!list.contains(other[k])) {
+ list += other[k];
+ }
+ }
+ }
+ }
+
+ return list;
}
template <typename T, typename G, typename I>
T getKey(const QString &provider, const I &in, const SecureArray &passphrase, ConvertResult *result)
{
- T k;
-
- // single
- if(!provider.isEmpty())
- {
- Provider *p = providerForName(provider);
- if(!p)
- return k;
- k = G::getKey(p, in, passphrase, result);
- }
- // all
- else
- {
- ProviderList pl = allProviders();
- for(int n = 0; n < pl.count(); ++n)
- {
- ConvertResult r;
- k = G::getKey(pl[n], in, passphrase, &r);
- if(result)
- *result = r;
- if(!k.isNull())
- break;
- if(r == ErrorPassphrase) // don't loop if we get this
- break;
- }
- }
-
- return k;
+ T k;
+
+ // single
+ if (!provider.isEmpty()) {
+ Provider *p = providerForName(provider);
+ if (!p) {
+ return k;
+ }
+ k = G::getKey(p, in, passphrase, result);
+ }
+ // all
+ else {
+ ProviderList pl = allProviders();
+ for (int n = 0; n < pl.count(); ++n) {
+ ConvertResult r;
+ k = G::getKey(pl[n], in, passphrase, &r);
+ if (result) {
+ *result = r;
+ }
+ if (!k.isNull()) {
+ break;
+ }
+ if (r == ErrorPassphrase) { // don't loop if we get this
+ break;
+ }
+ }
+ }
+
+ return k;
}
PBEAlgorithm get_pbe_default()
{
- return PBES2_TripleDES_SHA1;
+ return PBES2_TripleDES_SHA1;
}
static PrivateKey get_privatekey_der(const SecureArray &der, const QString &fileName, void *ptr, const SecureArray &passphrase, ConvertResult *result, const QString &provider)
{
- PrivateKey out;
- ConvertResult r;
- out = getKey<PrivateKey, Getter_PrivateKey<SecureArray>, SecureArray>(provider, der, passphrase, &r);
+ PrivateKey out;
+ ConvertResult r;
+ out = getKey<PrivateKey, Getter_PrivateKey<SecureArray>, SecureArray>(provider, der, passphrase, &r);
- // error converting without passphrase? maybe a passphrase is needed
- if(use_asker_fallback(r) && passphrase.isEmpty())
- {
- SecureArray pass;
- if(ask_passphrase(fileName, ptr, &pass))
- out = getKey<PrivateKey, Getter_PrivateKey<SecureArray>, SecureArray>(provider, der, pass, &r);
- }
- if(result)
- *result = r;
- return out;
+ // error converting without passphrase? maybe a passphrase is needed
+ if (use_asker_fallback(r) && passphrase.isEmpty()) {
+ SecureArray pass;
+ if (ask_passphrase(fileName, ptr, &pass)) {
+ out = getKey<PrivateKey, Getter_PrivateKey<SecureArray>, SecureArray>(provider, der, pass, &r);
+ }
+ }
+ if (result) {
+ *result = r;
+ }
+ return out;
}
static PrivateKey get_privatekey_pem(const QString &pem, const QString &fileName, void *ptr, const SecureArray &passphrase, ConvertResult *result, const QString &provider)
{
- PrivateKey out;
- ConvertResult r;
- out = getKey<PrivateKey, Getter_PrivateKey<QString>, QString>(provider, pem, passphrase, &r);
+ PrivateKey out;
+ ConvertResult r;
+ out = getKey<PrivateKey, Getter_PrivateKey<QString>, QString>(provider, pem, passphrase, &r);
- // error converting without passphrase? maybe a passphrase is needed
- if(use_asker_fallback(r) && passphrase.isEmpty())
- {
- SecureArray pass;
- if(ask_passphrase(fileName, ptr, &pass))
- out = getKey<PrivateKey, Getter_PrivateKey<QString>, QString>(provider, pem, pass, &r);
- }
- if(result)
- *result = r;
- return out;
+ // error converting without passphrase? maybe a passphrase is needed
+ if (use_asker_fallback(r) && passphrase.isEmpty()) {
+ SecureArray pass;
+ if (ask_passphrase(fileName, ptr, &pass)) {
+ out = getKey<PrivateKey, Getter_PrivateKey<QString>, QString>(provider, pem, pass, &r);
+ }
+ }
+ if (result) {
+ *result = r;
+ }
+ return out;
}
//----------------------------------------------------------------------------
// Global
//----------------------------------------------------------------------------
// adapted from Botan
-static const unsigned char pkcs_sha1[] =
-{
- 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02,
- 0x1A, 0x05, 0x00, 0x04, 0x14
+static const unsigned char pkcs_sha1[] = {
+ 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02,
+ 0x1A, 0x05, 0x00, 0x04, 0x14
};
-static const unsigned char pkcs_md5[] =
-{
- 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86,
- 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10
+static const unsigned char pkcs_md5[] = {
+ 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86,
+ 0xF7, 0x0D, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10
};
-static const unsigned char pkcs_md2[] =
-{
- 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86,
- 0xF7, 0x0D, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10
+static const unsigned char pkcs_md2[] = {
+ 0x30, 0x20, 0x30, 0x0C, 0x06, 0x08, 0x2A, 0x86, 0x48, 0x86,
+ 0xF7, 0x0D, 0x02, 0x02, 0x05, 0x00, 0x04, 0x10
};
-static const unsigned char pkcs_ripemd160[] =
-{
- 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02,
- 0x01, 0x05, 0x00, 0x04, 0x14
+static const unsigned char pkcs_ripemd160[] = {
+ 0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x24, 0x03, 0x02,
+ 0x01, 0x05, 0x00, 0x04, 0x14
};
QByteArray get_hash_id(const QString &name)
{
- if(name == "sha1")
- return QByteArray::fromRawData((const char *)pkcs_sha1, sizeof(pkcs_sha1));
- else if(name == "md5")
- return QByteArray::fromRawData((const char *)pkcs_md5, sizeof(pkcs_md5));
- else if(name == "md2")
- return QByteArray::fromRawData((const char *)pkcs_md2, sizeof(pkcs_md2));
- else if(name == "ripemd160")
- return QByteArray::fromRawData((const char *)pkcs_ripemd160, sizeof(pkcs_ripemd160));
- else
- return QByteArray();
+ if (name == "sha1") {
+ return QByteArray::fromRawData((const char *)pkcs_sha1, sizeof(pkcs_sha1));
+ } else if (name == "md5") {
+ return QByteArray::fromRawData((const char *)pkcs_md5, sizeof(pkcs_md5));
+ } else if (name == "md2") {
+ return QByteArray::fromRawData((const char *)pkcs_md2, sizeof(pkcs_md2));
+ } else if (name == "ripemd160") {
+ return QByteArray::fromRawData((const char *)pkcs_ripemd160, sizeof(pkcs_ripemd160));
+ } else {
+ return QByteArray();
+ }
}
QByteArray emsa3Encode(const QString &hashName, const QByteArray &digest, int size)
{
- QByteArray hash_id = get_hash_id(hashName);
- if(hash_id.isEmpty())
- return QByteArray();
-
- // logic adapted from Botan
- int basesize = hash_id.size() + digest.size() + 2;
- if(size == -1)
- size = basesize + 1; // default to 1-byte pad
- int padlen = size - basesize;
- if(padlen < 1)
- return QByteArray();
-
- QByteArray out(size, (char)0xff); // pad with 0xff
- out[0] = 0x01;
- out[padlen + 1] = 0x00;
- int at = padlen + 2;
- memcpy(out.data() + at, hash_id.data(), hash_id.size());
- at += hash_id.size();
- memcpy(out.data() + at, digest.data(), digest.size());
- return out;
+ QByteArray hash_id = get_hash_id(hashName);
+ if (hash_id.isEmpty()) {
+ return QByteArray();
+ }
+
+ // logic adapted from Botan
+ int basesize = hash_id.size() + digest.size() + 2;
+ if (size == -1) {
+ size = basesize + 1; // default to 1-byte pad
+ }
+ int padlen = size - basesize;
+ if (padlen < 1) {
+ return QByteArray();
+ }
+
+ QByteArray out(size, (char)0xff); // pad with 0xff
+ out[0] = 0x01;
+ out[padlen + 1] = 0x00;
+ int at = padlen + 2;
+ memcpy(out.data() + at, hash_id.data(), hash_id.size());
+ at += hash_id.size();
+ memcpy(out.data() + at, digest.data(), digest.size());
+ return out;
}
//----------------------------------------------------------------------------
// DLGroup
//----------------------------------------------------------------------------
class DLGroup::Private
{
public:
- BigInteger p, q, g;
+ BigInteger p, q, g;
- Private(const BigInteger &p1, const BigInteger &q1, const BigInteger &g1)
- :p(p1), q(q1), g(g1)
- {
- }
+ Private(const BigInteger &p1, const BigInteger &q1, const BigInteger &g1)
+ : p(p1), q(q1), g(g1)
+ {
+ }
};
DLGroup::DLGroup()
{
- d = 0;
+ d = 0;
}
DLGroup::DLGroup(const BigInteger &p, const BigInteger &q, const BigInteger &g)
{
- d = new Private(p, q, g);
+ d = new Private(p, q, g);
}
DLGroup::DLGroup(const BigInteger &p, const BigInteger &g)
{
- d = new Private(p, 0, g);
+ d = new Private(p, 0, g);
}
DLGroup::DLGroup(const DLGroup &from)
{
- d = 0;
- *this = from;
+ d = 0;
+ *this = from;
}
DLGroup::~DLGroup()
{
- delete d;
+ delete d;
}
-DLGroup & DLGroup::operator=(const DLGroup &from)
+DLGroup &DLGroup::operator=(const DLGroup &from)
{
- delete d;
- d = 0;
+ delete d;
+ d = 0;
- if(from.d)
- d = new Private(*from.d);
+ if (from.d) {
+ d = new Private(*from.d);
+ }
- return *this;
+ return *this;
}
QList<DLGroupSet> DLGroup::supportedGroupSets(const QString &provider)
{
- return getList<DLGroupSet, Getter_GroupSet>(provider);
+ return getList<DLGroupSet, Getter_GroupSet>(provider);
}
bool DLGroup::isNull() const
{
- return (d ? false: true);
+ return (d ? false : true);
}
BigInteger DLGroup::p() const
{
- Q_ASSERT(d);
- return d->p;
+ Q_ASSERT(d);
+ return d->p;
}
BigInteger DLGroup::q() const
{
- Q_ASSERT(d);
- return d->q;
+ Q_ASSERT(d);
+ return d->q;
}
BigInteger DLGroup::g() const
{
- Q_ASSERT(d);
- return d->g;
+ Q_ASSERT(d);
+ return d->g;
}
//----------------------------------------------------------------------------
// PKey
//----------------------------------------------------------------------------
class PKey::Private
{
public:
};
PKey::PKey()
{
- d = new Private;
+ d = new Private;
}
PKey::PKey(const QString &type, const QString &provider)
-:Algorithm(type, provider)
+ : Algorithm(type, provider)
{
- d = new Private;
+ d = new Private;
}
PKey::PKey(const PKey &from)
-:Algorithm(from)
+ : Algorithm(from)
{
- d = new Private;
- *this = from;
+ d = new Private;
+ *this = from;
}
PKey::~PKey()
{
- delete d;
+ delete d;
}
-PKey & PKey::operator=(const PKey &from)
+PKey &PKey::operator=(const PKey &from)
{
- Algorithm::operator=(from);
- *d = *from.d;
- return *this;
+ Algorithm::operator=(from);
+ *d = *from.d;
+ return *this;
}
void PKey::set(const PKey &k)
{
- *this = k;
+ *this = k;
}
void PKey::assignToPublic(PKey *dest) const
{
- dest->set(*this);
+ dest->set(*this);
- // converting private to public
- if(dest->isPrivate())
- static_cast<PKeyContext *>(dest->context())->key()->convertToPublic();
+ // converting private to public
+ if (dest->isPrivate()) {
+ static_cast<PKeyContext *>(dest->context())->key()->convertToPublic();
+ }
}
void PKey::assignToPrivate(PKey *dest) const
{
- dest->set(*this);
+ dest->set(*this);
}
QList<PKey::Type> PKey::supportedTypes(const QString &provider)
{
- return getList<Type, Getter_Type>(provider);
+ return getList<Type, Getter_Type>(provider);
}
QList<PKey::Type> PKey::supportedIOTypes(const QString &provider)
{
- return getList<Type, Getter_IOType>(provider);
+ return getList<Type, Getter_IOType>(provider);
}
bool PKey::isNull() const
{
- return (!context() ? true : false);
+ return (!context() ? true : false);
}
PKey::Type PKey::type() const
{
- if(isNull())
- return RSA; // some default so we don't explode
- return static_cast<const PKeyContext *>(context())->key()->type();
+ if (isNull()) {
+ return RSA; // some default so we don't explode
+ }
+ return static_cast<const PKeyContext *>(context())->key()->type();
}
int PKey::bitSize() const
{
- return static_cast<const PKeyContext *>(context())->key()->bits();
+ return static_cast<const PKeyContext *>(context())->key()->bits();
}
bool PKey::isRSA() const
{
- return (type() == RSA);
+ return (type() == RSA);
}
bool PKey::isDSA() const
{
- return (type() == DSA);
+ return (type() == DSA);
}
bool PKey::isDH() const
{
- return (type() == DH);
+ return (type() == DH);
}
bool PKey::isPublic() const
{
- if(isNull())
- return false;
- return !isPrivate();
+ if (isNull()) {
+ return false;
+ }
+ return !isPrivate();
}
bool PKey::isPrivate() const
{
- if(isNull())
- return false;
- return static_cast<const PKeyContext *>(context())->key()->isPrivate();
+ if (isNull()) {
+ return false;
+ }
+ return static_cast<const PKeyContext *>(context())->key()->isPrivate();
}
bool PKey::canExport() const
{
- return static_cast<const PKeyContext *>(context())->key()->canExport();
+ return static_cast<const PKeyContext *>(context())->key()->canExport();
}
bool PKey::canKeyAgree() const
{
- return isDH();
+ return isDH();
}
PublicKey PKey::toPublicKey() const
{
- PublicKey k;
- if(!isNull())
- assignToPublic(&k);
- return k;
+ PublicKey k;
+ if (!isNull()) {
+ assignToPublic(&k);
+ }
+ return k;
}
PrivateKey PKey::toPrivateKey() const
{
- PrivateKey k;
- if(!isNull() && isPrivate())
- assignToPrivate(&k);
- return k;
+ PrivateKey k;
+ if (!isNull() && isPrivate()) {
+ assignToPrivate(&k);
+ }
+ return k;
}
RSAPublicKey PKey::toRSAPublicKey() const
{
- RSAPublicKey k;
- if(!isNull() && isRSA())
- assignToPublic(&k);
- return k;
+ RSAPublicKey k;
+ if (!isNull() && isRSA()) {
+ assignToPublic(&k);
+ }
+ return k;
}
RSAPrivateKey PKey::toRSAPrivateKey() const
{
- RSAPrivateKey k;
- if(!isNull() && isRSA() && isPrivate())
- assignToPrivate(&k);
- return k;
+ RSAPrivateKey k;
+ if (!isNull() && isRSA() && isPrivate()) {
+ assignToPrivate(&k);
+ }
+ return k;
}
DSAPublicKey PKey::toDSAPublicKey() const
{
- DSAPublicKey k;
- if(!isNull() && isDSA())
- assignToPublic(&k);
- return k;
+ DSAPublicKey k;
+ if (!isNull() && isDSA()) {
+ assignToPublic(&k);
+ }
+ return k;
}
DSAPrivateKey PKey::toDSAPrivateKey() const
{
- DSAPrivateKey k;
- if(!isNull() && isDSA() && isPrivate())
- assignToPrivate(&k);
- return k;
+ DSAPrivateKey k;
+ if (!isNull() && isDSA() && isPrivate()) {
+ assignToPrivate(&k);
+ }
+ return k;
}
DHPublicKey PKey::toDHPublicKey() const
{
- DHPublicKey k;
- if(!isNull() && isDH())
- assignToPublic(&k);
- return k;
+ DHPublicKey k;
+ if (!isNull() && isDH()) {
+ assignToPublic(&k);
+ }
+ return k;
}
DHPrivateKey PKey::toDHPrivateKey() const
{
- DHPrivateKey k;
- if(!isNull() && isDH() && isPrivate())
- assignToPrivate(&k);
- return k;
+ DHPrivateKey k;
+ if (!isNull() && isDH() && isPrivate()) {
+ assignToPrivate(&k);
+ }
+ return k;
}
bool PKey::operator==(const PKey &a) const
{
- if(isNull() || a.isNull() || type() != a.type())
- return false;
+ if (isNull() || a.isNull() || type() != a.type()) {
+ return false;
+ }
- if(a.isPrivate())
- return (toPrivateKey().toDER() == a.toPrivateKey().toDER());
- else
- return (toPublicKey().toDER() == a.toPublicKey().toDER());
+ if (a.isPrivate()) {
+ return (toPrivateKey().toDER() == a.toPrivateKey().toDER());
+ } else {
+ return (toPublicKey().toDER() == a.toPublicKey().toDER());
+ }
}
bool PKey::operator!=(const PKey &a) const
{
- return !(*this == a);
+ return !(*this == a);
}
//----------------------------------------------------------------------------
// PublicKey
//----------------------------------------------------------------------------
PublicKey::PublicKey()
{
}
PublicKey::PublicKey(const QString &type, const QString &provider)
-:PKey(type, provider)
+ : PKey(type, provider)
{
}
PublicKey::PublicKey(const PrivateKey &k)
{
- set(k.toPublicKey());
+ set(k.toPublicKey());
}
PublicKey::PublicKey(const QString &fileName)
{
- *this = fromPEMFile(fileName, 0, QString());
+ *this = fromPEMFile(fileName, 0, QString());
}
PublicKey::PublicKey(const PublicKey &from)
-:PKey(from)
+ : PKey(from)
{
}
PublicKey::~PublicKey()
{
}
-PublicKey & PublicKey::operator=(const PublicKey &from)
+PublicKey &PublicKey::operator=(const PublicKey &from)
{
- PKey::operator=(from);
- return *this;
+ PKey::operator=(from);
+ return *this;
}
RSAPublicKey PublicKey::toRSA() const
{
- return toRSAPublicKey();
+ return toRSAPublicKey();
}
DSAPublicKey PublicKey::toDSA() const
{
- return toDSAPublicKey();
+ return toDSAPublicKey();
}
DHPublicKey PublicKey::toDH() const
{
- return toDHPublicKey();
+ return toDHPublicKey();
}
bool PublicKey::canEncrypt() const
{
- return isRSA();
+ return isRSA();
}
bool PublicKey::canDecrypt() const
{
- return isRSA();
+ return isRSA();
}
bool PublicKey::canVerify() const
{
- return (isRSA() || isDSA());
+ return (isRSA() || isDSA());
}
int PublicKey::maximumEncryptSize(EncryptionAlgorithm alg) const
{
- const PKeyContext* ctx = qobject_cast<const PKeyContext *>(context());
- if (ctx)
- return ctx->key()->maximumEncryptSize(alg);
- else
- return -1;
+ const PKeyContext *ctx = qobject_cast<const PKeyContext *>(context());
+ if (ctx) {
+ return ctx->key()->maximumEncryptSize(alg);
+ } else {
+ return -1;
+ }
}
SecureArray PublicKey::encrypt(const SecureArray &a, EncryptionAlgorithm alg)
{
- PKeyContext* ctx = qobject_cast<PKeyContext *>(context());
- if (ctx)
- return ctx->key()->encrypt(a, alg);
- else
- return SecureArray();
+ PKeyContext *ctx = qobject_cast<PKeyContext *>(context());
+ if (ctx) {
+ return ctx->key()->encrypt(a, alg);
+ } else {
+ return SecureArray();
+ }
}
bool PublicKey::decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg)
{
- PKeyContext* ctx = qobject_cast<PKeyContext *>(context());
- if (ctx)
- return ctx->key()->decrypt(in, out, alg);
- else
- return false;
+ PKeyContext *ctx = qobject_cast<PKeyContext *>(context());
+ if (ctx) {
+ return ctx->key()->decrypt(in, out, alg);
+ } else {
+ return false;
+ }
}
void PublicKey::startVerify(SignatureAlgorithm alg, SignatureFormat format)
{
- if(isDSA() && format == DefaultFormat)
- format = IEEE_1363;
- PKeyContext* ctx = qobject_cast<PKeyContext *>(context());
- if(ctx)
- ctx->key()->startVerify(alg, format);
+ if (isDSA() && format == DefaultFormat) {
+ format = IEEE_1363;
+ }
+ PKeyContext *ctx = qobject_cast<PKeyContext *>(context());
+ if (ctx) {
+ ctx->key()->startVerify(alg, format);
+ }
}
void PublicKey::update(const MemoryRegion &a)
{
- PKeyContext* ctx = qobject_cast<PKeyContext *>(context());
- if(ctx) {
- ctx->key()->update(a);
- }
+ PKeyContext *ctx = qobject_cast<PKeyContext *>(context());
+ if (ctx) {
+ ctx->key()->update(a);
+ }
}
bool PublicKey::validSignature(const QByteArray &sig)
{
- PKeyContext* ctx = qobject_cast<PKeyContext *>(context());
- if(ctx)
- return ctx->key()->endVerify(sig);
- return false;
+ PKeyContext *ctx = qobject_cast<PKeyContext *>(context());
+ if (ctx) {
+ return ctx->key()->endVerify(sig);
+ }
+ return false;
}
bool PublicKey::verifyMessage(const MemoryRegion &a, const QByteArray &sig, SignatureAlgorithm alg, SignatureFormat format)
{
- startVerify(alg, format);
- update(a);
- return validSignature(sig);
+ startVerify(alg, format);
+ update(a);
+ return validSignature(sig);
}
QByteArray PublicKey::toDER() const
{
- QByteArray out;
- const PKeyContext *cur = static_cast<const PKeyContext *>(context());
- Provider *p = providerForIOType(type(), cur);
- if(!p)
- return out;
- if(cur->provider() == p)
- {
- out = cur->publicToDER();
- }
- else
- {
- PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
- if(pk && pk->importKey(cur->key()))
- out = pk->publicToDER();
- delete pk;
- }
- return out;
+ QByteArray out;
+ const PKeyContext *cur = static_cast<const PKeyContext *>(context());
+ Provider *p = providerForIOType(type(), cur);
+ if (!p) {
+ return out;
+ }
+ if (cur->provider() == p) {
+ out = cur->publicToDER();
+ } else {
+ PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
+ if (pk && pk->importKey(cur->key())) {
+ out = pk->publicToDER();
+ }
+ delete pk;
+ }
+ return out;
}
QString PublicKey::toPEM() const
{
- QString out;
- const PKeyContext *cur = static_cast<const PKeyContext *>(context());
- if(!cur)
- return out;
- Provider *p = providerForIOType(type(), cur);
- if(!p)
- return out;
- if(cur->provider() == p)
- {
- out = cur->publicToPEM();
- }
- else
- {
- PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
- if(pk && pk->importKey(cur->key()))
- out = pk->publicToPEM();
- delete pk;
- }
- return out;
+ QString out;
+ const PKeyContext *cur = static_cast<const PKeyContext *>(context());
+ if (!cur) {
+ return out;
+ }
+ Provider *p = providerForIOType(type(), cur);
+ if (!p) {
+ return out;
+ }
+ if (cur->provider() == p) {
+ out = cur->publicToPEM();
+ } else {
+ PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
+ if (pk && pk->importKey(cur->key())) {
+ out = pk->publicToPEM();
+ }
+ delete pk;
+ }
+ return out;
}
bool PublicKey::toPEMFile(const QString &fileName) const
{
- return stringToFile(fileName, toPEM());
+ return stringToFile(fileName, toPEM());
}
PublicKey PublicKey::fromDER(const QByteArray &a, ConvertResult *result, const QString &provider)
{
- return getKey<PublicKey, Getter_PublicKey<QByteArray>, QByteArray>(provider, a, SecureArray(), result);
+ return getKey<PublicKey, Getter_PublicKey<QByteArray>, QByteArray>(provider, a, SecureArray(), result);
}
PublicKey PublicKey::fromPEM(const QString &s, ConvertResult *result, const QString &provider)
{
- return getKey<PublicKey, Getter_PublicKey<QString>, QString>(provider, s, SecureArray(), result);
+ return getKey<PublicKey, Getter_PublicKey<QString>, QString>(provider, s, SecureArray(), result);
}
PublicKey PublicKey::fromPEMFile(const QString &fileName, ConvertResult *result, const QString &provider)
{
- QString pem;
- if(!stringFromFile(fileName, &pem))
- {
- if(result)
- *result = ErrorFile;
- return PublicKey();
- }
- return fromPEM(pem, result, provider);
+ QString pem;
+ if (!stringFromFile(fileName, &pem)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return PublicKey();
+ }
+ return fromPEM(pem, result, provider);
}
//----------------------------------------------------------------------------
// PrivateKey
//----------------------------------------------------------------------------
PrivateKey::PrivateKey()
{
}
PrivateKey::PrivateKey(const QString &type, const QString &provider)
-:PKey(type, provider)
+ : PKey(type, provider)
{
}
PrivateKey::PrivateKey(const QString &fileName, const SecureArray &passphrase)
{
- *this = fromPEMFile(fileName, passphrase, 0, QString());
+ *this = fromPEMFile(fileName, passphrase, 0, QString());
}
PrivateKey::PrivateKey(const PrivateKey &from)
-:PKey(from)
+ : PKey(from)
{
}
PrivateKey::~PrivateKey()
{
}
-PrivateKey & PrivateKey::operator=(const PrivateKey &from)
+PrivateKey &PrivateKey::operator=(const PrivateKey &from)
{
- PKey::operator=(from);
- return *this;
+ PKey::operator=(from);
+ return *this;
}
RSAPrivateKey PrivateKey::toRSA() const
{
- return toRSAPrivateKey();
+ return toRSAPrivateKey();
}
DSAPrivateKey PrivateKey::toDSA() const
{
- return toDSAPrivateKey();
+ return toDSAPrivateKey();
}
DHPrivateKey PrivateKey::toDH() const
{
- return toDHPrivateKey();
+ return toDHPrivateKey();
}
bool PrivateKey::canDecrypt() const
{
- return isRSA();
+ return isRSA();
}
bool PrivateKey::canEncrypt() const
{
- return isRSA();
+ return isRSA();
}
bool PrivateKey::canSign() const
{
- return (isRSA() || isDSA());
+ return (isRSA() || isDSA());
}
int PrivateKey::maximumEncryptSize(EncryptionAlgorithm alg) const
{
return static_cast<const PKeyContext *>(context())->key()->maximumEncryptSize(alg);
}
bool PrivateKey::decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg)
{
- return static_cast<PKeyContext *>(context())->key()->decrypt(in, out, alg);
+ return static_cast<PKeyContext *>(context())->key()->decrypt(in, out, alg);
}
SecureArray PrivateKey::encrypt(const SecureArray &a, EncryptionAlgorithm alg)
{
- return static_cast<PKeyContext *>(context())->key()->encrypt(a, alg);
+ return static_cast<PKeyContext *>(context())->key()->encrypt(a, alg);
}
void PrivateKey::startSign(SignatureAlgorithm alg, SignatureFormat format)
{
- if(isDSA() && format == DefaultFormat)
- format = IEEE_1363;
- static_cast<PKeyContext *>(context())->key()->startSign(alg, format);
+ if (isDSA() && format == DefaultFormat) {
+ format = IEEE_1363;
+ }
+ static_cast<PKeyContext *>(context())->key()->startSign(alg, format);
}
void PrivateKey::update(const MemoryRegion &a)
{
- static_cast<PKeyContext *>(context())->key()->update(a);
+ static_cast<PKeyContext *>(context())->key()->update(a);
}
QByteArray PrivateKey::signature()
{
- return static_cast<PKeyContext *>(context())->key()->endSign();
+ return static_cast<PKeyContext *>(context())->key()->endSign();
}
QByteArray PrivateKey::signMessage(const MemoryRegion &a, SignatureAlgorithm alg, SignatureFormat format)
{
- startSign(alg, format);
- update(a);
- return signature();
+ startSign(alg, format);
+ update(a);
+ return signature();
}
SymmetricKey PrivateKey::deriveKey(const PublicKey &theirs)
{
- const PKeyContext *theirContext = static_cast<const PKeyContext *>(theirs.context());
- return static_cast<PKeyContext *>(context())->key()->deriveKey(*(theirContext->key()));
+ const PKeyContext *theirContext = static_cast<const PKeyContext *>(theirs.context());
+ return static_cast<PKeyContext *>(context())->key()->deriveKey(*(theirContext->key()));
}
QList<PBEAlgorithm> PrivateKey::supportedPBEAlgorithms(const QString &provider)
{
- return getList<PBEAlgorithm, Getter_PBE>(provider);
+ return getList<PBEAlgorithm, Getter_PBE>(provider);
}
SecureArray PrivateKey::toDER(const SecureArray &passphrase, PBEAlgorithm pbe) const
{
- SecureArray out;
- if(pbe == PBEDefault)
- pbe = get_pbe_default();
- const PKeyContext *cur = static_cast<const PKeyContext *>(context());
- Provider *p = providerForPBE(pbe, type(), cur);
- if(!p)
- return out;
- if(cur->provider() == p)
- {
- out = cur->privateToDER(passphrase, pbe);
- }
- else
- {
- PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
- if(pk->importKey(cur->key()))
- out = pk->privateToDER(passphrase, pbe);
- delete pk;
- }
- return out;
+ SecureArray out;
+ if (pbe == PBEDefault) {
+ pbe = get_pbe_default();
+ }
+ const PKeyContext *cur = static_cast<const PKeyContext *>(context());
+ Provider *p = providerForPBE(pbe, type(), cur);
+ if (!p) {
+ return out;
+ }
+ if (cur->provider() == p) {
+ out = cur->privateToDER(passphrase, pbe);
+ } else {
+ PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
+ if (pk->importKey(cur->key())) {
+ out = pk->privateToDER(passphrase, pbe);
+ }
+ delete pk;
+ }
+ return out;
}
QString PrivateKey::toPEM(const SecureArray &passphrase, PBEAlgorithm pbe) const
{
- QString out;
- if(pbe == PBEDefault)
- pbe = get_pbe_default();
- const PKeyContext *cur = static_cast<const PKeyContext *>(context());
- Provider *p = providerForPBE(pbe, type(), cur);
- if(!p)
- return out;
- if(cur->provider() == p)
- {
- out = cur->privateToPEM(passphrase, pbe);
- }
- else
- {
- PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
- if(pk->importKey(cur->key()))
- out = pk->privateToPEM(passphrase, pbe);
- delete pk;
- }
- return out;
+ QString out;
+ if (pbe == PBEDefault) {
+ pbe = get_pbe_default();
+ }
+ const PKeyContext *cur = static_cast<const PKeyContext *>(context());
+ Provider *p = providerForPBE(pbe, type(), cur);
+ if (!p) {
+ return out;
+ }
+ if (cur->provider() == p) {
+ out = cur->privateToPEM(passphrase, pbe);
+ } else {
+ PKeyContext *pk = static_cast<PKeyContext *>(getContext("pkey", p));
+ if (pk->importKey(cur->key())) {
+ out = pk->privateToPEM(passphrase, pbe);
+ }
+ delete pk;
+ }
+ return out;
}
bool PrivateKey::toPEMFile(const QString &fileName, const SecureArray &passphrase, PBEAlgorithm pbe) const
{
- return stringToFile(fileName, toPEM(passphrase, pbe));
+ return stringToFile(fileName, toPEM(passphrase, pbe));
}
PrivateKey PrivateKey::fromDER(const SecureArray &a, const SecureArray &passphrase, ConvertResult *result, const QString &provider)
{
- return get_privatekey_der(a, QString(), (void *)&a, passphrase, result, provider);
+ return get_privatekey_der(a, QString(), (void *)&a, passphrase, result, provider);
}
PrivateKey PrivateKey::fromPEM(const QString &s, const SecureArray &passphrase, ConvertResult *result, const QString &provider)
{
- return get_privatekey_pem(s, QString(), (void *)&s, passphrase, result, provider);
+ return get_privatekey_pem(s, QString(), (void *)&s, passphrase, result, provider);
}
PrivateKey PrivateKey::fromPEMFile(const QString &fileName, const SecureArray &passphrase, ConvertResult *result, const QString &provider)
{
- QString pem;
- if(!stringFromFile(fileName, &pem))
- {
- if(result)
- *result = ErrorFile;
- return PrivateKey();
- }
- return get_privatekey_pem(pem, fileName, 0, passphrase, result, provider);
+ QString pem;
+ if (!stringFromFile(fileName, &pem)) {
+ if (result) {
+ *result = ErrorFile;
+ }
+ return PrivateKey();
+ }
+ return get_privatekey_pem(pem, fileName, 0, passphrase, result, provider);
}
//----------------------------------------------------------------------------
// KeyGenerator
//----------------------------------------------------------------------------
class KeyGenerator::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- KeyGenerator *parent;
- bool blocking, wasBlocking;
- PrivateKey key;
- DLGroup group;
-
- PKeyBase *k;
- PKeyContext *dest;
- DLGroupContext *dc;
-
- Private(KeyGenerator *_parent) : QObject(_parent), parent(_parent)
- {
- k = 0;
- dest = 0;
- dc = 0;
- }
-
- ~Private()
- {
- delete k;
- delete dest;
- delete dc;
- }
+ KeyGenerator *parent;
+ bool blocking, wasBlocking;
+ PrivateKey key;
+ DLGroup group;
+
+ PKeyBase *k;
+ PKeyContext *dest;
+ DLGroupContext *dc;
+
+ Private(KeyGenerator *_parent) : QObject(_parent), parent(_parent)
+ {
+ k = 0;
+ dest = 0;
+ dc = 0;
+ }
+
+ ~Private()
+ {
+ delete k;
+ delete dest;
+ delete dc;
+ }
public slots:
- void done()
- {
- if(!k->isNull())
- {
- if(!wasBlocking)
- {
- k->setParent(0);
- k->moveToThread(0);
- }
- dest->setKey(k);
- k = 0;
-
- key.change(dest);
- dest = 0;
- }
- else
- {
- delete k;
- k = 0;
- delete dest;
- dest = 0;
- }
-
- if(!wasBlocking)
- emit parent->finished();
- }
-
- void done_group()
- {
- if(!dc->isNull())
- {
- BigInteger p, q, g;
- dc->getResult(&p, &q, &g);
- group = DLGroup(p, q, g);
- }
- delete dc;
- dc = 0;
-
- if(!wasBlocking)
- emit parent->finished();
- }
+ void done()
+ {
+ if (!k->isNull()) {
+ if (!wasBlocking) {
+ k->setParent(0);
+ k->moveToThread(0);
+ }
+ dest->setKey(k);
+ k = 0;
+
+ key.change(dest);
+ dest = 0;
+ } else {
+ delete k;
+ k = 0;
+ delete dest;
+ dest = 0;
+ }
+
+ if (!wasBlocking) {
+ emit parent->finished();
+ }
+ }
+
+ void done_group()
+ {
+ if (!dc->isNull()) {
+ BigInteger p, q, g;
+ dc->getResult(&p, &q, &g);
+ group = DLGroup(p, q, g);
+ }
+ delete dc;
+ dc = 0;
+
+ if (!wasBlocking) {
+ emit parent->finished();
+ }
+ }
};
KeyGenerator::KeyGenerator(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
- d->blocking = true;
+ d = new Private(this);
+ d->blocking = true;
}
KeyGenerator::~KeyGenerator()
{
- delete d;
+ delete d;
}
bool KeyGenerator::blockingEnabled() const
{
- return d->blocking;
+ return d->blocking;
}
void KeyGenerator::setBlockingEnabled(bool b)
{
- d->blocking = b;
+ d->blocking = b;
}
bool KeyGenerator::isBusy() const
{
- return (d->k ? true: false);
+ return (d->k ? true : false);
}
PrivateKey KeyGenerator::createRSA(int bits, int exp, const QString &provider)
{
- if(isBusy())
- return PrivateKey();
+ if (isBusy()) {
+ return PrivateKey();
+ }
- d->key = PrivateKey();
- d->wasBlocking = d->blocking;
- d->k = static_cast<RSAContext *>(getContext("rsa", provider));
- if (!d->k)
- return PrivateKey();
- d->dest = static_cast<PKeyContext *>(getContext("pkey", d->k->provider()));
+ d->key = PrivateKey();
+ d->wasBlocking = d->blocking;
+ d->k = static_cast<RSAContext *>(getContext("rsa", provider));
+ if (!d->k) {
+ return PrivateKey();
+ }
+ d->dest = static_cast<PKeyContext *>(getContext("pkey", d->k->provider()));
- if(!d->blocking)
- {
- d->k->moveToThread(thread());
- d->k->setParent(d);
- connect(d->k, SIGNAL(finished()), d, SLOT(done()));
- static_cast<RSAContext *>(d->k)->createPrivate(bits, exp, false);
- }
- else
- {
- static_cast<RSAContext *>(d->k)->createPrivate(bits, exp, true);
- d->done();
- }
+ if (!d->blocking) {
+ d->k->moveToThread(thread());
+ d->k->setParent(d);
+ connect(d->k, SIGNAL(finished()), d, SLOT(done()));
+ static_cast<RSAContext *>(d->k)->createPrivate(bits, exp, false);
+ } else {
+ static_cast<RSAContext *>(d->k)->createPrivate(bits, exp, true);
+ d->done();
+ }
- return d->key;
+ return d->key;
}
PrivateKey KeyGenerator::createDSA(const DLGroup &domain, const QString &provider)
{
- if(isBusy())
- return PrivateKey();
+ if (isBusy()) {
+ return PrivateKey();
+ }
- d->key = PrivateKey();
- d->wasBlocking = d->blocking;
- d->k = static_cast<DSAContext *>(getContext("dsa", provider));
- d->dest = static_cast<PKeyContext *>(getContext("pkey", d->k->provider()));
+ d->key = PrivateKey();
+ d->wasBlocking = d->blocking;
+ d->k = static_cast<DSAContext *>(getContext("dsa", provider));
+ d->dest = static_cast<PKeyContext *>(getContext("pkey", d->k->provider()));
- if(!d->blocking)
- {
- d->k->moveToThread(thread());
- d->k->setParent(d);
- connect(d->k, SIGNAL(finished()), d, SLOT(done()));
- static_cast<DSAContext *>(d->k)->createPrivate(domain, false);
- }
- else
- {
- static_cast<DSAContext *>(d->k)->createPrivate(domain, true);
- d->done();
- }
+ if (!d->blocking) {
+ d->k->moveToThread(thread());
+ d->k->setParent(d);
+ connect(d->k, SIGNAL(finished()), d, SLOT(done()));
+ static_cast<DSAContext *>(d->k)->createPrivate(domain, false);
+ } else {
+ static_cast<DSAContext *>(d->k)->createPrivate(domain, true);
+ d->done();
+ }
- return d->key;
+ return d->key;
}
PrivateKey KeyGenerator::createDH(const DLGroup &domain, const QString &provider)
{
- if(isBusy())
- return PrivateKey();
+ if (isBusy()) {
+ return PrivateKey();
+ }
- d->key = PrivateKey();
- d->wasBlocking = d->blocking;
- d->k = static_cast<DHContext *>(getContext("dh", provider));
- d->dest = static_cast<PKeyContext *>(getContext("pkey", d->k->provider()));
+ d->key = PrivateKey();
+ d->wasBlocking = d->blocking;
+ d->k = static_cast<DHContext *>(getContext("dh", provider));
+ d->dest = static_cast<PKeyContext *>(getContext("pkey", d->k->provider()));
- if(!d->blocking)
- {
- d->k->moveToThread(thread());
- d->k->setParent(d);
- connect(d->k, SIGNAL(finished()), d, SLOT(done()));
- static_cast<DHContext *>(d->k)->createPrivate(domain, false);
- }
- else
- {
- static_cast<DHContext *>(d->k)->createPrivate(domain, true);
- d->done();
- }
+ if (!d->blocking) {
+ d->k->moveToThread(thread());
+ d->k->setParent(d);
+ connect(d->k, SIGNAL(finished()), d, SLOT(done()));
+ static_cast<DHContext *>(d->k)->createPrivate(domain, false);
+ } else {
+ static_cast<DHContext *>(d->k)->createPrivate(domain, true);
+ d->done();
+ }
- return d->key;
+ return d->key;
}
PrivateKey KeyGenerator::key() const
{
- return d->key;
+ return d->key;
}
DLGroup KeyGenerator::createDLGroup(QCA::DLGroupSet set, const QString &provider)
{
- if(isBusy())
- return DLGroup();
+ if (isBusy()) {
+ return DLGroup();
+ }
- Provider *p;
- if(!provider.isEmpty())
- p = providerForName(provider);
- else
- p = providerForGroupSet(set);
+ Provider *p;
+ if (!provider.isEmpty()) {
+ p = providerForName(provider);
+ } else {
+ p = providerForGroupSet(set);
+ }
- d->dc = static_cast<DLGroupContext *>(getContext("dlgroup", p));
- d->group = DLGroup();
+ d->dc = static_cast<DLGroupContext *>(getContext("dlgroup", p));
+ d->group = DLGroup();
- if (d->dc)
- {
- d->wasBlocking = d->blocking;
- if(!d->blocking)
- {
- connect(d->dc, SIGNAL(finished()), d, SLOT(done_group()));
- d->dc->fetchGroup(set, false);
- }
- else
- {
- d->dc->fetchGroup(set, true);
- d->done_group();
- }
- }
+ if (d->dc) {
+ d->wasBlocking = d->blocking;
+ if (!d->blocking) {
+ connect(d->dc, SIGNAL(finished()), d, SLOT(done_group()));
+ d->dc->fetchGroup(set, false);
+ } else {
+ d->dc->fetchGroup(set, true);
+ d->done_group();
+ }
+ }
- return d->group;
+ return d->group;
}
DLGroup KeyGenerator::dlGroup() const
{
- return d->group;
+ return d->group;
}
//----------------------------------------------------------------------------
// RSAPublicKey
//----------------------------------------------------------------------------
RSAPublicKey::RSAPublicKey()
{
}
RSAPublicKey::RSAPublicKey(const BigInteger &n, const BigInteger &e, const QString &provider)
{
- RSAContext *k = static_cast<RSAContext *>(getContext("rsa", provider));
- k->createPublic(n, e);
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
- c->setKey(k);
- change(c);
+ RSAContext *k = static_cast<RSAContext *>(getContext("rsa", provider));
+ k->createPublic(n, e);
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
+ c->setKey(k);
+ change(c);
}
RSAPublicKey::RSAPublicKey(const RSAPrivateKey &k)
-:PublicKey(k)
+ : PublicKey(k)
{
}
BigInteger RSAPublicKey::n() const
{
- return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->n();
+ return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->n();
}
BigInteger RSAPublicKey::e() const
{
- return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->e();
+ return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->e();
}
//----------------------------------------------------------------------------
// RSAPrivateKey
//----------------------------------------------------------------------------
RSAPrivateKey::RSAPrivateKey()
{
}
RSAPrivateKey::RSAPrivateKey(const BigInteger &n, const BigInteger &e, const BigInteger &p, const BigInteger &q, const BigInteger &d, const QString &provider)
{
- RSAContext *k = static_cast<RSAContext *>(getContext("rsa", provider));
- k->createPrivate(n, e, p, q, d);
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
- c->setKey(k);
- change(c);
+ RSAContext *k = static_cast<RSAContext *>(getContext("rsa", provider));
+ k->createPrivate(n, e, p, q, d);
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
+ c->setKey(k);
+ change(c);
}
BigInteger RSAPrivateKey::n() const
{
- return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->n();
+ return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->n();
}
BigInteger RSAPrivateKey::e() const
{
- return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->e();
+ return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->e();
}
BigInteger RSAPrivateKey::p() const
{
- return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->p();
+ return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->p();
}
BigInteger RSAPrivateKey::q() const
{
- return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->q();
+ return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->q();
}
BigInteger RSAPrivateKey::d() const
{
- return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->d();
+ return static_cast<const RSAContext *>(static_cast<const PKeyContext *>(context())->key())->d();
}
//----------------------------------------------------------------------------
// DSAPublicKey
//----------------------------------------------------------------------------
DSAPublicKey::DSAPublicKey()
{
}
DSAPublicKey::DSAPublicKey(const DLGroup &domain, const BigInteger &y, const QString &provider)
{
- DSAContext *k = static_cast<DSAContext *>(getContext("dsa", provider));
- k->createPublic(domain, y);
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
- c->setKey(k);
- change(c);
+ DSAContext *k = static_cast<DSAContext *>(getContext("dsa", provider));
+ k->createPublic(domain, y);
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
+ c->setKey(k);
+ change(c);
}
DSAPublicKey::DSAPublicKey(const DSAPrivateKey &k)
-:PublicKey(k)
+ : PublicKey(k)
{
}
DLGroup DSAPublicKey::domain() const
{
- return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
+ return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
}
BigInteger DSAPublicKey::y() const
{
- return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->y();
+ return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->y();
}
//----------------------------------------------------------------------------
// DSAPrivateKey
//----------------------------------------------------------------------------
DSAPrivateKey::DSAPrivateKey()
{
}
DSAPrivateKey::DSAPrivateKey(const DLGroup &domain, const BigInteger &y, const BigInteger &x, const QString &provider)
{
- DSAContext *k = static_cast<DSAContext *>(getContext("dsa", provider));
- k->createPrivate(domain, y, x);
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
- c->setKey(k);
- change(c);
+ DSAContext *k = static_cast<DSAContext *>(getContext("dsa", provider));
+ k->createPrivate(domain, y, x);
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
+ c->setKey(k);
+ change(c);
}
DLGroup DSAPrivateKey::domain() const
{
- return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
+ return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
}
BigInteger DSAPrivateKey::y() const
{
- return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->y();
+ return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->y();
}
BigInteger DSAPrivateKey::x() const
{
- return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->x();
+ return static_cast<const DSAContext *>(static_cast<const PKeyContext *>(context())->key())->x();
}
//----------------------------------------------------------------------------
// DHPublicKey
//----------------------------------------------------------------------------
DHPublicKey::DHPublicKey()
{
}
DHPublicKey::DHPublicKey(const DLGroup &domain, const BigInteger &y, const QString &provider)
{
- DHContext *k = static_cast<DHContext *>(getContext("dh", provider));
- k->createPublic(domain, y);
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
- c->setKey(k);
- change(c);
+ DHContext *k = static_cast<DHContext *>(getContext("dh", provider));
+ k->createPublic(domain, y);
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
+ c->setKey(k);
+ change(c);
}
DHPublicKey::DHPublicKey(const DHPrivateKey &k)
-:PublicKey(k)
+ : PublicKey(k)
{
}
DLGroup DHPublicKey::domain() const
{
- return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
+ return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
}
BigInteger DHPublicKey::y() const
{
- return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->y();
+ return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->y();
}
//----------------------------------------------------------------------------
// DHPrivateKey
//----------------------------------------------------------------------------
DHPrivateKey::DHPrivateKey()
{
}
DHPrivateKey::DHPrivateKey(const DLGroup &domain, const BigInteger &y, const BigInteger &x, const QString &provider)
{
- DHContext *k = static_cast<DHContext *>(getContext("dh", provider));
- k->createPrivate(domain, y, x);
- PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
- c->setKey(k);
- change(c);
+ DHContext *k = static_cast<DHContext *>(getContext("dh", provider));
+ k->createPrivate(domain, y, x);
+ PKeyContext *c = static_cast<PKeyContext *>(getContext("pkey", k->provider()));
+ c->setKey(k);
+ change(c);
}
DLGroup DHPrivateKey::domain() const
{
- return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
+ return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->domain();
}
BigInteger DHPrivateKey::y() const
{
- return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->y();
+ return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->y();
}
BigInteger DHPrivateKey::x() const
{
- return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->x();
+ return static_cast<const DHContext *>(static_cast<const PKeyContext *>(context())->key())->x();
}
}
#include "qca_publickey.moc"
diff --git a/src/qca_safeobj.h b/src/qca_safeobj.h
index 5e0ff146..26de5918 100644
--- a/src/qca_safeobj.h
+++ b/src/qca_safeobj.h
@@ -1,79 +1,90 @@
/*
* qca_safeobj.h - Qt Cryptographic Architecture
* Copyright (C) 2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#ifndef QCA_SAFEOBJ_H
#define QCA_SAFEOBJ_H
// NOTE: this API is private to QCA
#include <QSocketNotifier>
#include <stdio.h>
-namespace QCA {
+namespace QCA
+{
// This function performs the following steps:
// obj->disconnect(owner); // to prevent future signals to owner
// obj->setParent(0); // to prevent delete if parent is deleted
// obj->deleteLater(); // now we can forget about the object
inline void releaseAndDeleteLater(QObject *owner, QObject *obj)
{
- obj->disconnect(owner);
- obj->setParent(0);
- obj->deleteLater();
+ obj->disconnect(owner);
+ obj->setParent(0);
+ obj->deleteLater();
}
-
-
class SafeSocketNotifier : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SafeSocketNotifier(int socket, QSocketNotifier::Type type,
- QObject *parent = 0) :
- QObject(parent)
- {
- sn = new QSocketNotifier(socket, type, this);
- connect(sn, SIGNAL(activated(int)), SIGNAL(activated(int)));
- }
+ SafeSocketNotifier(int socket, QSocketNotifier::Type type,
+ QObject *parent = 0) :
+ QObject(parent)
+ {
+ sn = new QSocketNotifier(socket, type, this);
+ connect(sn, SIGNAL(activated(int)), SIGNAL(activated(int)));
+ }
- ~SafeSocketNotifier()
- {
- sn->setEnabled(false);
- releaseAndDeleteLater(this, sn);
- }
+ ~SafeSocketNotifier()
+ {
+ sn->setEnabled(false);
+ releaseAndDeleteLater(this, sn);
+ }
- bool isEnabled() const { return sn->isEnabled(); }
- int socket() const { return sn->socket(); }
- QSocketNotifier::Type type() const { return sn->type(); }
+ bool isEnabled() const
+ {
+ return sn->isEnabled();
+ }
+ int socket() const
+ {
+ return sn->socket();
+ }
+ QSocketNotifier::Type type() const
+ {
+ return sn->type();
+ }
public slots:
- void setEnabled(bool enable) { sn->setEnabled(enable); }
+ void setEnabled(bool enable)
+ {
+ sn->setEnabled(enable);
+ }
signals:
- void activated(int socket);
+ void activated(int socket);
private:
- QSocketNotifier *sn;
+ QSocketNotifier *sn;
};
}
#endif
diff --git a/src/qca_safetimer.cpp b/src/qca_safetimer.cpp
index f497856c..b4bd5f38 100644
--- a/src/qca_safetimer.cpp
+++ b/src/qca_safetimer.cpp
@@ -1,246 +1,238 @@
/*
* qca_safetimer.cpp - Qt Cryptographic Architecture
* Copyright (C) 2014 Ivan Romanov <drizt@land.ru>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_safetimer.h"
#include <QElapsedTimer>
#include <qmath.h>
#include <QTimerEvent>
// #define SAFETIMER_DEBUG
#ifdef SAFETIMER_DEBUG
#include <QDebug>
#endif
namespace QCA
{
class SafeTimer::Private : public QObject
{
- Q_OBJECT
- friend class SafeTimer;
+ Q_OBJECT
+ friend class SafeTimer;
public:
- Private(QObject *parent = 0);
+ Private(QObject *parent = 0);
- int timerId;
- int fixerTimerId;
- bool isSingleShot;
- int interval;
- bool isActive;
- QElapsedTimer elapsedTimer;
+ int timerId;
+ int fixerTimerId;
+ bool isSingleShot;
+ int interval;
+ bool isActive;
+ QElapsedTimer elapsedTimer;
public slots:
- void fixTimer();
+ void fixTimer();
signals:
- void needFix();
+ void needFix();
protected:
- bool event(QEvent *event);
- void timerEvent(QTimerEvent *event);
+ bool event(QEvent *event);
+ void timerEvent(QTimerEvent *event);
};
SafeTimer::Private::Private(QObject *parent)
- : QObject(parent)
- , timerId(0)
- , fixerTimerId(0)
- , isSingleShot(false)
- , interval(0)
- , isActive(false)
- , elapsedTimer(QElapsedTimer())
+ : QObject(parent)
+ , timerId(0)
+ , fixerTimerId(0)
+ , isSingleShot(false)
+ , interval(0)
+ , isActive(false)
+ , elapsedTimer(QElapsedTimer())
{
- connect(this, SIGNAL(needFix()), SLOT(fixTimer()), Qt::QueuedConnection);
+ connect(this, SIGNAL(needFix()), SLOT(fixTimer()), Qt::QueuedConnection);
}
void SafeTimer::Private::fixTimer()
{
- // Start special timer to align ressurected old timer
- int msec = qMax(0, interval - static_cast<int>(elapsedTimer.elapsed()));
+ // Start special timer to align ressurected old timer
+ int msec = qMax(0, interval - static_cast<int>(elapsedTimer.elapsed()));
- fixerTimerId = startTimer(msec);
+ fixerTimerId = startTimer(msec);
#ifdef SAFETIMER_DEBUG
- qDebug() << "START FIXTIMER: id =" << fixerTimerId << ", thread =" << thread() << ", interval =" << msec << parent();
+ qDebug() << "START FIXTIMER: id =" << fixerTimerId << ", thread =" << thread() << ", interval =" << msec << parent();
#endif
}
bool SafeTimer::Private::event(QEvent *event)
{
- if (event->type() == QEvent::ThreadChange && fixerTimerId /* timer is actived */)
- {
- // Timer dies when an object changes owner thread. This trick
- // used to ressurect old timer in the new thread.
- // Signal is emited in the old thread but will be gotten in the new one.
+ if (event->type() == QEvent::ThreadChange && fixerTimerId /* timer is actived */) {
+ // Timer dies when an object changes owner thread. This trick
+ // used to ressurect old timer in the new thread.
+ // Signal is emited in the old thread but will be gotten in the new one.
#ifdef SAFETIMER_DEBUG
- qDebug() << "STOP FIXTIMER ON CHANGE THREAD: id =" << fixerTimerId << ", thread =" << thread() << parent();
+ qDebug() << "STOP FIXTIMER ON CHANGE THREAD: id =" << fixerTimerId << ", thread =" << thread() << parent();
#endif
- killTimer(fixerTimerId);
- fixerTimerId = 0;
- emit needFix();
- }
+ killTimer(fixerTimerId);
+ fixerTimerId = 0;
+ emit needFix();
+ }
- return QObject::event(event);
+ return QObject::event(event);
}
void SafeTimer::Private::timerEvent(QTimerEvent *event)
{
- if (event->timerId() == fixerTimerId)
- {
+ if (event->timerId() == fixerTimerId) {
#ifdef SAFETIMER_DEBUG
- qDebug() << "STOP FIXTIMER ON TIMEOUT: id =" << fixerTimerId << ", thread =" << thread() << parent();
+ qDebug() << "STOP FIXTIMER ON TIMEOUT: id =" << fixerTimerId << ", thread =" << thread() << parent();
#endif
- killTimer(fixerTimerId);
- fixerTimerId = 0;
-
- SafeTimer *safeTimer = qobject_cast<SafeTimer*>(parent());
- // Emulate timeout signal of not yet ressurected timer
- emit safeTimer->timeout();
- // Ressurect timer here if not a singleshot
- if (!isSingleShot)
- safeTimer->start();
- else
- isActive = false;
- }
- else
- {
+ killTimer(fixerTimerId);
+ fixerTimerId = 0;
+
+ SafeTimer *safeTimer = qobject_cast<SafeTimer *>(parent());
+ // Emulate timeout signal of not yet ressurected timer
+ emit safeTimer->timeout();
+ // Ressurect timer here if not a singleshot
+ if (!isSingleShot) {
+ safeTimer->start();
+ } else {
+ isActive = false;
+ }
+ } else {
#ifdef SAFETIMER_DEBUG
- qDebug() << "BAD PRIVATE TIME EVENT: id =" << timerId << ", thread =" << thread() << this << ", badId =" << event->timerId() << parent();
+ qDebug() << "BAD PRIVATE TIME EVENT: id =" << timerId << ", thread =" << thread() << this << ", badId =" << event->timerId() << parent();
#endif
- }
+ }
}
SafeTimer::SafeTimer(QObject *parent)
- : QObject()
- , d(new Private())
+ : QObject()
+ , d(new Private())
{
- // It must be done here. Initialization list can't be used.
- // Need to have proper class name. Look at TimerFixer::hook.
- setParent(parent);
- d->setParent(this);
+ // It must be done here. Initialization list can't be used.
+ // Need to have proper class name. Look at TimerFixer::hook.
+ setParent(parent);
+ d->setParent(this);
}
SafeTimer::~SafeTimer()
{
}
int SafeTimer::interval() const
{
- return d->interval;
+ return d->interval;
}
bool SafeTimer::isActive() const
{
- return d->isActive;
+ return d->isActive;
}
bool SafeTimer::isSingleShot() const
{
- return d->isSingleShot;
+ return d->isSingleShot;
}
void SafeTimer::setInterval(int msec)
{
- d->interval = msec;
+ d->interval = msec;
}
void SafeTimer::setSingleShot(bool singleShot)
{
- d->isSingleShot = singleShot;
+ d->isSingleShot = singleShot;
}
void SafeTimer::start(int msec)
{
- d->interval = msec;
- start();
+ d->interval = msec;
+ start();
}
void SafeTimer::start()
{
- stop();
+ stop();
- d->elapsedTimer.start();
- d->timerId = QObject::startTimer(d->interval);
- d->isActive = d->timerId > 0;
+ d->elapsedTimer.start();
+ d->timerId = QObject::startTimer(d->interval);
+ d->isActive = d->timerId > 0;
#ifdef SAFETIMER_DEBUG
- qDebug() << "START TIMER: id =" << d->timerId << ", thread =" << thread() << ", interval =" << d->interval << this;
+ qDebug() << "START TIMER: id =" << d->timerId << ", thread =" << thread() << ", interval =" << d->interval << this;
#endif
}
void SafeTimer::stop()
{
- if (d->timerId)
- {
- QObject::killTimer(d->timerId);
+ if (d->timerId) {
+ QObject::killTimer(d->timerId);
#ifdef SAFETIMER_DEBUG
- qDebug() << "STOP TIMER: id =" << d->timerId << ", thread =" << thread() << this;
+ qDebug() << "STOP TIMER: id =" << d->timerId << ", thread =" << thread() << this;
#endif
- d->timerId = 0;
- }
+ d->timerId = 0;
+ }
- if (d->fixerTimerId)
- {
+ if (d->fixerTimerId) {
#ifdef SAFETIMER_DEBUG
- qDebug() << "STOP FIXER TIMER: id =" << d->fixerTimerId << ", thread =" << thread() << this;
+ qDebug() << "STOP FIXER TIMER: id =" << d->fixerTimerId << ", thread =" << thread() << this;
#endif
- d->killTimer(d->fixerTimerId);
- d->fixerTimerId = 0;
- }
- d->isActive = false;
+ d->killTimer(d->fixerTimerId);
+ d->fixerTimerId = 0;
+ }
+ d->isActive = false;
}
bool SafeTimer::event(QEvent *event)
{
- if (event->type() == QEvent::ThreadChange && d->timerId /* timer is actived */)
- {
- // Timer dies when an object changes owner thread. This trick
- // used to ressurect old timer in the new thread.
- // Signal is emited in the old thread but will be gotten in the new one.
+ if (event->type() == QEvent::ThreadChange && d->timerId /* timer is actived */) {
+ // Timer dies when an object changes owner thread. This trick
+ // used to ressurect old timer in the new thread.
+ // Signal is emited in the old thread but will be gotten in the new one.
#ifdef SAFETIMER_DEBUG
- qDebug() << "CHANGE THREAD: id =" << d->timerId << ", thread =" << thread() << this;
+ qDebug() << "CHANGE THREAD: id =" << d->timerId << ", thread =" << thread() << this;
#endif
- killTimer(d->timerId);
- d->timerId = 0;
- emit d->needFix();
- }
+ killTimer(d->timerId);
+ d->timerId = 0;
+ emit d->needFix();
+ }
- return QObject::event(event);
+ return QObject::event(event);
}
void SafeTimer::timerEvent(QTimerEvent *event)
{
- if (event->timerId() == d->timerId)
- {
- if (d->isSingleShot)
- stop();
- emit timeout();
- }
- else
- {
+ if (event->timerId() == d->timerId) {
+ if (d->isSingleShot) {
+ stop();
+ }
+ emit timeout();
+ } else {
#ifdef SAFETIMER_DEBUG
- qDebug() << "BAD TIME EVENT: id =" << d->timerId << ", thread =" << thread() << this << ", badId =" << event->timerId() << this;
+ qDebug() << "BAD TIME EVENT: id =" << d->timerId << ", thread =" << thread() << this << ", badId =" << event->timerId() << this;
#endif
- }
+ }
}
} // end namespace QCA
#include "qca_safetimer.moc"
diff --git a/src/qca_securelayer.cpp b/src/qca_securelayer.cpp
index 5408b5b8..dfade6c0 100644
--- a/src/qca_securelayer.cpp
+++ b/src/qca_securelayer.cpp
@@ -1,2019 +1,1951 @@
/*
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_securelayer.h"
#include "qcaprovider.h"
#include "qca_safeobj.h"
#include "qca_safetimer.h"
#include <QPointer>
#if QT_VERSION >= 0x050000
#include <QMetaMethod>
#endif
-namespace QCA {
+namespace QCA
+{
Provider::Context *getContext(const QString &type, const QString &provider);
-enum ResetMode
-{
- ResetSession = 0,
- ResetSessionAndData = 1,
- ResetAll = 2
+enum ResetMode {
+ ResetSession = 0,
+ ResetSessionAndData = 1,
+ ResetAll = 2
};
//----------------------------------------------------------------------------
// LayerTracker
//----------------------------------------------------------------------------
class LayerTracker
{
private:
- struct Item
- {
- int plain;
- qint64 encoded;
- };
+ struct Item {
+ int plain;
+ qint64 encoded;
+ };
- int p;
- QList<Item> list;
+ int p;
+ QList<Item> list;
public:
- LayerTracker()
- {
- p = 0;
- }
-
- void reset()
- {
- p = 0;
- list.clear();
- }
-
- void addPlain(int plain)
- {
- p += plain;
- }
-
- void specifyEncoded(int encoded, int plain)
- {
- // can't specify more bytes than we have
- if(plain > p)
- plain = p;
- p -= plain;
- Item i;
- i.plain = plain;
- i.encoded = encoded;
- list += i;
- }
-
- int finished(qint64 encoded)
- {
- int plain = 0;
- for(QList<Item>::Iterator it = list.begin(); it != list.end();)
- {
- Item &i = *it;
-
- // not enough?
- if(encoded < i.encoded)
- {
- i.encoded -= encoded;
- break;
- }
-
- encoded -= i.encoded;
- plain += i.plain;
- it = list.erase(it);
- }
- return plain;
- }
+ LayerTracker()
+ {
+ p = 0;
+ }
+
+ void reset()
+ {
+ p = 0;
+ list.clear();
+ }
+
+ void addPlain(int plain)
+ {
+ p += plain;
+ }
+
+ void specifyEncoded(int encoded, int plain)
+ {
+ // can't specify more bytes than we have
+ if (plain > p) {
+ plain = p;
+ }
+ p -= plain;
+ Item i;
+ i.plain = plain;
+ i.encoded = encoded;
+ list += i;
+ }
+
+ int finished(qint64 encoded)
+ {
+ int plain = 0;
+ for (QList<Item>::Iterator it = list.begin(); it != list.end();) {
+ Item &i = *it;
+
+ // not enough?
+ if (encoded < i.encoded) {
+ i.encoded -= encoded;
+ break;
+ }
+
+ encoded -= i.encoded;
+ plain += i.plain;
+ it = list.erase(it);
+ }
+ return plain;
+ }
};
//----------------------------------------------------------------------------
// SecureLayer
//----------------------------------------------------------------------------
SecureLayer::SecureLayer(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
}
bool SecureLayer::isClosable() const
{
- return false;
+ return false;
}
void SecureLayer::close()
{
}
QByteArray SecureLayer::readUnprocessed()
{
- return QByteArray();
+ return QByteArray();
}
//----------------------------------------------------------------------------
// TLSSession
//----------------------------------------------------------------------------
TLSSession::TLSSession()
{
}
TLSSession::TLSSession(const TLSSession &from)
-:Algorithm(from)
+ : Algorithm(from)
{
}
TLSSession::~TLSSession()
{
}
-TLSSession & TLSSession::operator=(const TLSSession &from)
+TLSSession &TLSSession::operator=(const TLSSession &from)
{
- Algorithm::operator=(from);
- return *this;
+ Algorithm::operator=(from);
+ return *this;
}
bool TLSSession::isNull() const
{
- return (!context() ? true : false);
+ return (!context() ? true : false);
}
//----------------------------------------------------------------------------
// TLS
//----------------------------------------------------------------------------
class TLS::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum
- {
- OpStart,
- OpUpdate
- };
-
- enum State
- {
- Inactive,
- Initializing,
- Handshaking,
- Connected,
- Closing
- };
-
- class Action
- {
- public:
- enum Type
- {
- ReadyRead,
- ReadyReadOutgoing,
- Handshaken,
- Close,
- CheckPeerCertificate,
- CertificateRequested,
- HostNameReceived
- };
-
- int type;
-
- Action(int _type) : type(_type)
- {
- }
- };
-
- TLS *q;
- TLSContext *c;
- TLS::Mode mode;
-
- // signal connected flags
- bool connect_hostNameReceived;
- bool connect_certificateRequested;
- bool connect_peerCertificateAvailable;
- bool connect_handshaken;
-
- // persistent settings (survives ResetSessionAndData)
- CertificateChain localCert;
- PrivateKey localKey;
- CertificateCollection trusted;
- bool con_ssfMode;
- int con_minSSF, con_maxSSF;
- QStringList con_cipherSuites;
- bool tryCompress;
- int packet_mtu;
- QList<CertificateInfoOrdered> issuerList;
- TLSSession session;
-
- // session
- State state;
- bool blocked;
- bool server;
- QString host;
- TLSContext::SessionInfo sessionInfo;
- SafeTimer actionTrigger;
- int op;
- QList<Action> actionQueue;
- bool need_update;
- bool maybe_input;
- bool emitted_hostNameReceived;
- bool emitted_certificateRequested;
- bool emitted_peerCertificateAvailable;
-
- // data (survives ResetSession)
- CertificateChain peerCert;
- Validity peerValidity;
- bool hostMismatch;
- Error errorCode;
-
- // stream i/o
- QByteArray in, out;
- QByteArray to_net, from_net;
- QByteArray unprocessed;
- int out_pending;
- int to_net_encoded;
- LayerTracker layer;
-
- // datagram i/o
- QList<QByteArray> packet_in, packet_out;
- QList<QByteArray> packet_to_net, packet_from_net;
- int packet_out_pending; // packet count
- QList<int> packet_to_net_encoded;
-
- Private(TLS *_q, TLS::Mode _mode) : QObject(_q), q(_q), mode(_mode), actionTrigger(this)
- {
- // c is 0 during initial reset, so we don't redundantly reset it
- c = 0;
- connect_hostNameReceived = false;
- connect_certificateRequested = false;
- connect_peerCertificateAvailable = false;
- connect_handshaken = false;
- server = false;
-
- connect(&actionTrigger, SIGNAL(timeout()), SLOT(doNextAction()));
- actionTrigger.setSingleShot(true);
-
- reset(ResetAll);
-
- c = static_cast<TLSContext *>(q->context());
-
- // parent the context to us, so that moveToThread works
- c->setParent(this);
-
- connect(c, SIGNAL(resultsReady()), SLOT(tls_resultsReady()));
- connect(c, SIGNAL(dtlsTimeout()), SLOT(tls_dtlsTimeout()));
- }
-
- ~Private()
- {
- // context is owned by Algorithm, unparent so we don't double-delete
- c->setParent(0);
- }
-
- void reset(ResetMode mode)
- {
- if(c)
- c->reset();
-
- // if we reset while in client mode, then clear this list
- // (it should only persist when used for server mode)
- if(!server)
- issuerList.clear();
-
- state = Inactive;
- blocked = false;
- server = false;
- host = QString();
- sessionInfo = TLSContext::SessionInfo();
- actionTrigger.stop();
- op = -1;
- actionQueue.clear();
- need_update = false;
- maybe_input = false;
- emitted_hostNameReceived = false;
- emitted_certificateRequested = false;
- emitted_peerCertificateAvailable = false;
-
- out.clear();
- out_pending = 0;
- packet_out.clear();
- packet_out_pending = 0;
-
- if(mode >= ResetSessionAndData)
- {
- peerCert = CertificateChain();
- peerValidity = ErrorValidityUnknown;
- hostMismatch = false;
- errorCode = (TLS::Error)-1;
-
- in.clear();
- to_net.clear();
- from_net.clear();
- unprocessed.clear();
- to_net_encoded = 0;
- layer.reset();
-
- packet_in.clear();
- packet_to_net.clear();
- packet_from_net.clear();
- packet_to_net_encoded.clear();
- }
-
- if(mode >= ResetAll)
- {
- localCert = CertificateChain();
- localKey = PrivateKey();
- trusted = CertificateCollection();
- con_ssfMode = true;
- con_minSSF = 128;
- con_maxSSF = -1;
- con_cipherSuites = QStringList();
- tryCompress = false;
- packet_mtu = -1;
- issuerList.clear();
- session = TLSSession();
- }
- }
-
- void start(bool serverMode)
- {
- state = Initializing;
- server = serverMode;
-
- c->setup(serverMode, host, tryCompress);
-
- if(con_ssfMode)
- c->setConstraints(con_minSSF, con_maxSSF);
- else
- c->setConstraints(con_cipherSuites);
-
- c->setCertificate(localCert, localKey);
- c->setTrustedCertificates(trusted);
- if(serverMode)
- c->setIssuerList(issuerList);
- if(!session.isNull())
- {
- TLSSessionContext *sc = static_cast<TLSSessionContext*>(session.context());
- c->setSessionId(*sc);
- }
- c->setMTU(packet_mtu);
-
- QCA_logTextMessage(QString("tls[%1]: c->start()").arg(q->objectName()), Logger::Information);
- op = OpStart;
- c->start();
- }
-
- void close()
- {
- QCA_logTextMessage(QString("tls[%1]: close").arg(q->objectName()), Logger::Information);
-
- if(state != Connected)
- return;
-
- state = Closing;
- c->shutdown();
- }
-
- void continueAfterStep()
- {
- QCA_logTextMessage(QString("tls[%1]: continueAfterStep").arg(q->objectName()), Logger::Information);
-
- if(!blocked)
- return;
-
- blocked = false;
- update();
- }
-
- void processNextAction()
- {
- if(actionQueue.isEmpty())
- {
- if(need_update)
- {
- QCA_logTextMessage(QString("tls[%1]: need_update").arg(q->objectName()), Logger::Information);
- update();
- }
- return;
- }
-
- Action a = actionQueue.takeFirst();
-
- // set up for the next one, if necessary
- if(!actionQueue.isEmpty() || need_update)
- {
- if(!actionTrigger.isActive())
- actionTrigger.start();
- }
-
- if(a.type == Action::ReadyRead)
- {
- emit q->readyRead();
- }
- else if(a.type == Action::ReadyReadOutgoing)
- {
- emit q->readyReadOutgoing();
- }
- else if(a.type == Action::Handshaken)
- {
- state = Connected;
-
- // write any app data waiting during handshake
- if(!out.isEmpty())
- {
- need_update = true;
- if(!actionTrigger.isActive())
- actionTrigger.start();
- }
-
- QCA_logTextMessage(QString("tls[%1]: handshaken").arg(q->objectName()), Logger::Information);
-
- if(connect_handshaken)
- {
- blocked = true;
- emit q->handshaken();
- }
- }
- else if(a.type == Action::Close)
- {
- unprocessed = c->unprocessed();
- reset(ResetSession);
- emit q->closed();
- }
- else if(a.type == Action::CheckPeerCertificate)
- {
- peerCert = c->peerCertificateChain();
- if(!peerCert.isEmpty())
- {
- peerValidity = c->peerCertificateValidity();
- if(peerValidity == ValidityGood && !host.isEmpty() && !peerCert.primary().matchesHostName(host))
- hostMismatch = true;
- }
-
- if(connect_peerCertificateAvailable)
- {
- blocked = true;
- emitted_peerCertificateAvailable = true;
- emit q->peerCertificateAvailable();
- }
- }
- else if(a.type == Action::CertificateRequested)
- {
- issuerList = c->issuerList();
- if(connect_certificateRequested)
- {
- blocked = true;
- emitted_certificateRequested = true;
- emit q->certificateRequested();
- }
- }
- else if(a.type == Action::HostNameReceived)
- {
- if(connect_hostNameReceived)
- {
- blocked = true;
- emitted_hostNameReceived = true;
- emit q->hostNameReceived();
- }
- }
- }
-
- void update()
- {
- QCA_logTextMessage(QString("tls[%1]: update").arg(q->objectName()), Logger::Information);
-
- if(blocked)
- {
- QCA_logTextMessage(QString("tls[%1]: ignoring update while blocked").arg(q->objectName()), Logger::Information);
- return;
- }
-
- if(!actionQueue.isEmpty())
- {
- QCA_logTextMessage(QString("tls[%1]: ignoring update while processing actions").arg(q->objectName()), Logger::Information);
- need_update = true;
- return;
- }
-
- // only allow one operation at a time
- if(op != -1)
- {
- QCA_logTextMessage(QString("tls[%1]: ignoring update while operation active").arg(q->objectName()), Logger::Information);
- need_update = true;
- return;
- }
-
- need_update = false;
-
- QByteArray arg_from_net, arg_from_app;
-
- if(state == Handshaking)
- {
- // during handshake, only send from_net (no app data)
-
- if(mode == TLS::Stream)
- {
- arg_from_net = from_net;
- from_net.clear();
- }
- else
- {
- // note: there may not be a packet
- if(!packet_from_net.isEmpty())
- arg_from_net = packet_from_net.takeFirst();
- }
- }
- else
- {
- if(mode == TLS::Stream)
- {
- if(!from_net.isEmpty())
- {
- arg_from_net = from_net;
- from_net.clear();
- }
-
- if(!out.isEmpty())
- {
- out_pending += out.size();
- arg_from_app = out;
- out.clear();
- }
- }
- else
- {
- if(!packet_from_net.isEmpty())
- arg_from_net = packet_from_net.takeFirst();
-
- if(!packet_out.isEmpty())
- {
- arg_from_app = packet_out.takeFirst();
- ++packet_out_pending;
- }
- }
- }
-
- if(arg_from_net.isEmpty() && arg_from_app.isEmpty() && !maybe_input)
- {
- QCA_logTextMessage(QString("tls[%1]: ignoring update: no output and no expected input").arg(q->objectName()), Logger::Information);
- return;
- }
-
- // clear this flag
- maybe_input = false;
-
- QCA_logTextMessage(QString("tls[%1]: c->update").arg(q->objectName()), Logger::Information);
- op = OpUpdate;
- c->update(arg_from_net, arg_from_app);
- }
-
- void start_finished()
- {
- bool ok = c->result() == TLSContext::Success;
- if(!ok)
- {
- reset(ResetSession);
- errorCode = TLS::ErrorInit;
- emit q->error();
- return;
- }
-
- state = Handshaking;
-
- // immediately update so we can get the first packet to send
- maybe_input = true;
- update();
- }
-
- void update_finished()
- {
- TLSContext::Result r = c->result();
- if(r == TLSContext::Error)
- {
- if(state == Handshaking || state == Closing)
- {
- reset(ResetSession);
- errorCode = ErrorHandshake;
- }
- else
- {
- reset(ResetSession);
- errorCode = ErrorCrypt;
- }
-
- emit q->error();
- return;
- }
-
- QByteArray c_to_net = c->to_net();
- if(!c_to_net.isEmpty())
- {
- QCA_logTextMessage(QString("tls[%1]: to_net %2").arg(q->objectName(), QString::number(c_to_net.size())), Logger::Information);
- }
-
- if(state == Closing)
- {
- if(mode == TLS::Stream)
- to_net += c_to_net;
- else
- packet_to_net += c_to_net;
-
- if(!c_to_net.isEmpty())
- actionQueue += Action(Action::ReadyReadOutgoing);
-
- if(r == TLSContext::Success)
- actionQueue += Action(Action::Close);
-
- processNextAction();
- return;
- }
- else if(state == Handshaking)
- {
- if(mode == TLS::Stream)
- to_net += c_to_net;
- else
- packet_to_net += c_to_net;
-
- if(!c_to_net.isEmpty())
- actionQueue += Action(Action::ReadyReadOutgoing);
-
- bool clientHello = false;
- bool serverHello = false;
- if(server)
- clientHello = c->clientHelloReceived();
- else
- serverHello = c->serverHelloReceived();
-
- // client specifies a host?
- if(!emitted_hostNameReceived && clientHello)
- {
- host = c->hostName();
- if(!host.isEmpty())
- actionQueue += Action(Action::HostNameReceived);
- }
-
- // successful handshake or server hello means there might be a peer cert
- if(!emitted_peerCertificateAvailable && (r == TLSContext::Success || (!server && serverHello)))
- actionQueue += Action(Action::CheckPeerCertificate);
-
- // server requests a cert from us?
- if(!emitted_certificateRequested && (serverHello && c->certificateRequested()))
- actionQueue += Action(Action::CertificateRequested);
-
- if(r == TLSContext::Success)
- {
- sessionInfo = c->sessionInfo();
- if(sessionInfo.id)
- {
- TLSSessionContext *sc = static_cast<TLSSessionContext*>(sessionInfo.id->clone());
- session.change(sc);
- }
-
- actionQueue += Action(Action::Handshaken);
- }
-
- processNextAction();
- return;
- }
- else // Connected
- {
- QByteArray c_to_app = c->to_app();
- if(!c_to_app.isEmpty())
- {
- QCA_logTextMessage(QString("tls[%1]: to_app %2").arg(q->objectName(), QString::number(c_to_app.size())), Logger::Information);
- }
-
- bool eof = c->eof();
- int enc = -1;
- if(!c_to_net.isEmpty())
- enc = c->encoded();
-
- bool io_pending = false;
- if(mode == TLS::Stream)
- {
- if(!c_to_net.isEmpty())
- out_pending -= enc;
-
- if(out_pending > 0)
- {
- maybe_input = true;
- io_pending = true;
- }
-
- if(!out.isEmpty())
- io_pending = true;
- }
- else
- {
- if(!c_to_net.isEmpty())
- --packet_out_pending;
-
- if(packet_out_pending > 0)
- {
- maybe_input = true;
- io_pending = true;
- }
-
- if(!packet_out.isEmpty())
- io_pending = true;
- }
-
- if(mode == TLS::Stream)
- {
- to_net += c_to_net;
- in += c_to_app;
- to_net_encoded += enc;
- }
- else
- {
- packet_to_net += c_to_net;
- packet_in += c_to_app;
- }
-
- if(!c_to_net.isEmpty())
- actionQueue += Action(Action::ReadyReadOutgoing);
-
- if(!c_to_app.isEmpty())
- actionQueue += Action(Action::ReadyRead);
-
- if(eof)
- {
- close();
- maybe_input = true;
- }
-
- if(eof || io_pending)
- {
- QCA_logTextMessage(QString("tls[%1]: eof || io_pending").arg(q->objectName()), Logger::Information);
- update();
- }
-
- processNextAction();
- return;
- }
- }
+ enum {
+ OpStart,
+ OpUpdate
+ };
+
+ enum State {
+ Inactive,
+ Initializing,
+ Handshaking,
+ Connected,
+ Closing
+ };
+
+ class Action
+ {
+ public:
+ enum Type {
+ ReadyRead,
+ ReadyReadOutgoing,
+ Handshaken,
+ Close,
+ CheckPeerCertificate,
+ CertificateRequested,
+ HostNameReceived
+ };
+
+ int type;
+
+ Action(int _type) : type(_type)
+ {
+ }
+ };
+
+ TLS *q;
+ TLSContext *c;
+ TLS::Mode mode;
+
+ // signal connected flags
+ bool connect_hostNameReceived;
+ bool connect_certificateRequested;
+ bool connect_peerCertificateAvailable;
+ bool connect_handshaken;
+
+ // persistent settings (survives ResetSessionAndData)
+ CertificateChain localCert;
+ PrivateKey localKey;
+ CertificateCollection trusted;
+ bool con_ssfMode;
+ int con_minSSF, con_maxSSF;
+ QStringList con_cipherSuites;
+ bool tryCompress;
+ int packet_mtu;
+ QList<CertificateInfoOrdered> issuerList;
+ TLSSession session;
+
+ // session
+ State state;
+ bool blocked;
+ bool server;
+ QString host;
+ TLSContext::SessionInfo sessionInfo;
+ SafeTimer actionTrigger;
+ int op;
+ QList<Action> actionQueue;
+ bool need_update;
+ bool maybe_input;
+ bool emitted_hostNameReceived;
+ bool emitted_certificateRequested;
+ bool emitted_peerCertificateAvailable;
+
+ // data (survives ResetSession)
+ CertificateChain peerCert;
+ Validity peerValidity;
+ bool hostMismatch;
+ Error errorCode;
+
+ // stream i/o
+ QByteArray in, out;
+ QByteArray to_net, from_net;
+ QByteArray unprocessed;
+ int out_pending;
+ int to_net_encoded;
+ LayerTracker layer;
+
+ // datagram i/o
+ QList<QByteArray> packet_in, packet_out;
+ QList<QByteArray> packet_to_net, packet_from_net;
+ int packet_out_pending; // packet count
+ QList<int> packet_to_net_encoded;
+
+ Private(TLS *_q, TLS::Mode _mode) : QObject(_q), q(_q), mode(_mode), actionTrigger(this)
+ {
+ // c is 0 during initial reset, so we don't redundantly reset it
+ c = 0;
+ connect_hostNameReceived = false;
+ connect_certificateRequested = false;
+ connect_peerCertificateAvailable = false;
+ connect_handshaken = false;
+ server = false;
+
+ connect(&actionTrigger, SIGNAL(timeout()), SLOT(doNextAction()));
+ actionTrigger.setSingleShot(true);
+
+ reset(ResetAll);
+
+ c = static_cast<TLSContext *>(q->context());
+
+ // parent the context to us, so that moveToThread works
+ c->setParent(this);
+
+ connect(c, SIGNAL(resultsReady()), SLOT(tls_resultsReady()));
+ connect(c, SIGNAL(dtlsTimeout()), SLOT(tls_dtlsTimeout()));
+ }
+
+ ~Private()
+ {
+ // context is owned by Algorithm, unparent so we don't double-delete
+ c->setParent(0);
+ }
+
+ void reset(ResetMode mode)
+ {
+ if (c) {
+ c->reset();
+ }
+
+ // if we reset while in client mode, then clear this list
+ // (it should only persist when used for server mode)
+ if (!server) {
+ issuerList.clear();
+ }
+
+ state = Inactive;
+ blocked = false;
+ server = false;
+ host = QString();
+ sessionInfo = TLSContext::SessionInfo();
+ actionTrigger.stop();
+ op = -1;
+ actionQueue.clear();
+ need_update = false;
+ maybe_input = false;
+ emitted_hostNameReceived = false;
+ emitted_certificateRequested = false;
+ emitted_peerCertificateAvailable = false;
+
+ out.clear();
+ out_pending = 0;
+ packet_out.clear();
+ packet_out_pending = 0;
+
+ if (mode >= ResetSessionAndData) {
+ peerCert = CertificateChain();
+ peerValidity = ErrorValidityUnknown;
+ hostMismatch = false;
+ errorCode = (TLS::Error) - 1;
+
+ in.clear();
+ to_net.clear();
+ from_net.clear();
+ unprocessed.clear();
+ to_net_encoded = 0;
+ layer.reset();
+
+ packet_in.clear();
+ packet_to_net.clear();
+ packet_from_net.clear();
+ packet_to_net_encoded.clear();
+ }
+
+ if (mode >= ResetAll) {
+ localCert = CertificateChain();
+ localKey = PrivateKey();
+ trusted = CertificateCollection();
+ con_ssfMode = true;
+ con_minSSF = 128;
+ con_maxSSF = -1;
+ con_cipherSuites = QStringList();
+ tryCompress = false;
+ packet_mtu = -1;
+ issuerList.clear();
+ session = TLSSession();
+ }
+ }
+
+ void start(bool serverMode)
+ {
+ state = Initializing;
+ server = serverMode;
+
+ c->setup(serverMode, host, tryCompress);
+
+ if (con_ssfMode) {
+ c->setConstraints(con_minSSF, con_maxSSF);
+ } else {
+ c->setConstraints(con_cipherSuites);
+ }
+
+ c->setCertificate(localCert, localKey);
+ c->setTrustedCertificates(trusted);
+ if (serverMode) {
+ c->setIssuerList(issuerList);
+ }
+ if (!session.isNull()) {
+ TLSSessionContext *sc = static_cast<TLSSessionContext *>(session.context());
+ c->setSessionId(*sc);
+ }
+ c->setMTU(packet_mtu);
+
+ QCA_logTextMessage(QString("tls[%1]: c->start()").arg(q->objectName()), Logger::Information);
+ op = OpStart;
+ c->start();
+ }
+
+ void close()
+ {
+ QCA_logTextMessage(QString("tls[%1]: close").arg(q->objectName()), Logger::Information);
+
+ if (state != Connected) {
+ return;
+ }
+
+ state = Closing;
+ c->shutdown();
+ }
+
+ void continueAfterStep()
+ {
+ QCA_logTextMessage(QString("tls[%1]: continueAfterStep").arg(q->objectName()), Logger::Information);
+
+ if (!blocked) {
+ return;
+ }
+
+ blocked = false;
+ update();
+ }
+
+ void processNextAction()
+ {
+ if (actionQueue.isEmpty()) {
+ if (need_update) {
+ QCA_logTextMessage(QString("tls[%1]: need_update").arg(q->objectName()), Logger::Information);
+ update();
+ }
+ return;
+ }
+
+ Action a = actionQueue.takeFirst();
+
+ // set up for the next one, if necessary
+ if (!actionQueue.isEmpty() || need_update) {
+ if (!actionTrigger.isActive()) {
+ actionTrigger.start();
+ }
+ }
+
+ if (a.type == Action::ReadyRead) {
+ emit q->readyRead();
+ } else if (a.type == Action::ReadyReadOutgoing) {
+ emit q->readyReadOutgoing();
+ } else if (a.type == Action::Handshaken) {
+ state = Connected;
+
+ // write any app data waiting during handshake
+ if (!out.isEmpty()) {
+ need_update = true;
+ if (!actionTrigger.isActive()) {
+ actionTrigger.start();
+ }
+ }
+
+ QCA_logTextMessage(QString("tls[%1]: handshaken").arg(q->objectName()), Logger::Information);
+
+ if (connect_handshaken) {
+ blocked = true;
+ emit q->handshaken();
+ }
+ } else if (a.type == Action::Close) {
+ unprocessed = c->unprocessed();
+ reset(ResetSession);
+ emit q->closed();
+ } else if (a.type == Action::CheckPeerCertificate) {
+ peerCert = c->peerCertificateChain();
+ if (!peerCert.isEmpty()) {
+ peerValidity = c->peerCertificateValidity();
+ if (peerValidity == ValidityGood && !host.isEmpty() && !peerCert.primary().matchesHostName(host)) {
+ hostMismatch = true;
+ }
+ }
+
+ if (connect_peerCertificateAvailable) {
+ blocked = true;
+ emitted_peerCertificateAvailable = true;
+ emit q->peerCertificateAvailable();
+ }
+ } else if (a.type == Action::CertificateRequested) {
+ issuerList = c->issuerList();
+ if (connect_certificateRequested) {
+ blocked = true;
+ emitted_certificateRequested = true;
+ emit q->certificateRequested();
+ }
+ } else if (a.type == Action::HostNameReceived) {
+ if (connect_hostNameReceived) {
+ blocked = true;
+ emitted_hostNameReceived = true;
+ emit q->hostNameReceived();
+ }
+ }
+ }
+
+ void update()
+ {
+ QCA_logTextMessage(QString("tls[%1]: update").arg(q->objectName()), Logger::Information);
+
+ if (blocked) {
+ QCA_logTextMessage(QString("tls[%1]: ignoring update while blocked").arg(q->objectName()), Logger::Information);
+ return;
+ }
+
+ if (!actionQueue.isEmpty()) {
+ QCA_logTextMessage(QString("tls[%1]: ignoring update while processing actions").arg(q->objectName()), Logger::Information);
+ need_update = true;
+ return;
+ }
+
+ // only allow one operation at a time
+ if (op != -1) {
+ QCA_logTextMessage(QString("tls[%1]: ignoring update while operation active").arg(q->objectName()), Logger::Information);
+ need_update = true;
+ return;
+ }
+
+ need_update = false;
+
+ QByteArray arg_from_net, arg_from_app;
+
+ if (state == Handshaking) {
+ // during handshake, only send from_net (no app data)
+
+ if (mode == TLS::Stream) {
+ arg_from_net = from_net;
+ from_net.clear();
+ } else {
+ // note: there may not be a packet
+ if (!packet_from_net.isEmpty()) {
+ arg_from_net = packet_from_net.takeFirst();
+ }
+ }
+ } else {
+ if (mode == TLS::Stream) {
+ if (!from_net.isEmpty()) {
+ arg_from_net = from_net;
+ from_net.clear();
+ }
+
+ if (!out.isEmpty()) {
+ out_pending += out.size();
+ arg_from_app = out;
+ out.clear();
+ }
+ } else {
+ if (!packet_from_net.isEmpty()) {
+ arg_from_net = packet_from_net.takeFirst();
+ }
+
+ if (!packet_out.isEmpty()) {
+ arg_from_app = packet_out.takeFirst();
+ ++packet_out_pending;
+ }
+ }
+ }
+
+ if (arg_from_net.isEmpty() && arg_from_app.isEmpty() && !maybe_input) {
+ QCA_logTextMessage(QString("tls[%1]: ignoring update: no output and no expected input").arg(q->objectName()), Logger::Information);
+ return;
+ }
+
+ // clear this flag
+ maybe_input = false;
+
+ QCA_logTextMessage(QString("tls[%1]: c->update").arg(q->objectName()), Logger::Information);
+ op = OpUpdate;
+ c->update(arg_from_net, arg_from_app);
+ }
+
+ void start_finished()
+ {
+ bool ok = c->result() == TLSContext::Success;
+ if (!ok) {
+ reset(ResetSession);
+ errorCode = TLS::ErrorInit;
+ emit q->error();
+ return;
+ }
+
+ state = Handshaking;
+
+ // immediately update so we can get the first packet to send
+ maybe_input = true;
+ update();
+ }
+
+ void update_finished()
+ {
+ TLSContext::Result r = c->result();
+ if (r == TLSContext::Error) {
+ if (state == Handshaking || state == Closing) {
+ reset(ResetSession);
+ errorCode = ErrorHandshake;
+ } else {
+ reset(ResetSession);
+ errorCode = ErrorCrypt;
+ }
+
+ emit q->error();
+ return;
+ }
+
+ QByteArray c_to_net = c->to_net();
+ if (!c_to_net.isEmpty()) {
+ QCA_logTextMessage(QString("tls[%1]: to_net %2").arg(q->objectName(), QString::number(c_to_net.size())), Logger::Information);
+ }
+
+ if (state == Closing) {
+ if (mode == TLS::Stream) {
+ to_net += c_to_net;
+ } else {
+ packet_to_net += c_to_net;
+ }
+
+ if (!c_to_net.isEmpty()) {
+ actionQueue += Action(Action::ReadyReadOutgoing);
+ }
+
+ if (r == TLSContext::Success) {
+ actionQueue += Action(Action::Close);
+ }
+
+ processNextAction();
+ return;
+ } else if (state == Handshaking) {
+ if (mode == TLS::Stream) {
+ to_net += c_to_net;
+ } else {
+ packet_to_net += c_to_net;
+ }
+
+ if (!c_to_net.isEmpty()) {
+ actionQueue += Action(Action::ReadyReadOutgoing);
+ }
+
+ bool clientHello = false;
+ bool serverHello = false;
+ if (server) {
+ clientHello = c->clientHelloReceived();
+ } else {
+ serverHello = c->serverHelloReceived();
+ }
+
+ // client specifies a host?
+ if (!emitted_hostNameReceived && clientHello) {
+ host = c->hostName();
+ if (!host.isEmpty()) {
+ actionQueue += Action(Action::HostNameReceived);
+ }
+ }
+
+ // successful handshake or server hello means there might be a peer cert
+ if (!emitted_peerCertificateAvailable && (r == TLSContext::Success || (!server && serverHello))) {
+ actionQueue += Action(Action::CheckPeerCertificate);
+ }
+
+ // server requests a cert from us?
+ if (!emitted_certificateRequested && (serverHello && c->certificateRequested())) {
+ actionQueue += Action(Action::CertificateRequested);
+ }
+
+ if (r == TLSContext::Success) {
+ sessionInfo = c->sessionInfo();
+ if (sessionInfo.id) {
+ TLSSessionContext *sc = static_cast<TLSSessionContext *>(sessionInfo.id->clone());
+ session.change(sc);
+ }
+
+ actionQueue += Action(Action::Handshaken);
+ }
+
+ processNextAction();
+ return;
+ } else { // Connected
+ QByteArray c_to_app = c->to_app();
+ if (!c_to_app.isEmpty()) {
+ QCA_logTextMessage(QString("tls[%1]: to_app %2").arg(q->objectName(), QString::number(c_to_app.size())), Logger::Information);
+ }
+
+ bool eof = c->eof();
+ int enc = -1;
+ if (!c_to_net.isEmpty()) {
+ enc = c->encoded();
+ }
+
+ bool io_pending = false;
+ if (mode == TLS::Stream) {
+ if (!c_to_net.isEmpty()) {
+ out_pending -= enc;
+ }
+
+ if (out_pending > 0) {
+ maybe_input = true;
+ io_pending = true;
+ }
+
+ if (!out.isEmpty()) {
+ io_pending = true;
+ }
+ } else {
+ if (!c_to_net.isEmpty()) {
+ --packet_out_pending;
+ }
+
+ if (packet_out_pending > 0) {
+ maybe_input = true;
+ io_pending = true;
+ }
+
+ if (!packet_out.isEmpty()) {
+ io_pending = true;
+ }
+ }
+
+ if (mode == TLS::Stream) {
+ to_net += c_to_net;
+ in += c_to_app;
+ to_net_encoded += enc;
+ } else {
+ packet_to_net += c_to_net;
+ packet_in += c_to_app;
+ }
+
+ if (!c_to_net.isEmpty()) {
+ actionQueue += Action(Action::ReadyReadOutgoing);
+ }
+
+ if (!c_to_app.isEmpty()) {
+ actionQueue += Action(Action::ReadyRead);
+ }
+
+ if (eof) {
+ close();
+ maybe_input = true;
+ }
+
+ if (eof || io_pending) {
+ QCA_logTextMessage(QString("tls[%1]: eof || io_pending").arg(q->objectName()), Logger::Information);
+ update();
+ }
+
+ processNextAction();
+ return;
+ }
+ }
private slots:
- void tls_resultsReady()
- {
- QCA_logTextMessage(QString("tls[%1]: c->resultsReady()").arg(q->objectName()), Logger::Information);
-
- Q_ASSERT(op != -1);
-
- int last_op = op;
- op = -1;
-
- if(last_op == OpStart)
- start_finished();
- else // OpUpdate
- update_finished();
- }
-
- void tls_dtlsTimeout()
- {
- QCA_logTextMessage(QString("tls[%1]: c->dtlsTimeout()").arg(q->objectName()), Logger::Information);
-
- maybe_input = true;
- update();
- }
-
- void doNextAction()
- {
- processNextAction();
- }
+ void tls_resultsReady()
+ {
+ QCA_logTextMessage(QString("tls[%1]: c->resultsReady()").arg(q->objectName()), Logger::Information);
+
+ Q_ASSERT(op != -1);
+
+ int last_op = op;
+ op = -1;
+
+ if (last_op == OpStart) {
+ start_finished();
+ } else { // OpUpdate
+ update_finished();
+ }
+ }
+
+ void tls_dtlsTimeout()
+ {
+ QCA_logTextMessage(QString("tls[%1]: c->dtlsTimeout()").arg(q->objectName()), Logger::Information);
+
+ maybe_input = true;
+ update();
+ }
+
+ void doNextAction()
+ {
+ processNextAction();
+ }
};
TLS::TLS(QObject *parent, const QString &provider)
-:SecureLayer(parent), Algorithm("tls", provider)
+ : SecureLayer(parent), Algorithm("tls", provider)
{
- d = new Private(this, TLS::Stream);
+ d = new Private(this, TLS::Stream);
}
TLS::TLS(Mode mode, QObject *parent, const QString &provider)
-:SecureLayer(parent), Algorithm(mode == Stream ? "tls" : "dtls", provider)
+ : SecureLayer(parent), Algorithm(mode == Stream ? "tls" : "dtls", provider)
{
- d = new Private(this, mode);
+ d = new Private(this, mode);
}
TLS::~TLS()
{
- delete d;
+ delete d;
}
void TLS::reset()
{
- d->reset(ResetAll);
+ d->reset(ResetAll);
}
QStringList TLS::supportedCipherSuites(const Version &version) const
{
- return d->c->supportedCipherSuites(version);
+ return d->c->supportedCipherSuites(version);
}
void TLS::setCertificate(const CertificateChain &cert, const PrivateKey &key)
{
- d->localCert = cert;
- d->localKey = key;
- if(d->state != TLS::Private::Inactive)
- d->c->setCertificate(cert, key);
+ d->localCert = cert;
+ d->localKey = key;
+ if (d->state != TLS::Private::Inactive) {
+ d->c->setCertificate(cert, key);
+ }
}
void TLS::setCertificate(const KeyBundle &kb)
{
- setCertificate(kb.certificateChain(), kb.privateKey());
+ setCertificate(kb.certificateChain(), kb.privateKey());
}
CertificateCollection TLS::trustedCertificates() const
{
- return d->trusted;
+ return d->trusted;
}
void TLS::setTrustedCertificates(const CertificateCollection &trusted)
{
- d->trusted = trusted;
- if(d->state != TLS::Private::Inactive)
- d->c->setTrustedCertificates(trusted);
+ d->trusted = trusted;
+ if (d->state != TLS::Private::Inactive) {
+ d->c->setTrustedCertificates(trusted);
+ }
}
void TLS::setConstraints(SecurityLevel s)
{
- int min = 128;
- switch(s)
- {
- case SL_None:
- min = 0;
- break;
- case SL_Integrity:
- min = 1;
- break;
- case SL_Export:
- min = 40;
- break;
- case SL_Baseline:
- min = 128;
- break;
- case SL_High:
- min = 129;
- break;
- case SL_Highest:
- min = qMax(129, d->c->maxSSF());
- break;
- }
-
- d->con_ssfMode = true;
- d->con_minSSF = min;
- d->con_maxSSF = -1;
-
- if(d->state != TLS::Private::Inactive)
- d->c->setConstraints(d->con_minSSF, d->con_maxSSF);
+ int min = 128;
+ switch (s) {
+ case SL_None:
+ min = 0;
+ break;
+ case SL_Integrity:
+ min = 1;
+ break;
+ case SL_Export:
+ min = 40;
+ break;
+ case SL_Baseline:
+ min = 128;
+ break;
+ case SL_High:
+ min = 129;
+ break;
+ case SL_Highest:
+ min = qMax(129, d->c->maxSSF());
+ break;
+ }
+
+ d->con_ssfMode = true;
+ d->con_minSSF = min;
+ d->con_maxSSF = -1;
+
+ if (d->state != TLS::Private::Inactive) {
+ d->c->setConstraints(d->con_minSSF, d->con_maxSSF);
+ }
}
void TLS::setConstraints(int minSSF, int maxSSF)
{
- d->con_ssfMode = true;
- d->con_minSSF = minSSF;
- d->con_maxSSF = maxSSF;
+ d->con_ssfMode = true;
+ d->con_minSSF = minSSF;
+ d->con_maxSSF = maxSSF;
- if(d->state != TLS::Private::Inactive)
- d->c->setConstraints(d->con_minSSF, d->con_maxSSF);
+ if (d->state != TLS::Private::Inactive) {
+ d->c->setConstraints(d->con_minSSF, d->con_maxSSF);
+ }
}
void TLS::setConstraints(const QStringList &cipherSuiteList)
{
- d->con_ssfMode = false;
- d->con_cipherSuites = cipherSuiteList;
+ d->con_ssfMode = false;
+ d->con_cipherSuites = cipherSuiteList;
- if(d->state != TLS::Private::Inactive)
- d->c->setConstraints(d->con_cipherSuites);
+ if (d->state != TLS::Private::Inactive) {
+ d->c->setConstraints(d->con_cipherSuites);
+ }
}
QList<CertificateInfoOrdered> TLS::issuerList() const
{
- return d->issuerList;
+ return d->issuerList;
}
void TLS::setIssuerList(const QList<CertificateInfoOrdered> &issuers)
{
- d->issuerList = issuers;
- if(d->state != TLS::Private::Inactive)
- d->c->setIssuerList(issuers);
+ d->issuerList = issuers;
+ if (d->state != TLS::Private::Inactive) {
+ d->c->setIssuerList(issuers);
+ }
}
void TLS::setSession(const TLSSession &session)
{
- d->session = session;
+ d->session = session;
}
bool TLS::canCompress() const
{
- return d->c->canCompress();
+ return d->c->canCompress();
}
bool TLS::canSetHostName() const
{
- return d->c->canSetHostName();
+ return d->c->canSetHostName();
}
bool TLS::compressionEnabled() const
{
- return d->tryCompress;
+ return d->tryCompress;
}
void TLS::setCompressionEnabled(bool b)
{
- d->tryCompress = b;
+ d->tryCompress = b;
}
void TLS::startClient(const QString &host)
{
- d->reset(ResetSessionAndData);
- d->host = host;
- d->issuerList.clear();
+ d->reset(ResetSessionAndData);
+ d->host = host;
+ d->issuerList.clear();
- // client mode
- d->start(false);
+ // client mode
+ d->start(false);
}
void TLS::startServer()
{
- d->reset(ResetSessionAndData);
+ d->reset(ResetSessionAndData);
- // server mode
- d->start(true);
+ // server mode
+ d->start(true);
}
void TLS::continueAfterStep()
{
- d->continueAfterStep();
+ d->continueAfterStep();
}
bool TLS::isHandshaken() const
{
- if(d->state == TLS::Private::Connected || d->state == TLS::Private::Closing)
- return true;
- else
- return false;
+ if (d->state == TLS::Private::Connected || d->state == TLS::Private::Closing) {
+ return true;
+ } else {
+ return false;
+ }
}
bool TLS::isCompressed() const
{
- return d->sessionInfo.isCompressed;
+ return d->sessionInfo.isCompressed;
}
TLS::Version TLS::version() const
{
- return d->sessionInfo.version;
+ return d->sessionInfo.version;
}
QString TLS::cipherSuite() const
{
- return d->sessionInfo.cipherSuite;
+ return d->sessionInfo.cipherSuite;
}
int TLS::cipherBits() const
{
- return d->sessionInfo.cipherBits;
+ return d->sessionInfo.cipherBits;
}
int TLS::cipherMaxBits() const
{
- return d->sessionInfo.cipherMaxBits;
+ return d->sessionInfo.cipherMaxBits;
}
TLSSession TLS::session() const
{
- return d->session;
+ return d->session;
}
TLS::Error TLS::errorCode() const
{
- return d->errorCode;
+ return d->errorCode;
}
TLS::IdentityResult TLS::peerIdentityResult() const
{
- if(d->peerCert.isEmpty())
- return NoCertificate;
+ if (d->peerCert.isEmpty()) {
+ return NoCertificate;
+ }
- if(d->peerValidity != ValidityGood)
- return InvalidCertificate;
+ if (d->peerValidity != ValidityGood) {
+ return InvalidCertificate;
+ }
- if(d->hostMismatch)
- return HostMismatch;
+ if (d->hostMismatch) {
+ return HostMismatch;
+ }
- return Valid;
+ return Valid;
}
Validity TLS::peerCertificateValidity() const
{
- return d->peerValidity;
+ return d->peerValidity;
}
CertificateChain TLS::localCertificateChain() const
{
- return d->localCert;
+ return d->localCert;
}
PrivateKey TLS::localPrivateKey() const
{
- return d->localKey;
+ return d->localKey;
}
CertificateChain TLS::peerCertificateChain() const
{
- return d->peerCert;
+ return d->peerCert;
}
bool TLS::isClosable() const
{
- return true;
+ return true;
}
int TLS::bytesAvailable() const
{
- if(d->mode == Stream)
- return d->in.size();
- else
- return 0;
+ if (d->mode == Stream) {
+ return d->in.size();
+ } else {
+ return 0;
+ }
}
int TLS::bytesOutgoingAvailable() const
{
- if(d->mode == Stream)
- return d->to_net.size();
- else
- return 0;
+ if (d->mode == Stream) {
+ return d->to_net.size();
+ } else {
+ return 0;
+ }
}
void TLS::close()
{
- d->close();
- d->update();
+ d->close();
+ d->update();
}
void TLS::write(const QByteArray &a)
{
- if(d->mode == Stream)
- {
- d->out.append(a);
- d->layer.addPlain(a.size());
- }
- else
- d->packet_out.append(a);
- QCA_logTextMessage(QString("tls[%1]: write").arg(objectName()), Logger::Information);
- d->update();
+ if (d->mode == Stream) {
+ d->out.append(a);
+ d->layer.addPlain(a.size());
+ } else {
+ d->packet_out.append(a);
+ }
+ QCA_logTextMessage(QString("tls[%1]: write").arg(objectName()), Logger::Information);
+ d->update();
}
QByteArray TLS::read()
{
- if(d->mode == Stream)
- {
- QByteArray a = d->in;
- d->in.clear();
- return a;
- }
- else
- {
- if(!d->packet_in.isEmpty())
- return d->packet_in.takeFirst();
- else
- return QByteArray();
- }
+ if (d->mode == Stream) {
+ QByteArray a = d->in;
+ d->in.clear();
+ return a;
+ } else {
+ if (!d->packet_in.isEmpty()) {
+ return d->packet_in.takeFirst();
+ } else {
+ return QByteArray();
+ }
+ }
}
void TLS::writeIncoming(const QByteArray &a)
{
- if(d->mode == Stream)
- d->from_net.append(a);
- else
- d->packet_from_net.append(a);
- QCA_logTextMessage(QString("tls[%1]: writeIncoming %2").arg(objectName(), QString::number(a.size())), Logger::Information);
- d->update();
+ if (d->mode == Stream) {
+ d->from_net.append(a);
+ } else {
+ d->packet_from_net.append(a);
+ }
+ QCA_logTextMessage(QString("tls[%1]: writeIncoming %2").arg(objectName(), QString::number(a.size())), Logger::Information);
+ d->update();
}
QByteArray TLS::readOutgoing(int *plainBytes)
{
- if(d->mode == Stream)
- {
- QByteArray a = d->to_net;
- d->to_net.clear();
- if(plainBytes)
- *plainBytes = d->to_net_encoded;
- d->layer.specifyEncoded(a.size(), d->to_net_encoded);
- d->to_net_encoded = 0;
- return a;
- }
- else
- {
- if(!d->packet_to_net.isEmpty())
- {
- QByteArray a = d->packet_to_net.takeFirst();
- int x = d->packet_to_net_encoded.takeFirst();
- if(plainBytes)
- *plainBytes = x;
- return a;
- }
- else
- {
- if(plainBytes)
- *plainBytes = 0;
- return QByteArray();
- }
- }
+ if (d->mode == Stream) {
+ QByteArray a = d->to_net;
+ d->to_net.clear();
+ if (plainBytes) {
+ *plainBytes = d->to_net_encoded;
+ }
+ d->layer.specifyEncoded(a.size(), d->to_net_encoded);
+ d->to_net_encoded = 0;
+ return a;
+ } else {
+ if (!d->packet_to_net.isEmpty()) {
+ QByteArray a = d->packet_to_net.takeFirst();
+ int x = d->packet_to_net_encoded.takeFirst();
+ if (plainBytes) {
+ *plainBytes = x;
+ }
+ return a;
+ } else {
+ if (plainBytes) {
+ *plainBytes = 0;
+ }
+ return QByteArray();
+ }
+ }
}
QByteArray TLS::readUnprocessed()
{
- if(d->mode == Stream)
- {
- QByteArray a = d->unprocessed;
- d->unprocessed.clear();
- return a;
- }
- else
- return QByteArray();
+ if (d->mode == Stream) {
+ QByteArray a = d->unprocessed;
+ d->unprocessed.clear();
+ return a;
+ } else {
+ return QByteArray();
+ }
}
int TLS::convertBytesWritten(qint64 bytes)
{
- return d->layer.finished(bytes);
+ return d->layer.finished(bytes);
}
int TLS::packetsAvailable() const
{
- return d->packet_in.count();
+ return d->packet_in.count();
}
int TLS::packetsOutgoingAvailable() const
{
- return d->packet_to_net.count();
+ return d->packet_to_net.count();
}
int TLS::packetMTU() const
{
- return d->packet_mtu;
+ return d->packet_mtu;
}
void TLS::setPacketMTU(int size) const
{
- d->packet_mtu = size;
- if(d->state != TLS::Private::Inactive)
- d->c->setMTU(size);
+ d->packet_mtu = size;
+ if (d->state != TLS::Private::Inactive) {
+ d->c->setMTU(size);
+ }
}
#if QT_VERSION >= 0x050000
void TLS::connectNotify(const QMetaMethod &signal)
{
- if(signal == QMetaMethod::fromSignal(&TLS::hostNameReceived))
- d->connect_hostNameReceived = true;
- else if(signal == QMetaMethod::fromSignal(&TLS::certificateRequested))
- d->connect_certificateRequested = true;
- else if(signal == QMetaMethod::fromSignal(&TLS::peerCertificateAvailable))
- d->connect_peerCertificateAvailable = true;
- else if(signal == QMetaMethod::fromSignal(&TLS::handshaken))
- d->connect_handshaken = true;
+ if (signal == QMetaMethod::fromSignal(&TLS::hostNameReceived)) {
+ d->connect_hostNameReceived = true;
+ } else if (signal == QMetaMethod::fromSignal(&TLS::certificateRequested)) {
+ d->connect_certificateRequested = true;
+ } else if (signal == QMetaMethod::fromSignal(&TLS::peerCertificateAvailable)) {
+ d->connect_peerCertificateAvailable = true;
+ } else if (signal == QMetaMethod::fromSignal(&TLS::handshaken)) {
+ d->connect_handshaken = true;
+ }
}
void TLS::disconnectNotify(const QMetaMethod &signal)
{
- if(signal == QMetaMethod::fromSignal(&TLS::hostNameReceived))
- d->connect_hostNameReceived = false;
- else if(signal == QMetaMethod::fromSignal(&TLS::certificateRequested))
- d->connect_certificateRequested = false;
- else if(signal == QMetaMethod::fromSignal(&TLS::peerCertificateAvailable))
- d->connect_peerCertificateAvailable = false;
- else if(signal == QMetaMethod::fromSignal(&TLS::handshaken))
- d->connect_handshaken = false;
+ if (signal == QMetaMethod::fromSignal(&TLS::hostNameReceived)) {
+ d->connect_hostNameReceived = false;
+ } else if (signal == QMetaMethod::fromSignal(&TLS::certificateRequested)) {
+ d->connect_certificateRequested = false;
+ } else if (signal == QMetaMethod::fromSignal(&TLS::peerCertificateAvailable)) {
+ d->connect_peerCertificateAvailable = false;
+ } else if (signal == QMetaMethod::fromSignal(&TLS::handshaken)) {
+ d->connect_handshaken = false;
+ }
}
#else
void TLS::connectNotify(const char *signal)
{
- if(signal == QMetaObject::normalizedSignature(SIGNAL(hostNameReceived())))
- d->connect_hostNameReceived = true;
- else if(signal == QMetaObject::normalizedSignature(SIGNAL(certificateRequested())))
- d->connect_certificateRequested = true;
- else if(signal == QMetaObject::normalizedSignature(SIGNAL(peerCertificateAvailable())))
- d->connect_peerCertificateAvailable = true;
- else if(signal == QMetaObject::normalizedSignature(SIGNAL(handshaken())))
- d->connect_handshaken = true;
+ if (signal == QMetaObject::normalizedSignature(SIGNAL(hostNameReceived()))) {
+ d->connect_hostNameReceived = true;
+ } else if (signal == QMetaObject::normalizedSignature(SIGNAL(certificateRequested()))) {
+ d->connect_certificateRequested = true;
+ } else if (signal == QMetaObject::normalizedSignature(SIGNAL(peerCertificateAvailable()))) {
+ d->connect_peerCertificateAvailable = true;
+ } else if (signal == QMetaObject::normalizedSignature(SIGNAL(handshaken()))) {
+ d->connect_handshaken = true;
+ }
}
void TLS::disconnectNotify(const char *signal)
{
- if(signal == QMetaObject::normalizedSignature(SIGNAL(hostNameReceived())))
- d->connect_hostNameReceived = false;
- else if(signal == QMetaObject::normalizedSignature(SIGNAL(certificateRequested())))
- d->connect_certificateRequested = false;
- else if(signal == QMetaObject::normalizedSignature(SIGNAL(peerCertificateAvailable())))
- d->connect_peerCertificateAvailable = false;
- else if(signal == QMetaObject::normalizedSignature(SIGNAL(handshaken())))
- d->connect_handshaken = false;
+ if (signal == QMetaObject::normalizedSignature(SIGNAL(hostNameReceived()))) {
+ d->connect_hostNameReceived = false;
+ } else if (signal == QMetaObject::normalizedSignature(SIGNAL(certificateRequested()))) {
+ d->connect_certificateRequested = false;
+ } else if (signal == QMetaObject::normalizedSignature(SIGNAL(peerCertificateAvailable()))) {
+ d->connect_peerCertificateAvailable = false;
+ } else if (signal == QMetaObject::normalizedSignature(SIGNAL(handshaken()))) {
+ d->connect_handshaken = false;
+ }
}
#endif
//----------------------------------------------------------------------------
// SASL::Params
//----------------------------------------------------------------------------
class SASL::Params::Private
{
public:
- bool needUsername, canSendAuthzid, needPassword, canSendRealm;
+ bool needUsername, canSendAuthzid, needPassword, canSendRealm;
};
SASL::Params::Params()
-:d(new Private)
+ : d(new Private)
{
}
SASL::Params::Params(bool user, bool authzid, bool pass, bool realm)
-:d(new Private)
+ : d(new Private)
{
- d->needUsername = user;
- d->canSendAuthzid = authzid;
- d->needPassword = pass;
- d->canSendRealm = realm;
+ d->needUsername = user;
+ d->canSendAuthzid = authzid;
+ d->needPassword = pass;
+ d->canSendRealm = realm;
}
SASL::Params::Params(const SASL::Params &from)
-:d(new Private(*from.d))
+ : d(new Private(*from.d))
{
}
SASL::Params::~Params()
{
- delete d;
+ delete d;
}
-SASL::Params & SASL::Params::operator=(const SASL::Params &from)
+SASL::Params &SASL::Params::operator=(const SASL::Params &from)
{
- *d = *from.d;
- return *this;
+ *d = *from.d;
+ return *this;
}
bool SASL::Params::needUsername() const
{
- return d->needUsername;
+ return d->needUsername;
}
bool SASL::Params::canSendAuthzid() const
{
- return d->canSendAuthzid;
+ return d->canSendAuthzid;
}
bool SASL::Params::needPassword() const
{
- return d->needPassword;
+ return d->needPassword;
}
bool SASL::Params::canSendRealm() const
{
- return d->canSendRealm;
+ return d->canSendRealm;
}
//----------------------------------------------------------------------------
// SASL
//----------------------------------------------------------------------------
/*
These don't map, but I don't think it matters much..
SASL_TRYAGAIN (-8) transient failure (e.g., weak key)
SASL_BADMAC (-9) integrity check failed
-- client only codes --
SASL_WRONGMECH (-11) mechanism doesn't support requested feature
SASL_NEWSECRET (-12) new secret needed
-- server only codes --
SASL_TRANS (-17) One time use of a plaintext password will
enable requested mechanism for user
SASL_PWLOCK (-21) password locked
SASL_NOCHANGE (-22) requested change was not needed
*/
class SASL::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- enum
- {
- OpStart,
- OpServerFirstStep,
- OpNextStep,
- OpTryAgain,
- OpUpdate
- };
-
- class Action
- {
- public:
- enum Type
- {
- ClientStarted,
- NextStep,
- Authenticated,
- ReadyRead,
- ReadyReadOutgoing
- };
-
- int type;
- QByteArray stepData;
- bool haveInit;
-
- Action(int _type) : type(_type)
- {
- }
-
- Action(int _type, const QByteArray &_stepData) : type(_type), stepData(_stepData)
- {
- }
-
- Action(int _type, bool _haveInit, const QByteArray &_stepData) : type(_type), stepData(_stepData), haveInit(_haveInit)
- {
- }
- };
-
- SASL *q;
- SASLContext *c;
-
- // persistent settings (survives ResetSessionAndData)
- AuthFlags auth_flags;
- int ssfmin, ssfmax;
- QString ext_authid;
- int ext_ssf;
- bool localSet, remoteSet;
- SASLContext::HostPort local, remote;
- bool set_username, set_authzid, set_password, set_realm;
- QString username, authzid, realm;
- SecureArray password;
-
- // session
- bool server;
- QStringList mechlist;
- QString server_realm;
- bool allowClientSendFirst;
- bool disableServerSendLast;
- SafeTimer actionTrigger;
- int op;
- QList<Action> actionQueue;
- bool need_update;
- bool first;
- bool authed;
-
- // data (survives ResetSession)
- QString mech; // selected mech
- Error errorCode;
-
- // stream i/o
- QByteArray in, out;
- QByteArray to_net, from_net;
- int out_pending;
- int to_net_encoded;
- LayerTracker layer;
-
- Private(SASL *_q) : QObject(_q), q(_q), actionTrigger(this)
- {
- c = 0;
- set_username = false;
- set_authzid = false;
- set_password = false;
- set_realm = false;
-
- connect(&actionTrigger, SIGNAL(timeout()), SLOT(doNextAction()));
- actionTrigger.setSingleShot(true);
-
- reset(ResetAll);
-
- c = static_cast<SASLContext *>(q->context());
-
- // parent the context to us, so that moveToThread works
- c->setParent(this);
-
- connect(c, SIGNAL(resultsReady()), SLOT(sasl_resultsReady()));
- }
-
- ~Private()
- {
- // context is owned by Algorithm, unparent so we don't double-delete
- c->setParent(0);
- }
-
- void reset(ResetMode mode)
- {
- if(c)
- c->reset();
-
- server = false;
- mechlist.clear();
- server_realm = QString();
- allowClientSendFirst = false;
- disableServerSendLast = true;
- actionTrigger.stop();
- op = -1;
- actionQueue.clear();
- need_update = false;
- first = false;
- authed = false;
-
- out.clear();
- out_pending = 0;
-
- if(mode >= ResetSessionAndData)
- {
- mech = QString();
- errorCode = (SASL::Error)-1;
-
- in.clear();
- to_net.clear();
- from_net.clear();
- to_net_encoded = 0;
- layer.reset();
- }
-
- if(mode >= ResetAll)
- {
- auth_flags = SASL::AuthFlagsNone;
- ssfmin = 0;
- ssfmax = 0;
- ext_authid = QString();
- ext_ssf = 0;
- localSet = false;
- remoteSet = false;
- local = SASLContext::HostPort();
- remote = SASLContext::HostPort();
-
- set_username = false;
- username = QString();
- set_authzid = false;
- authzid = QString();
- set_password = false;
- password = SecureArray();
- set_realm = false;
- realm = QString();
- }
- }
-
- void setup(const QString &service, const QString &host)
- {
- c->setup(service, host, localSet ? &local : 0, remoteSet ? &remote : 0, ext_authid, ext_ssf);
- c->setConstraints(auth_flags, ssfmin, ssfmax);
-
- QString *p_username = 0;
- QString *p_authzid = 0;
- SecureArray *p_password = 0;
- QString *p_realm = 0;
-
- if(set_username)
- p_username = &username;
- if(set_authzid)
- p_authzid = &authzid;
- if(set_password)
- p_password = &password;
- if(set_realm)
- p_realm = &realm;
-
- c->setClientParams(p_username, p_authzid, p_password, p_realm);
- }
-
- void start()
- {
- op = OpStart;
- first = true;
-
- if(server)
- {
- QCA_logTextMessage(QString("sasl[%1]: c->startServer()").arg(q->objectName()), Logger::Information);
- c->startServer(server_realm, disableServerSendLast);
- }
- else
- {
- QCA_logTextMessage(QString("sasl[%1]: c->startClient()").arg(q->objectName()), Logger::Information);
- c->startClient(mechlist, allowClientSendFirst);
- }
- }
-
- void putServerFirstStep(const QString &mech, const QByteArray *clientInit)
- {
- if(op != -1)
- return;
-
- QCA_logTextMessage(QString("sasl[%1]: c->serverFirstStep()").arg(q->objectName()), Logger::Information);
- op = OpServerFirstStep;
- c->serverFirstStep(mech, clientInit);
- }
-
- void putStep(const QByteArray &stepData)
- {
- if(op != -1)
- return;
-
- QCA_logTextMessage(QString("sasl[%1]: c->nextStep()").arg(q->objectName()), Logger::Information);
- op = OpNextStep;
- c->nextStep(stepData);
- }
-
- void tryAgain()
- {
- if(op != -1)
- return;
-
- QCA_logTextMessage(QString("sasl[%1]: c->tryAgain()").arg(q->objectName()), Logger::Information);
- op = OpTryAgain;
- c->tryAgain();
- }
-
- void processNextAction()
- {
- if(actionQueue.isEmpty())
- {
- if(need_update)
- update();
- return;
- }
-
- Action a = actionQueue.takeFirst();
-
- // set up for the next one, if necessary
- if(!actionQueue.isEmpty() || need_update)
- {
- if(!actionTrigger.isActive())
- actionTrigger.start();
- }
-
- if(a.type == Action::ClientStarted)
- {
- emit q->clientStarted(a.haveInit, a.stepData);
- }
- else if(a.type == Action::NextStep)
- {
- emit q->nextStep(a.stepData);
- }
- else if(a.type == Action::Authenticated)
- {
- authed = true;
-
- // write any app data waiting during authentication
- if(!out.isEmpty())
- {
- need_update = true;
- if(!actionTrigger.isActive())
- actionTrigger.start();
- }
-
- QCA_logTextMessage(QString("sasl[%1]: authenticated").arg(q->objectName()), Logger::Information);
- emit q->authenticated();
- }
- else if(a.type == Action::ReadyRead)
- {
- emit q->readyRead();
- }
- else if(a.type == Action::ReadyReadOutgoing)
- {
- emit q->readyReadOutgoing();
- }
- }
-
- void update()
- {
- // defer writes while authenticating
- if(!authed)
- {
- QCA_logTextMessage(QString("sasl[%1]: ignoring update while not yet authenticated").arg(q->objectName()), Logger::Information);
- return;
- }
-
- if(!actionQueue.isEmpty())
- {
- QCA_logTextMessage(QString("sasl[%1]: ignoring update while processing actions").arg(q->objectName()), Logger::Information);
- need_update = true;
- return;
- }
-
- // only allow one operation at a time
- if(op != -1)
- {
- QCA_logTextMessage(QString("sasl[%1]: ignoring update while operation active").arg(q->objectName()), Logger::Information);
- need_update = true;
- return;
- }
-
- need_update = false;
-
- QCA_logTextMessage(QString("sasl[%1]: c->update()").arg(q->objectName()), Logger::Information);
- op = OpUpdate;
- out_pending += out.size();
- c->update(from_net, out);
- from_net.clear();
- out.clear();
- }
+ enum {
+ OpStart,
+ OpServerFirstStep,
+ OpNextStep,
+ OpTryAgain,
+ OpUpdate
+ };
+
+ class Action
+ {
+ public:
+ enum Type {
+ ClientStarted,
+ NextStep,
+ Authenticated,
+ ReadyRead,
+ ReadyReadOutgoing
+ };
+
+ int type;
+ QByteArray stepData;
+ bool haveInit;
+
+ Action(int _type) : type(_type)
+ {
+ }
+
+ Action(int _type, const QByteArray &_stepData) : type(_type), stepData(_stepData)
+ {
+ }
+
+ Action(int _type, bool _haveInit, const QByteArray &_stepData) : type(_type), stepData(_stepData), haveInit(_haveInit)
+ {
+ }
+ };
+
+ SASL *q;
+ SASLContext *c;
+
+ // persistent settings (survives ResetSessionAndData)
+ AuthFlags auth_flags;
+ int ssfmin, ssfmax;
+ QString ext_authid;
+ int ext_ssf;
+ bool localSet, remoteSet;
+ SASLContext::HostPort local, remote;
+ bool set_username, set_authzid, set_password, set_realm;
+ QString username, authzid, realm;
+ SecureArray password;
+
+ // session
+ bool server;
+ QStringList mechlist;
+ QString server_realm;
+ bool allowClientSendFirst;
+ bool disableServerSendLast;
+ SafeTimer actionTrigger;
+ int op;
+ QList<Action> actionQueue;
+ bool need_update;
+ bool first;
+ bool authed;
+
+ // data (survives ResetSession)
+ QString mech; // selected mech
+ Error errorCode;
+
+ // stream i/o
+ QByteArray in, out;
+ QByteArray to_net, from_net;
+ int out_pending;
+ int to_net_encoded;
+ LayerTracker layer;
+
+ Private(SASL *_q) : QObject(_q), q(_q), actionTrigger(this)
+ {
+ c = 0;
+ set_username = false;
+ set_authzid = false;
+ set_password = false;
+ set_realm = false;
+
+ connect(&actionTrigger, SIGNAL(timeout()), SLOT(doNextAction()));
+ actionTrigger.setSingleShot(true);
+
+ reset(ResetAll);
+
+ c = static_cast<SASLContext *>(q->context());
+
+ // parent the context to us, so that moveToThread works
+ c->setParent(this);
+
+ connect(c, SIGNAL(resultsReady()), SLOT(sasl_resultsReady()));
+ }
+
+ ~Private()
+ {
+ // context is owned by Algorithm, unparent so we don't double-delete
+ c->setParent(0);
+ }
+
+ void reset(ResetMode mode)
+ {
+ if (c) {
+ c->reset();
+ }
+
+ server = false;
+ mechlist.clear();
+ server_realm = QString();
+ allowClientSendFirst = false;
+ disableServerSendLast = true;
+ actionTrigger.stop();
+ op = -1;
+ actionQueue.clear();
+ need_update = false;
+ first = false;
+ authed = false;
+
+ out.clear();
+ out_pending = 0;
+
+ if (mode >= ResetSessionAndData) {
+ mech = QString();
+ errorCode = (SASL::Error) - 1;
+
+ in.clear();
+ to_net.clear();
+ from_net.clear();
+ to_net_encoded = 0;
+ layer.reset();
+ }
+
+ if (mode >= ResetAll) {
+ auth_flags = SASL::AuthFlagsNone;
+ ssfmin = 0;
+ ssfmax = 0;
+ ext_authid = QString();
+ ext_ssf = 0;
+ localSet = false;
+ remoteSet = false;
+ local = SASLContext::HostPort();
+ remote = SASLContext::HostPort();
+
+ set_username = false;
+ username = QString();
+ set_authzid = false;
+ authzid = QString();
+ set_password = false;
+ password = SecureArray();
+ set_realm = false;
+ realm = QString();
+ }
+ }
+
+ void setup(const QString &service, const QString &host)
+ {
+ c->setup(service, host, localSet ? &local : 0, remoteSet ? &remote : 0, ext_authid, ext_ssf);
+ c->setConstraints(auth_flags, ssfmin, ssfmax);
+
+ QString *p_username = 0;
+ QString *p_authzid = 0;
+ SecureArray *p_password = 0;
+ QString *p_realm = 0;
+
+ if (set_username) {
+ p_username = &username;
+ }
+ if (set_authzid) {
+ p_authzid = &authzid;
+ }
+ if (set_password) {
+ p_password = &password;
+ }
+ if (set_realm) {
+ p_realm = &realm;
+ }
+
+ c->setClientParams(p_username, p_authzid, p_password, p_realm);
+ }
+
+ void start()
+ {
+ op = OpStart;
+ first = true;
+
+ if (server) {
+ QCA_logTextMessage(QString("sasl[%1]: c->startServer()").arg(q->objectName()), Logger::Information);
+ c->startServer(server_realm, disableServerSendLast);
+ } else {
+ QCA_logTextMessage(QString("sasl[%1]: c->startClient()").arg(q->objectName()), Logger::Information);
+ c->startClient(mechlist, allowClientSendFirst);
+ }
+ }
+
+ void putServerFirstStep(const QString &mech, const QByteArray *clientInit)
+ {
+ if (op != -1) {
+ return;
+ }
+
+ QCA_logTextMessage(QString("sasl[%1]: c->serverFirstStep()").arg(q->objectName()), Logger::Information);
+ op = OpServerFirstStep;
+ c->serverFirstStep(mech, clientInit);
+ }
+
+ void putStep(const QByteArray &stepData)
+ {
+ if (op != -1) {
+ return;
+ }
+
+ QCA_logTextMessage(QString("sasl[%1]: c->nextStep()").arg(q->objectName()), Logger::Information);
+ op = OpNextStep;
+ c->nextStep(stepData);
+ }
+
+ void tryAgain()
+ {
+ if (op != -1) {
+ return;
+ }
+
+ QCA_logTextMessage(QString("sasl[%1]: c->tryAgain()").arg(q->objectName()), Logger::Information);
+ op = OpTryAgain;
+ c->tryAgain();
+ }
+
+ void processNextAction()
+ {
+ if (actionQueue.isEmpty()) {
+ if (need_update) {
+ update();
+ }
+ return;
+ }
+
+ Action a = actionQueue.takeFirst();
+
+ // set up for the next one, if necessary
+ if (!actionQueue.isEmpty() || need_update) {
+ if (!actionTrigger.isActive()) {
+ actionTrigger.start();
+ }
+ }
+
+ if (a.type == Action::ClientStarted) {
+ emit q->clientStarted(a.haveInit, a.stepData);
+ } else if (a.type == Action::NextStep) {
+ emit q->nextStep(a.stepData);
+ } else if (a.type == Action::Authenticated) {
+ authed = true;
+
+ // write any app data waiting during authentication
+ if (!out.isEmpty()) {
+ need_update = true;
+ if (!actionTrigger.isActive()) {
+ actionTrigger.start();
+ }
+ }
+
+ QCA_logTextMessage(QString("sasl[%1]: authenticated").arg(q->objectName()), Logger::Information);
+ emit q->authenticated();
+ } else if (a.type == Action::ReadyRead) {
+ emit q->readyRead();
+ } else if (a.type == Action::ReadyReadOutgoing) {
+ emit q->readyReadOutgoing();
+ }
+ }
+
+ void update()
+ {
+ // defer writes while authenticating
+ if (!authed) {
+ QCA_logTextMessage(QString("sasl[%1]: ignoring update while not yet authenticated").arg(q->objectName()), Logger::Information);
+ return;
+ }
+
+ if (!actionQueue.isEmpty()) {
+ QCA_logTextMessage(QString("sasl[%1]: ignoring update while processing actions").arg(q->objectName()), Logger::Information);
+ need_update = true;
+ return;
+ }
+
+ // only allow one operation at a time
+ if (op != -1) {
+ QCA_logTextMessage(QString("sasl[%1]: ignoring update while operation active").arg(q->objectName()), Logger::Information);
+ need_update = true;
+ return;
+ }
+
+ need_update = false;
+
+ QCA_logTextMessage(QString("sasl[%1]: c->update()").arg(q->objectName()), Logger::Information);
+ op = OpUpdate;
+ out_pending += out.size();
+ c->update(from_net, out);
+ from_net.clear();
+ out.clear();
+ }
private slots:
- void sasl_resultsReady()
- {
- QCA_logTextMessage(QString("sasl[%1]: c->resultsReady()").arg(q->objectName()), Logger::Information);
-
- int last_op = op;
- op = -1;
-
- SASLContext::Result r = c->result();
-
- if(last_op == OpStart)
- {
- if(server)
- {
- if(r != SASLContext::Success)
- {
- errorCode = SASL::ErrorInit;
- emit q->error();
- return;
- }
-
- emit q->serverStarted();
- return;
- }
- else // client
- {
- mech = c->mech();
-
- // fall into this logic
- last_op = OpTryAgain;
- }
- }
- else if(last_op == OpServerFirstStep)
- {
- // fall into this logic
- last_op = OpTryAgain;
- }
- else if(last_op == OpNextStep)
- {
- // fall into this logic
- last_op = OpTryAgain;
- }
-
- if(last_op == OpTryAgain)
- {
- if(server)
- {
- if(r == SASLContext::Continue)
- {
- emit q->nextStep(c->stepData());
- return;
- }
- else if(r == SASLContext::AuthCheck)
- {
- emit q->authCheck(c->username(), c->authzid());
- return;
- }
- else if(r == SASLContext::Success)
- {
- if(!disableServerSendLast)
- actionQueue += Action(Action::NextStep, c->stepData());
-
- actionQueue += Action(Action::Authenticated);
-
- processNextAction();
- return;
- }
- else // error
- {
- errorCode = SASL::ErrorHandshake;
- emit q->error();
- return;
- }
- }
- else // client
- {
- if(first)
- {
- if(r == SASLContext::Error)
- {
- if(first)
- errorCode = SASL::ErrorInit;
- else
- errorCode = SASL::ErrorHandshake;
- emit q->error();
- return;
- }
- else if(r == SASLContext::Params)
- {
- Params np = c->clientParams();
- emit q->needParams(np);
- return;
- }
-
- first = false;
- actionQueue += Action(Action::ClientStarted, c->haveClientInit(), c->stepData());
- if(r == SASLContext::Success)
- actionQueue += Action(Action::Authenticated);
-
- processNextAction();
- return;
- }
- else
- {
- if(r == SASLContext::Error)
- {
- errorCode = ErrorHandshake;
- emit q->error();
- return;
- }
- else if(r == SASLContext::Params)
- {
- Params np = c->clientParams();
- emit q->needParams(np);
- return;
- }
- else if(r == SASLContext::Continue)
- {
- emit q->nextStep(c->stepData());
- return;
- }
- else if(r == SASLContext::Success)
- {
- actionQueue += Action(Action::NextStep, c->stepData());
- actionQueue += Action(Action::Authenticated);
-
- processNextAction();
- return;
- }
- }
- }
- }
- else if(last_op == OpUpdate)
- {
- if(r != SASLContext::Success)
- {
- errorCode = ErrorCrypt;
- emit q->error();
- return;
- }
-
- QByteArray c_to_net = c->to_net();
- QByteArray c_to_app = c->to_app();
- int enc = -1;
- if(!c_to_net.isEmpty())
- enc = c->encoded();
-
- bool io_pending = false;
- if(!c_to_net.isEmpty())
- out_pending -= enc;
-
- if(out_pending > 0)
- io_pending = true;
-
- if(!out.isEmpty())
- io_pending = true;
-
- to_net += c_to_net;
- in += c_to_app;
- to_net_encoded += enc;
-
- if(!c_to_net.isEmpty())
- actionQueue += Action(Action::ReadyReadOutgoing);
-
- if(!c_to_app.isEmpty())
- actionQueue += Action(Action::ReadyRead);
-
- if(io_pending)
- update();
-
- processNextAction();
- return;
- }
- }
-
- void doNextAction()
- {
- processNextAction();
- }
+ void sasl_resultsReady()
+ {
+ QCA_logTextMessage(QString("sasl[%1]: c->resultsReady()").arg(q->objectName()), Logger::Information);
+
+ int last_op = op;
+ op = -1;
+
+ SASLContext::Result r = c->result();
+
+ if (last_op == OpStart) {
+ if (server) {
+ if (r != SASLContext::Success) {
+ errorCode = SASL::ErrorInit;
+ emit q->error();
+ return;
+ }
+
+ emit q->serverStarted();
+ return;
+ } else { // client
+ mech = c->mech();
+
+ // fall into this logic
+ last_op = OpTryAgain;
+ }
+ } else if (last_op == OpServerFirstStep) {
+ // fall into this logic
+ last_op = OpTryAgain;
+ } else if (last_op == OpNextStep) {
+ // fall into this logic
+ last_op = OpTryAgain;
+ }
+
+ if (last_op == OpTryAgain) {
+ if (server) {
+ if (r == SASLContext::Continue) {
+ emit q->nextStep(c->stepData());
+ return;
+ } else if (r == SASLContext::AuthCheck) {
+ emit q->authCheck(c->username(), c->authzid());
+ return;
+ } else if (r == SASLContext::Success) {
+ if (!disableServerSendLast) {
+ actionQueue += Action(Action::NextStep, c->stepData());
+ }
+
+ actionQueue += Action(Action::Authenticated);
+
+ processNextAction();
+ return;
+ } else { // error
+ errorCode = SASL::ErrorHandshake;
+ emit q->error();
+ return;
+ }
+ } else { // client
+ if (first) {
+ if (r == SASLContext::Error) {
+ if (first) {
+ errorCode = SASL::ErrorInit;
+ } else {
+ errorCode = SASL::ErrorHandshake;
+ }
+ emit q->error();
+ return;
+ } else if (r == SASLContext::Params) {
+ Params np = c->clientParams();
+ emit q->needParams(np);
+ return;
+ }
+
+ first = false;
+ actionQueue += Action(Action::ClientStarted, c->haveClientInit(), c->stepData());
+ if (r == SASLContext::Success) {
+ actionQueue += Action(Action::Authenticated);
+ }
+
+ processNextAction();
+ return;
+ } else {
+ if (r == SASLContext::Error) {
+ errorCode = ErrorHandshake;
+ emit q->error();
+ return;
+ } else if (r == SASLContext::Params) {
+ Params np = c->clientParams();
+ emit q->needParams(np);
+ return;
+ } else if (r == SASLContext::Continue) {
+ emit q->nextStep(c->stepData());
+ return;
+ } else if (r == SASLContext::Success) {
+ actionQueue += Action(Action::NextStep, c->stepData());
+ actionQueue += Action(Action::Authenticated);
+
+ processNextAction();
+ return;
+ }
+ }
+ }
+ } else if (last_op == OpUpdate) {
+ if (r != SASLContext::Success) {
+ errorCode = ErrorCrypt;
+ emit q->error();
+ return;
+ }
+
+ QByteArray c_to_net = c->to_net();
+ QByteArray c_to_app = c->to_app();
+ int enc = -1;
+ if (!c_to_net.isEmpty()) {
+ enc = c->encoded();
+ }
+
+ bool io_pending = false;
+ if (!c_to_net.isEmpty()) {
+ out_pending -= enc;
+ }
+
+ if (out_pending > 0) {
+ io_pending = true;
+ }
+
+ if (!out.isEmpty()) {
+ io_pending = true;
+ }
+
+ to_net += c_to_net;
+ in += c_to_app;
+ to_net_encoded += enc;
+
+ if (!c_to_net.isEmpty()) {
+ actionQueue += Action(Action::ReadyReadOutgoing);
+ }
+
+ if (!c_to_app.isEmpty()) {
+ actionQueue += Action(Action::ReadyRead);
+ }
+
+ if (io_pending) {
+ update();
+ }
+
+ processNextAction();
+ return;
+ }
+ }
+
+ void doNextAction()
+ {
+ processNextAction();
+ }
};
SASL::SASL(QObject *parent, const QString &provider)
-:SecureLayer(parent), Algorithm("sasl", provider)
+ : SecureLayer(parent), Algorithm("sasl", provider)
{
- d = new Private(this);
+ d = new Private(this);
}
SASL::~SASL()
{
- delete d;
+ delete d;
}
void SASL::reset()
{
- d->reset(ResetAll);
+ d->reset(ResetAll);
}
SASL::Error SASL::errorCode() const
{
- return d->errorCode;
+ return d->errorCode;
}
SASL::AuthCondition SASL::authCondition() const
{
- return d->c->authCondition();
+ return d->c->authCondition();
}
void SASL::setConstraints(AuthFlags f, SecurityLevel s)
{
- int min = 0;
- if(s == SL_Integrity)
- min = 1;
- else if(s == SL_Export)
- min = 56;
- else if(s == SL_Baseline)
- min = 128;
- else if(s == SL_High)
- min = 192;
- else if(s == SL_Highest)
- min = 256;
+ int min = 0;
+ if (s == SL_Integrity) {
+ min = 1;
+ } else if (s == SL_Export) {
+ min = 56;
+ } else if (s == SL_Baseline) {
+ min = 128;
+ } else if (s == SL_High) {
+ min = 192;
+ } else if (s == SL_Highest) {
+ min = 256;
+ }
- setConstraints(f, min, 256);
+ setConstraints(f, min, 256);
}
void SASL::setConstraints(AuthFlags f, int minSSF, int maxSSF)
{
- d->auth_flags = f;
+ d->auth_flags = f;
- d->ssfmin = minSSF;
- d->ssfmax = maxSSF;
+ d->ssfmin = minSSF;
+ d->ssfmax = maxSSF;
}
void SASL::setExternalAuthId(const QString &authid)
{
- d->ext_authid = authid;
+ d->ext_authid = authid;
}
void SASL::setExternalSSF(int strength)
{
- d->ext_ssf = strength;
+ d->ext_ssf = strength;
}
void SASL::setLocalAddress(const QString &addr, quint16 port)
{
- d->localSet = true;
- d->local.addr = addr;
- d->local.port = port;
+ d->localSet = true;
+ d->local.addr = addr;
+ d->local.port = port;
}
void SASL::setRemoteAddress(const QString &addr, quint16 port)
{
- d->remoteSet = true;
- d->remote.addr = addr;
- d->remote.port = port;
+ d->remoteSet = true;
+ d->remote.addr = addr;
+ d->remote.port = port;
}
void SASL::startClient(const QString &service, const QString &host, const QStringList &mechlist, ClientSendMode mode)
{
- d->reset(ResetSessionAndData);
- d->setup(service, host);
- d->server = false;
- d->mechlist = mechlist;
- d->allowClientSendFirst = (mode == AllowClientSendFirst);
- d->start();
+ d->reset(ResetSessionAndData);
+ d->setup(service, host);
+ d->server = false;
+ d->mechlist = mechlist;
+ d->allowClientSendFirst = (mode == AllowClientSendFirst);
+ d->start();
}
void SASL::startServer(const QString &service, const QString &host, const QString &realm, ServerSendMode mode)
{
- d->reset(ResetSessionAndData);
- d->setup(service, host);
- d->server = true;
- d->server_realm = realm;
- d->disableServerSendLast = (mode == DisableServerSendLast);
- d->start();
+ d->reset(ResetSessionAndData);
+ d->setup(service, host);
+ d->server = true;
+ d->server_realm = realm;
+ d->disableServerSendLast = (mode == DisableServerSendLast);
+ d->start();
}
void SASL::putServerFirstStep(const QString &mech)
{
- d->putServerFirstStep(mech, 0);
+ d->putServerFirstStep(mech, 0);
}
void SASL::putServerFirstStep(const QString &mech, const QByteArray &clientInit)
{
- d->putServerFirstStep(mech, &clientInit);
+ d->putServerFirstStep(mech, &clientInit);
}
void SASL::putStep(const QByteArray &stepData)
{
- d->putStep(stepData);
+ d->putStep(stepData);
}
void SASL::setUsername(const QString &user)
{
- d->set_username = true;
- d->username = user;
- d->c->setClientParams(&user, 0, 0, 0);
+ d->set_username = true;
+ d->username = user;
+ d->c->setClientParams(&user, 0, 0, 0);
}
void SASL::setAuthzid(const QString &authzid)
{
- d->set_authzid = true;
- d->authzid = authzid;
- d->c->setClientParams(0, &authzid, 0, 0);
+ d->set_authzid = true;
+ d->authzid = authzid;
+ d->c->setClientParams(0, &authzid, 0, 0);
}
void SASL::setPassword(const SecureArray &pass)
{
- d->set_password = true;
- d->password = pass;
- d->c->setClientParams(0, 0, &pass, 0);
+ d->set_password = true;
+ d->password = pass;
+ d->c->setClientParams(0, 0, &pass, 0);
}
void SASL::setRealm(const QString &realm)
{
- d->set_realm = true;
- d->realm = realm;
- d->c->setClientParams(0, 0, 0, &realm);
+ d->set_realm = true;
+ d->realm = realm;
+ d->c->setClientParams(0, 0, 0, &realm);
}
void SASL::continueAfterParams()
{
- d->tryAgain();
+ d->tryAgain();
}
void SASL::continueAfterAuthCheck()
{
- d->tryAgain();
+ d->tryAgain();
}
QString SASL::mechanism() const
{
- return d->mech;
+ return d->mech;
}
QStringList SASL::mechanismList() const
{
- return d->c->mechlist();
+ return d->c->mechlist();
}
QStringList SASL::realmList() const
{
- return d->c->realmlist();
+ return d->c->realmlist();
}
int SASL::ssf() const
{
- return d->c->ssf();
+ return d->c->ssf();
}
int SASL::bytesAvailable() const
{
- return d->in.size();
+ return d->in.size();
}
int SASL::bytesOutgoingAvailable() const
{
- return d->to_net.size();
+ return d->to_net.size();
}
void SASL::write(const QByteArray &a)
{
- d->out.append(a);
- d->layer.addPlain(a.size());
- d->update();
+ d->out.append(a);
+ d->layer.addPlain(a.size());
+ d->update();
}
QByteArray SASL::read()
{
- QByteArray a = d->in;
- d->in.clear();
- return a;
+ QByteArray a = d->in;
+ d->in.clear();
+ return a;
}
void SASL::writeIncoming(const QByteArray &a)
{
- d->from_net.append(a);
- d->update();
+ d->from_net.append(a);
+ d->update();
}
QByteArray SASL::readOutgoing(int *plainBytes)
{
- QByteArray a = d->to_net;
- d->to_net.clear();
- if(plainBytes)
- *plainBytes = d->to_net_encoded;
- d->layer.specifyEncoded(a.size(), d->to_net_encoded);
- d->to_net_encoded = 0;
- return a;
+ QByteArray a = d->to_net;
+ d->to_net.clear();
+ if (plainBytes) {
+ *plainBytes = d->to_net_encoded;
+ }
+ d->layer.specifyEncoded(a.size(), d->to_net_encoded);
+ d->to_net_encoded = 0;
+ return a;
}
int SASL::convertBytesWritten(qint64 bytes)
{
- return d->layer.finished(bytes);
+ return d->layer.finished(bytes);
}
}
#include "qca_securelayer.moc"
diff --git a/src/qca_securemessage.cpp b/src/qca_securemessage.cpp
index 02303cf3..a4541aa4 100644
--- a/src/qca_securemessage.cpp
+++ b/src/qca_securemessage.cpp
@@ -1,688 +1,685 @@
/*
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_securemessage.h"
#include "qcaprovider.h"
#include "qca_safeobj.h"
#include "qca_safetimer.h"
-namespace QCA {
+namespace QCA
+{
Provider::Context *getContext(const QString &type, const QString &provider);
//----------------------------------------------------------------------------
// SecureMessageKey
//----------------------------------------------------------------------------
class SecureMessageKey::Private : public QSharedData
{
public:
- SecureMessageKey::Type type;
- PGPKey pgp_pub, pgp_sec;
- CertificateChain cert_pub;
- PrivateKey cert_sec;
-
- Private()
- {
- type = SecureMessageKey::None;
- }
-
- // set the proper type, and reset the opposite data structures if needed
- void ensureType(SecureMessageKey::Type t)
- {
- // if we were non-null and changed, we may need to reset some things
- if(type != SecureMessageKey::None && t != type)
- {
- if(type == SecureMessageKey::X509)
- {
- cert_pub = CertificateChain();
- cert_sec = PrivateKey();
- }
- else if(type == SecureMessageKey::PGP)
- {
- pgp_pub = PGPKey();
- pgp_sec = PGPKey();
- }
- }
- type = t;
- }
+ SecureMessageKey::Type type;
+ PGPKey pgp_pub, pgp_sec;
+ CertificateChain cert_pub;
+ PrivateKey cert_sec;
+
+ Private()
+ {
+ type = SecureMessageKey::None;
+ }
+
+ // set the proper type, and reset the opposite data structures if needed
+ void ensureType(SecureMessageKey::Type t)
+ {
+ // if we were non-null and changed, we may need to reset some things
+ if (type != SecureMessageKey::None && t != type) {
+ if (type == SecureMessageKey::X509) {
+ cert_pub = CertificateChain();
+ cert_sec = PrivateKey();
+ } else if (type == SecureMessageKey::PGP) {
+ pgp_pub = PGPKey();
+ pgp_sec = PGPKey();
+ }
+ }
+ type = t;
+ }
};
SecureMessageKey::SecureMessageKey()
-:d(new Private)
+ : d(new Private)
{
}
SecureMessageKey::SecureMessageKey(const SecureMessageKey &from)
-:d(from.d)
+ : d(from.d)
{
}
SecureMessageKey::~SecureMessageKey()
{
}
-SecureMessageKey & SecureMessageKey::operator=(const SecureMessageKey &from)
+SecureMessageKey &SecureMessageKey::operator=(const SecureMessageKey &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
bool SecureMessageKey::isNull() const
{
- return (d->type == None);
+ return (d->type == None);
}
SecureMessageKey::Type SecureMessageKey::type() const
{
- return d->type;
+ return d->type;
}
PGPKey SecureMessageKey::pgpPublicKey() const
{
- return d->pgp_pub;
+ return d->pgp_pub;
}
PGPKey SecureMessageKey::pgpSecretKey() const
{
- return d->pgp_sec;
+ return d->pgp_sec;
}
void SecureMessageKey::setPGPPublicKey(const PGPKey &pub)
{
- d->ensureType(SecureMessageKey::PGP);
- d->pgp_pub = pub;
+ d->ensureType(SecureMessageKey::PGP);
+ d->pgp_pub = pub;
}
void SecureMessageKey::setPGPSecretKey(const PGPKey &sec)
{
- d->ensureType(SecureMessageKey::PGP);
- Q_ASSERT(sec.isSecret());
- d->pgp_sec = sec;
+ d->ensureType(SecureMessageKey::PGP);
+ Q_ASSERT(sec.isSecret());
+ d->pgp_sec = sec;
}
CertificateChain SecureMessageKey::x509CertificateChain() const
{
- return d->cert_pub;
+ return d->cert_pub;
}
PrivateKey SecureMessageKey::x509PrivateKey() const
{
- return d->cert_sec;
+ return d->cert_sec;
}
void SecureMessageKey::setX509CertificateChain(const CertificateChain &c)
{
- d->ensureType(SecureMessageKey::X509);
- d->cert_pub = c;
+ d->ensureType(SecureMessageKey::X509);
+ d->cert_pub = c;
}
void SecureMessageKey::setX509PrivateKey(const PrivateKey &k)
{
- d->ensureType(SecureMessageKey::X509);
- d->cert_sec = k;
+ d->ensureType(SecureMessageKey::X509);
+ d->cert_sec = k;
}
void SecureMessageKey::setX509KeyBundle(const KeyBundle &kb)
{
- setX509CertificateChain(kb.certificateChain());
- setX509PrivateKey(kb.privateKey());
+ setX509CertificateChain(kb.certificateChain());
+ setX509PrivateKey(kb.privateKey());
}
bool SecureMessageKey::havePrivate() const
{
- if(d->type == SecureMessageKey::PGP && !d->pgp_sec.isNull())
- return true;
- else if(d->type == SecureMessageKey::X509 && !d->cert_sec.isNull())
- return true;
- return false;
+ if (d->type == SecureMessageKey::PGP && !d->pgp_sec.isNull()) {
+ return true;
+ } else if (d->type == SecureMessageKey::X509 && !d->cert_sec.isNull()) {
+ return true;
+ }
+ return false;
}
QString SecureMessageKey::name() const
{
- if(d->type == SecureMessageKey::PGP && !d->pgp_pub.isNull())
- return d->pgp_pub.primaryUserId();
- else if(d->type == SecureMessageKey::X509 && !d->cert_pub.isEmpty())
- return d->cert_pub.primary().commonName();
- else
- return QString();
+ if (d->type == SecureMessageKey::PGP && !d->pgp_pub.isNull()) {
+ return d->pgp_pub.primaryUserId();
+ } else if (d->type == SecureMessageKey::X509 && !d->cert_pub.isEmpty()) {
+ return d->cert_pub.primary().commonName();
+ } else {
+ return QString();
+ }
}
//----------------------------------------------------------------------------
// SecureMessageSignature
//----------------------------------------------------------------------------
class SecureMessageSignature::Private : public QSharedData
{
public:
- SecureMessageSignature::IdentityResult r;
- Validity v;
- SecureMessageKey key;
- QDateTime ts;
-
- Private()
- {
- r = SecureMessageSignature::NoKey;
- v = ErrorValidityUnknown;
- }
+ SecureMessageSignature::IdentityResult r;
+ Validity v;
+ SecureMessageKey key;
+ QDateTime ts;
+
+ Private()
+ {
+ r = SecureMessageSignature::NoKey;
+ v = ErrorValidityUnknown;
+ }
};
SecureMessageSignature::SecureMessageSignature()
-:d(new Private)
+ : d(new Private)
{
}
SecureMessageSignature::SecureMessageSignature(IdentityResult r, Validity v, const SecureMessageKey &key, const QDateTime &ts)
-:d(new Private)
+ : d(new Private)
{
- d->r = r;
- d->v = v;
- d->key = key;
- d->ts = ts;
+ d->r = r;
+ d->v = v;
+ d->key = key;
+ d->ts = ts;
}
SecureMessageSignature::SecureMessageSignature(const SecureMessageSignature &from)
-:d(from.d)
+ : d(from.d)
{
}
SecureMessageSignature::~SecureMessageSignature()
{
}
-SecureMessageSignature & SecureMessageSignature::operator=(const SecureMessageSignature &from)
+SecureMessageSignature &SecureMessageSignature::operator=(const SecureMessageSignature &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
SecureMessageSignature::IdentityResult SecureMessageSignature::identityResult() const
{
- return d->r;
+ return d->r;
}
Validity SecureMessageSignature::keyValidity() const
{
- return d->v;
+ return d->v;
}
SecureMessageKey SecureMessageSignature::key() const
{
- return d->key;
+ return d->key;
}
QDateTime SecureMessageSignature::timestamp() const
{
- return d->ts;
+ return d->ts;
}
//----------------------------------------------------------------------------
// SecureMessage
//----------------------------------------------------------------------------
-enum ResetMode
-{
- ResetSession = 0,
- ResetSessionAndData = 1,
- ResetAll = 2
+enum ResetMode {
+ ResetSession = 0,
+ ResetSessionAndData = 1,
+ ResetAll = 2
};
class SecureMessage::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SecureMessage *q;
- MessageContext *c;
- SecureMessageSystem *system;
-
- bool bundleSigner, smime;
- SecureMessage::Format format;
- SecureMessageKeyList to;
- SecureMessageKeyList from;
-
- QByteArray in;
- bool success;
- SecureMessage::Error errorCode;
- QByteArray detachedSig;
- QString hashName;
- SecureMessageSignatureList signers;
- QString dtext;
-
- QList<int> bytesWrittenArgs;
- SafeTimer readyReadTrigger, bytesWrittenTrigger, finishedTrigger;
-
- Private(SecureMessage *_q) : readyReadTrigger(this), bytesWrittenTrigger(this), finishedTrigger(this)
- {
- q = _q;
- c = 0;
- system = 0;
-
- readyReadTrigger.setSingleShot(true);
- bytesWrittenTrigger.setSingleShot(true);
- finishedTrigger.setSingleShot(true);
- connect(&readyReadTrigger, SIGNAL(timeout()), SLOT(t_readyRead()));
- connect(&bytesWrittenTrigger, SIGNAL(timeout()), SLOT(t_bytesWritten()));
- connect(&finishedTrigger, SIGNAL(timeout()), SLOT(t_finished()));
-
- reset(ResetAll);
- }
-
- void init()
- {
- connect(c, SIGNAL(updated()), SLOT(updated()));
- }
-
- void reset(ResetMode mode)
- {
- if(c)
- c->reset();
-
- bytesWrittenArgs.clear();
- readyReadTrigger.stop();
- bytesWrittenTrigger.stop();
- finishedTrigger.stop();
-
- if(mode >= ResetSessionAndData)
- {
- in.clear();
- success = false;
- errorCode = SecureMessage::ErrorUnknown;
- detachedSig.clear();
- hashName = QString();
- signers.clear();
- }
-
- if(mode >= ResetAll)
- {
- bundleSigner = true;
- format = SecureMessage::Binary;
- to.clear();
- from.clear();
- }
- }
+ SecureMessage *q;
+ MessageContext *c;
+ SecureMessageSystem *system;
+
+ bool bundleSigner, smime;
+ SecureMessage::Format format;
+ SecureMessageKeyList to;
+ SecureMessageKeyList from;
+
+ QByteArray in;
+ bool success;
+ SecureMessage::Error errorCode;
+ QByteArray detachedSig;
+ QString hashName;
+ SecureMessageSignatureList signers;
+ QString dtext;
+
+ QList<int> bytesWrittenArgs;
+ SafeTimer readyReadTrigger, bytesWrittenTrigger, finishedTrigger;
+
+ Private(SecureMessage *_q) : readyReadTrigger(this), bytesWrittenTrigger(this), finishedTrigger(this)
+ {
+ q = _q;
+ c = 0;
+ system = 0;
+
+ readyReadTrigger.setSingleShot(true);
+ bytesWrittenTrigger.setSingleShot(true);
+ finishedTrigger.setSingleShot(true);
+ connect(&readyReadTrigger, SIGNAL(timeout()), SLOT(t_readyRead()));
+ connect(&bytesWrittenTrigger, SIGNAL(timeout()), SLOT(t_bytesWritten()));
+ connect(&finishedTrigger, SIGNAL(timeout()), SLOT(t_finished()));
+
+ reset(ResetAll);
+ }
+
+ void init()
+ {
+ connect(c, SIGNAL(updated()), SLOT(updated()));
+ }
+
+ void reset(ResetMode mode)
+ {
+ if (c) {
+ c->reset();
+ }
+
+ bytesWrittenArgs.clear();
+ readyReadTrigger.stop();
+ bytesWrittenTrigger.stop();
+ finishedTrigger.stop();
+
+ if (mode >= ResetSessionAndData) {
+ in.clear();
+ success = false;
+ errorCode = SecureMessage::ErrorUnknown;
+ detachedSig.clear();
+ hashName = QString();
+ signers.clear();
+ }
+
+ if (mode >= ResetAll) {
+ bundleSigner = true;
+ format = SecureMessage::Binary;
+ to.clear();
+ from.clear();
+ }
+ }
public slots:
- void updated()
- {
- bool sig_read = false;
- bool sig_written = false;
- bool sig_done = false;
- int written = 0;
- {
- QByteArray a = c->read();
- if(!a.isEmpty())
- {
- sig_read = true;
- in.append(a);
- }
-
- int x = c->written();
- if(x > 0)
- {
- sig_written = true;
- written = x;
- }
- }
-
- if(c->finished())
- {
- sig_done = true;
-
- success = c->success();
- errorCode = c->errorCode();
- dtext = c->diagnosticText();
- if(success)
- {
- detachedSig = c->signature();
- hashName = c->hashName();
- signers = c->signers();
- }
- reset(ResetSession);
- }
-
- if(sig_read)
- readyReadTrigger.start();
- if(sig_written)
- {
- bytesWrittenArgs += written;
- bytesWrittenTrigger.start();
- }
- if(sig_done)
- finishedTrigger.start();
- }
-
- void t_readyRead()
- {
- emit q->readyRead();
- }
-
- void t_bytesWritten()
- {
- emit q->bytesWritten(bytesWrittenArgs.takeFirst());
- }
-
- void t_finished()
- {
- emit q->finished();
- }
+ void updated()
+ {
+ bool sig_read = false;
+ bool sig_written = false;
+ bool sig_done = false;
+ int written = 0;
+ {
+ QByteArray a = c->read();
+ if (!a.isEmpty()) {
+ sig_read = true;
+ in.append(a);
+ }
+
+ int x = c->written();
+ if (x > 0) {
+ sig_written = true;
+ written = x;
+ }
+ }
+
+ if (c->finished()) {
+ sig_done = true;
+
+ success = c->success();
+ errorCode = c->errorCode();
+ dtext = c->diagnosticText();
+ if (success) {
+ detachedSig = c->signature();
+ hashName = c->hashName();
+ signers = c->signers();
+ }
+ reset(ResetSession);
+ }
+
+ if (sig_read) {
+ readyReadTrigger.start();
+ }
+ if (sig_written) {
+ bytesWrittenArgs += written;
+ bytesWrittenTrigger.start();
+ }
+ if (sig_done) {
+ finishedTrigger.start();
+ }
+ }
+
+ void t_readyRead()
+ {
+ emit q->readyRead();
+ }
+
+ void t_bytesWritten()
+ {
+ emit q->bytesWritten(bytesWrittenArgs.takeFirst());
+ }
+
+ void t_finished()
+ {
+ emit q->finished();
+ }
};
SecureMessage::SecureMessage(SecureMessageSystem *system)
{
- d = new Private(this);
- d->system = system;
- d->c = static_cast<SMSContext *>(d->system->context())->createMessage();
- change(d->c);
- d->init();
+ d = new Private(this);
+ d->system = system;
+ d->c = static_cast<SMSContext *>(d->system->context())->createMessage();
+ change(d->c);
+ d->init();
}
SecureMessage::~SecureMessage()
{
- delete d;
+ delete d;
}
SecureMessage::Type SecureMessage::type() const
{
- return d->c->type();
+ return d->c->type();
}
bool SecureMessage::canSignMultiple() const
{
- return d->c->canSignMultiple();
+ return d->c->canSignMultiple();
}
bool SecureMessage::canClearsign() const
{
- return (type() == OpenPGP);
+ return (type() == OpenPGP);
}
bool SecureMessage::canSignAndEncrypt() const
{
- return (type() == OpenPGP);
+ return (type() == OpenPGP);
}
void SecureMessage::reset()
{
- d->reset(ResetAll);
+ d->reset(ResetAll);
}
bool SecureMessage::bundleSignerEnabled() const
{
- return d->bundleSigner;
+ return d->bundleSigner;
}
bool SecureMessage::smimeAttributesEnabled() const
{
- return d->smime;
+ return d->smime;
}
SecureMessage::Format SecureMessage::format() const
{
- return d->format;
+ return d->format;
}
SecureMessageKeyList SecureMessage::recipientKeys() const
{
- return d->to;
+ return d->to;
}
SecureMessageKeyList SecureMessage::signerKeys() const
{
- return d->from;
+ return d->from;
}
void SecureMessage::setBundleSignerEnabled(bool b)
{
- d->bundleSigner = b;
+ d->bundleSigner = b;
}
void SecureMessage::setSMIMEAttributesEnabled(bool b)
{
- d->smime = b;
+ d->smime = b;
}
void SecureMessage::setFormat(Format f)
{
- d->format = f;
+ d->format = f;
}
void SecureMessage::setRecipient(const SecureMessageKey &key)
{
- d->to = SecureMessageKeyList() << key;
+ d->to = SecureMessageKeyList() << key;
}
void SecureMessage::setRecipients(const SecureMessageKeyList &keys)
{
- d->to = keys;
+ d->to = keys;
}
void SecureMessage::setSigner(const SecureMessageKey &key)
{
- d->from = SecureMessageKeyList() << key;
+ d->from = SecureMessageKeyList() << key;
}
void SecureMessage::setSigners(const SecureMessageKeyList &keys)
{
- d->from = keys;
+ d->from = keys;
}
void SecureMessage::startEncrypt()
{
- d->reset(ResetSessionAndData);
- d->c->setupEncrypt(d->to);
- d->c->start(d->format, MessageContext::Encrypt);
+ d->reset(ResetSessionAndData);
+ d->c->setupEncrypt(d->to);
+ d->c->start(d->format, MessageContext::Encrypt);
}
void SecureMessage::startDecrypt()
{
- d->reset(ResetSessionAndData);
- d->c->start(d->format, MessageContext::Decrypt);
+ d->reset(ResetSessionAndData);
+ d->c->start(d->format, MessageContext::Decrypt);
}
void SecureMessage::startSign(SignMode m)
{
- d->reset(ResetSessionAndData);
- d->c->setupSign(d->from, m, d->bundleSigner, d->smime);
- d->c->start(d->format, MessageContext::Sign);
+ d->reset(ResetSessionAndData);
+ d->c->setupSign(d->from, m, d->bundleSigner, d->smime);
+ d->c->start(d->format, MessageContext::Sign);
}
void SecureMessage::startVerify(const QByteArray &sig)
{
- d->reset(ResetSessionAndData);
- if(!sig.isEmpty())
- d->c->setupVerify(sig);
- d->c->start(d->format, MessageContext::Verify);
+ d->reset(ResetSessionAndData);
+ if (!sig.isEmpty()) {
+ d->c->setupVerify(sig);
+ }
+ d->c->start(d->format, MessageContext::Verify);
}
void SecureMessage::startSignAndEncrypt()
{
- d->reset(ResetSessionAndData);
- d->c->setupEncrypt(d->to);
- d->c->setupSign(d->from, Message, d->bundleSigner, d->smime);
- d->c->start(d->format, MessageContext::SignAndEncrypt);
+ d->reset(ResetSessionAndData);
+ d->c->setupEncrypt(d->to);
+ d->c->setupSign(d->from, Message, d->bundleSigner, d->smime);
+ d->c->start(d->format, MessageContext::SignAndEncrypt);
}
void SecureMessage::update(const QByteArray &in)
{
- d->c->update(in);
+ d->c->update(in);
}
QByteArray SecureMessage::read()
{
- QByteArray a = d->in;
- d->in.clear();
- return a;
+ QByteArray a = d->in;
+ d->in.clear();
+ return a;
}
int SecureMessage::bytesAvailable() const
{
- return d->in.size();
+ return d->in.size();
}
void SecureMessage::end()
{
- d->c->end();
+ d->c->end();
}
bool SecureMessage::waitForFinished(int msecs)
{
- d->c->waitForFinished(msecs);
- d->updated();
- return d->success;
+ d->c->waitForFinished(msecs);
+ d->updated();
+ return d->success;
}
bool SecureMessage::success() const
{
- return d->success;
+ return d->success;
}
SecureMessage::Error SecureMessage::errorCode() const
{
- return d->errorCode;
+ return d->errorCode;
}
QByteArray SecureMessage::signature() const
{
- return d->detachedSig;
+ return d->detachedSig;
}
QString SecureMessage::hashName() const
{
- return d->hashName;
+ return d->hashName;
}
bool SecureMessage::wasSigned() const
{
- return !d->signers.isEmpty();
+ return !d->signers.isEmpty();
}
bool SecureMessage::verifySuccess() const
{
- // if we're not done or there were no signers, then return false
- if(!d->success || d->signers.isEmpty())
- return false;
+ // if we're not done or there were no signers, then return false
+ if (!d->success || d->signers.isEmpty()) {
+ return false;
+ }
- // make sure all signers have a valid signature
- for(int n = 0; n < d->signers.count(); ++n)
- {
- if(d->signers[n].identityResult() != SecureMessageSignature::Valid)
- return false;
- }
- return true;
+ // make sure all signers have a valid signature
+ for (int n = 0; n < d->signers.count(); ++n) {
+ if (d->signers[n].identityResult() != SecureMessageSignature::Valid) {
+ return false;
+ }
+ }
+ return true;
}
SecureMessageSignature SecureMessage::signer() const
{
- if(d->signers.isEmpty())
- return SecureMessageSignature();
+ if (d->signers.isEmpty()) {
+ return SecureMessageSignature();
+ }
- return d->signers.first();
+ return d->signers.first();
}
SecureMessageSignatureList SecureMessage::signers() const
{
- return d->signers;
+ return d->signers;
}
QString SecureMessage::diagnosticText() const
{
- return d->dtext;
+ return d->dtext;
}
//----------------------------------------------------------------------------
// SecureMessageSystem
//----------------------------------------------------------------------------
SecureMessageSystem::SecureMessageSystem(QObject *parent, const QString &type, const QString &provider)
-:QObject(parent), Algorithm(type, provider)
+ : QObject(parent), Algorithm(type, provider)
{
}
SecureMessageSystem::~SecureMessageSystem()
{
}
//----------------------------------------------------------------------------
// OpenPGP
//----------------------------------------------------------------------------
OpenPGP::OpenPGP(QObject *parent, const QString &provider)
-:SecureMessageSystem(parent, "openpgp", provider)
+ : SecureMessageSystem(parent, "openpgp", provider)
{
}
OpenPGP::~OpenPGP()
{
}
//----------------------------------------------------------------------------
// CMS
//----------------------------------------------------------------------------
class CMS::Private
{
public:
- CertificateCollection trusted, untrusted;
- SecureMessageKeyList privateKeys;
+ CertificateCollection trusted, untrusted;
+ SecureMessageKeyList privateKeys;
};
CMS::CMS(QObject *parent, const QString &provider)
-:SecureMessageSystem(parent, "cms", provider)
+ : SecureMessageSystem(parent, "cms", provider)
{
- d = new Private;
+ d = new Private;
}
CMS::~CMS()
{
- delete d;
+ delete d;
}
CertificateCollection CMS::trustedCertificates() const
{
- return d->trusted;
+ return d->trusted;
}
CertificateCollection CMS::untrustedCertificates() const
{
- return d->untrusted;
+ return d->untrusted;
}
SecureMessageKeyList CMS::privateKeys() const
{
- return d->privateKeys;
+ return d->privateKeys;
}
void CMS::setTrustedCertificates(const CertificateCollection &trusted)
{
- d->trusted = trusted;
- static_cast<SMSContext *>(context())->setTrustedCertificates(trusted);
+ d->trusted = trusted;
+ static_cast<SMSContext *>(context())->setTrustedCertificates(trusted);
}
void CMS::setUntrustedCertificates(const CertificateCollection &untrusted)
{
- d->untrusted = untrusted;
- static_cast<SMSContext *>(context())->setUntrustedCertificates(untrusted);
+ d->untrusted = untrusted;
+ static_cast<SMSContext *>(context())->setUntrustedCertificates(untrusted);
}
void CMS::setPrivateKeys(const SecureMessageKeyList &keys)
{
- d->privateKeys = keys;
- static_cast<SMSContext *>(context())->setPrivateKeys(keys);
+ d->privateKeys = keys;
+ static_cast<SMSContext *>(context())->setPrivateKeys(keys);
}
}
#include "qca_securemessage.moc"
diff --git a/src/qca_systemstore.h b/src/qca_systemstore.h
index cdf15659..80d49c24 100644
--- a/src/qca_systemstore.h
+++ b/src/qca_systemstore.h
@@ -1,36 +1,37 @@
/*
* qca_systemstore.h - Qt Cryptographic Architecture
* Copyright (C) 2004 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#ifndef QCA_SYSTEMSTORE_H
#define QCA_SYSTEMSTORE_H
// NOTE: this API is private to QCA
#include "qca_cert.h"
-namespace QCA {
+namespace QCA
+{
bool qca_have_systemstore();
CertificateCollection qca_get_systemstore(const QString &provider);
}
#endif
diff --git a/src/qca_systemstore_flatfile.cpp b/src/qca_systemstore_flatfile.cpp
index a85d167c..fc25524c 100644
--- a/src/qca_systemstore_flatfile.cpp
+++ b/src/qca_systemstore_flatfile.cpp
@@ -1,38 +1,39 @@
/*
* Copyright (C) 2004,2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_systemstore.h"
#include <QFile>
-namespace QCA {
+namespace QCA
+{
bool qca_have_systemstore()
{
- QFile f(QCA_SYSTEMSTORE_PATH);
- return f.open(QFile::ReadOnly);
+ QFile f(QCA_SYSTEMSTORE_PATH);
+ return f.open(QFile::ReadOnly);
}
CertificateCollection qca_get_systemstore(const QString &provider)
{
- return CertificateCollection::fromFlatTextFile(QCA_SYSTEMSTORE_PATH, 0, provider);
+ return CertificateCollection::fromFlatTextFile(QCA_SYSTEMSTORE_PATH, 0, provider);
}
}
diff --git a/src/qca_systemstore_mac.cpp b/src/qca_systemstore_mac.cpp
index 6190bf9f..77244077 100644
--- a/src/qca_systemstore_mac.cpp
+++ b/src/qca_systemstore_mac.cpp
@@ -1,54 +1,56 @@
/*
* Copyright (C) 2004,2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_systemstore.h"
#include <Security/SecTrust.h>
#include <Security/SecCertificate.h>
-namespace QCA {
+namespace QCA
+{
bool qca_have_systemstore()
{
- return true;
+ return true;
}
CertificateCollection qca_get_systemstore(const QString &provider)
{
- CertificateCollection col;
- CFArrayRef anchors;
- if(SecTrustCopyAnchorCertificates(&anchors) != 0)
- return col;
- for(int n = 0; n < CFArrayGetCount(anchors); ++n)
- {
- SecCertificateRef cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, n);
- CFDataRef derRef = SecCertificateCopyData(cr);
- QByteArray der((const char *)CFDataGetBytePtr(derRef), CFDataGetLength(derRef));
- CFRelease(derRef);
+ CertificateCollection col;
+ CFArrayRef anchors;
+ if (SecTrustCopyAnchorCertificates(&anchors) != 0) {
+ return col;
+ }
+ for (int n = 0; n < CFArrayGetCount(anchors); ++n) {
+ SecCertificateRef cr = (SecCertificateRef)CFArrayGetValueAtIndex(anchors, n);
+ CFDataRef derRef = SecCertificateCopyData(cr);
+ QByteArray der((const char *)CFDataGetBytePtr(derRef), CFDataGetLength(derRef));
+ CFRelease(derRef);
- Certificate cert = Certificate::fromDER(der, 0, provider);
- if(!cert.isNull())
- col.addCertificate(cert);
- }
- CFRelease(anchors);
- return col;
+ Certificate cert = Certificate::fromDER(der, 0, provider);
+ if (!cert.isNull()) {
+ col.addCertificate(cert);
+ }
+ }
+ CFRelease(anchors);
+ return col;
}
}
diff --git a/src/qca_systemstore_win.cpp b/src/qca_systemstore_win.cpp
index b48d8529..8d7a93b3 100644
--- a/src/qca_systemstore_win.cpp
+++ b/src/qca_systemstore_win.cpp
@@ -1,73 +1,77 @@
/*
* Copyright (C) 2004,2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// need to define this immediately
#define _WIN32_WINNT 0x400
#include "qca_systemstore.h"
#include <windows.h>
#include <wincrypt.h>
-namespace QCA {
+namespace QCA
+{
bool qca_have_systemstore()
{
- bool ok = false;
- HCERTSTORE hSystemStore;
- hSystemStore = CertOpenSystemStoreA(0, "ROOT");
- if(hSystemStore)
- ok = true;
- CertCloseStore(hSystemStore, 0);
- return ok;
+ bool ok = false;
+ HCERTSTORE hSystemStore;
+ hSystemStore = CertOpenSystemStoreA(0, "ROOT");
+ if (hSystemStore) {
+ ok = true;
+ }
+ CertCloseStore(hSystemStore, 0);
+ return ok;
}
CertificateCollection qca_get_systemstore(const QString &provider)
{
- CertificateCollection col;
- HCERTSTORE hSystemStore;
- hSystemStore = CertOpenSystemStoreA(0, "ROOT");
- if(!hSystemStore)
- return col;
- PCCERT_CONTEXT pc = NULL;
- while(1)
- {
- pc = CertFindCertificateInStore(
- hSystemStore,
- X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
- 0,
- CERT_FIND_ANY,
- NULL,
- pc);
- if(!pc)
- break;
- int size = pc->cbCertEncoded;
- QByteArray der(size, 0);
- memcpy(der.data(), pc->pbCertEncoded, size);
+ CertificateCollection col;
+ HCERTSTORE hSystemStore;
+ hSystemStore = CertOpenSystemStoreA(0, "ROOT");
+ if (!hSystemStore) {
+ return col;
+ }
+ PCCERT_CONTEXT pc = NULL;
+ while (1) {
+ pc = CertFindCertificateInStore(
+ hSystemStore,
+ X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
+ 0,
+ CERT_FIND_ANY,
+ NULL,
+ pc);
+ if (!pc) {
+ break;
+ }
+ int size = pc->cbCertEncoded;
+ QByteArray der(size, 0);
+ memcpy(der.data(), pc->pbCertEncoded, size);
- Certificate cert = Certificate::fromDER(der, 0, provider);
- if(!cert.isNull())
- col.addCertificate(cert);
- }
- CertCloseStore(hSystemStore, 0);
- return col;
+ Certificate cert = Certificate::fromDER(der, 0, provider);
+ if (!cert.isNull()) {
+ col.addCertificate(cert);
+ }
+ }
+ CertCloseStore(hSystemStore, 0);
+ return col;
}
}
diff --git a/src/qca_textfilter.cpp b/src/qca_textfilter.cpp
index 3baf511b..00888c11 100644
--- a/src/qca_textfilter.cpp
+++ b/src/qca_textfilter.cpp
@@ -1,517 +1,504 @@
/*
* Copyright (C) 2003-2005 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_textfilter.h"
-namespace QCA {
+namespace QCA
+{
//----------------------------------------------------------------------------
// TextFilter
//----------------------------------------------------------------------------
TextFilter::TextFilter(Direction dir)
{
- setup(dir);
+ setup(dir);
}
void TextFilter::setup(Direction dir)
{
- _dir = dir;
+ _dir = dir;
}
Direction TextFilter::direction() const
{
- return _dir;
+ return _dir;
}
MemoryRegion TextFilter::encode(const MemoryRegion &a)
{
- setup(Encode);
- return process(a);
+ setup(Encode);
+ return process(a);
}
MemoryRegion TextFilter::decode(const MemoryRegion &a)
{
- setup(Decode);
- return process(a);
+ setup(Decode);
+ return process(a);
}
QString TextFilter::arrayToString(const MemoryRegion &a)
{
- return QString::fromLatin1(encode(a).toByteArray());
+ return QString::fromLatin1(encode(a).toByteArray());
}
MemoryRegion TextFilter::stringToArray(const QString &s)
{
- if(s.isEmpty())
- return MemoryRegion();
- return decode(s.toLatin1());
+ if (s.isEmpty()) {
+ return MemoryRegion();
+ }
+ return decode(s.toLatin1());
}
QString TextFilter::encodeString(const QString &s)
{
- return arrayToString(s.toUtf8());
+ return arrayToString(s.toUtf8());
}
QString TextFilter::decodeString(const QString &s)
{
- return QString::fromUtf8(stringToArray(s).toByteArray());
+ return QString::fromUtf8(stringToArray(s).toByteArray());
}
//----------------------------------------------------------------------------
// Hex
//----------------------------------------------------------------------------
static int enhex(uchar c)
{
- if(c < 10)
- return c + '0';
- else if(c < 16)
- return c - 10 + 'a';
- else
- return -1;
+ if (c < 10) {
+ return c + '0';
+ } else if (c < 16) {
+ return c - 10 + 'a';
+ } else {
+ return -1;
+ }
}
static int dehex(char c)
{
- if(c >= 'a' && c <= 'f')
- return c - 'a' + 10;
- else if(c >= 'A' && c <= 'F')
- return c - 'A' + 10;
- else if(c >= '0' && c <= '9')
- return c - '0';
- else
- return -1;
+ if (c >= 'a' && c <= 'f') {
+ return c - 'a' + 10;
+ } else if (c >= 'A' && c <= 'F') {
+ return c - 'A' + 10;
+ } else if (c >= '0' && c <= '9') {
+ return c - '0';
+ } else {
+ return -1;
+ }
}
Hex::Hex(Direction dir)
-:TextFilter(dir)
+ : TextFilter(dir)
{
- clear();
+ clear();
}
void Hex::clear()
{
- partial = false;
- _ok = true;
+ partial = false;
+ _ok = true;
}
MemoryRegion Hex::update(const MemoryRegion &m)
{
- QByteArray a = m.toByteArray();
- if(_dir == Encode)
- {
- QByteArray out(a.size() * 2, 0);
- int at = 0;
- int c;
- for(int n = 0; n < (int)a.size(); ++n)
- {
- uchar lo = (uchar)a[n] & 0x0f;
- uchar hi = (uchar)a[n] >> 4;
- c = enhex(hi);
- if(c == -1)
- {
- _ok = false;
- break;
- }
- out[at++] = (char)c;
- c = enhex(lo);
- if(c == -1)
- {
- _ok = false;
- break;
- }
- out[at++] = (char)c;
- }
- if(!_ok)
- return MemoryRegion();
-
- return out;
- }
- else
- {
- uchar lo = 0;
- uchar hi = 0;
- bool flag = false;
- if(partial)
- {
- hi = val;
- flag = true;
- }
-
- QByteArray out(a.size() / 2, 0);
- int at = 0;
- int c;
- for(int n = 0; n < (int)a.size(); ++n)
- {
- c = dehex((char)a[n]);
- if(c == -1)
- {
- _ok = false;
- break;
- }
- if(flag)
- {
- lo = (uchar)c;
- uchar full = ((hi & 0x0f) << 4) + (lo & 0x0f);
- out[at++] = full;
- flag = false;
- }
- else
- {
- hi = (uchar)c;
- flag = true;
- }
- }
- if(!_ok)
- return MemoryRegion();
-
- if(flag)
- {
- val = hi;
- partial = true;
- }
- return out;
- }
+ QByteArray a = m.toByteArray();
+ if (_dir == Encode) {
+ QByteArray out(a.size() * 2, 0);
+ int at = 0;
+ int c;
+ for (int n = 0; n < (int)a.size(); ++n) {
+ uchar lo = (uchar)a[n] & 0x0f;
+ uchar hi = (uchar)a[n] >> 4;
+ c = enhex(hi);
+ if (c == -1) {
+ _ok = false;
+ break;
+ }
+ out[at++] = (char)c;
+ c = enhex(lo);
+ if (c == -1) {
+ _ok = false;
+ break;
+ }
+ out[at++] = (char)c;
+ }
+ if (!_ok) {
+ return MemoryRegion();
+ }
+
+ return out;
+ } else {
+ uchar lo = 0;
+ uchar hi = 0;
+ bool flag = false;
+ if (partial) {
+ hi = val;
+ flag = true;
+ }
+
+ QByteArray out(a.size() / 2, 0);
+ int at = 0;
+ int c;
+ for (int n = 0; n < (int)a.size(); ++n) {
+ c = dehex((char)a[n]);
+ if (c == -1) {
+ _ok = false;
+ break;
+ }
+ if (flag) {
+ lo = (uchar)c;
+ uchar full = ((hi & 0x0f) << 4) + (lo & 0x0f);
+ out[at++] = full;
+ flag = false;
+ } else {
+ hi = (uchar)c;
+ flag = true;
+ }
+ }
+ if (!_ok) {
+ return MemoryRegion();
+ }
+
+ if (flag) {
+ val = hi;
+ partial = true;
+ }
+ return out;
+ }
}
MemoryRegion Hex::final()
{
- if(partial)
- _ok = false;
- return MemoryRegion();
+ if (partial) {
+ _ok = false;
+ }
+ return MemoryRegion();
}
bool Hex::ok() const
{
- return _ok;
+ return _ok;
}
//----------------------------------------------------------------------------
// Base64
//----------------------------------------------------------------------------
Base64::Base64(Direction dir)
-:TextFilter(dir)
+ : TextFilter(dir)
{
- _lb_enabled = false;
- _lb_column = 76;
+ _lb_enabled = false;
+ _lb_column = 76;
}
void Base64::clear()
{
- partial.resize(0);
- _ok = true;
- col = 0;
+ partial.resize(0);
+ _ok = true;
+ col = 0;
}
bool Base64::lineBreaksEnabled() const
{
- return _lb_enabled;
+ return _lb_enabled;
}
int Base64::lineBreaksColumn() const
{
- return _lb_column;
+ return _lb_column;
}
void Base64::setLineBreaksEnabled(bool b)
{
- _lb_enabled = b;
+ _lb_enabled = b;
}
void Base64::setLineBreaksColumn(int column)
{
- if(column > 0)
- _lb_column = column;
- else
- _lb_column = 76;
+ if (column > 0) {
+ _lb_column = column;
+ } else {
+ _lb_column = 76;
+ }
}
static QByteArray b64encode(const QByteArray &s)
{
- int i;
- int len = s.size();
- static char tbl[] =
- "ABCDEFGH"
- "IJKLMNOP"
- "QRSTUVWX"
- "YZabcdef"
- "ghijklmn"
- "opqrstuv"
- "wxyz0123"
- "456789+/"
- "=";
- int a, b, c;
-
- QByteArray p((len + 2) / 3 * 4, 0);
- int at = 0;
- for(i = 0; i < len; i += 3)
- {
- a = ((unsigned char)s[i] & 3) << 4;
- if(i + 1 < len)
- {
- a += (unsigned char)s[i + 1] >> 4;
- b = ((unsigned char)s[i + 1] & 0xf) << 2;
- if(i + 2 < len)
- {
- b += (unsigned char)s[i + 2] >> 6;
- c = (unsigned char)s[i + 2] & 0x3f;
- }
- else
- c = 64;
- }
- else
- b = c = 64;
-
- p[at++] = tbl[(unsigned char)s[i] >> 2];
- p[at++] = tbl[a];
- p[at++] = tbl[b];
- p[at++] = tbl[c];
- }
- return p;
+ int i;
+ int len = s.size();
+ static char tbl[] =
+ "ABCDEFGH"
+ "IJKLMNOP"
+ "QRSTUVWX"
+ "YZabcdef"
+ "ghijklmn"
+ "opqrstuv"
+ "wxyz0123"
+ "456789+/"
+ "=";
+ int a, b, c;
+
+ QByteArray p((len + 2) / 3 * 4, 0);
+ int at = 0;
+ for (i = 0; i < len; i += 3) {
+ a = ((unsigned char)s[i] & 3) << 4;
+ if (i + 1 < len) {
+ a += (unsigned char)s[i + 1] >> 4;
+ b = ((unsigned char)s[i + 1] & 0xf) << 2;
+ if (i + 2 < len) {
+ b += (unsigned char)s[i + 2] >> 6;
+ c = (unsigned char)s[i + 2] & 0x3f;
+ } else {
+ c = 64;
+ }
+ } else {
+ b = c = 64;
+ }
+
+ p[at++] = tbl[(unsigned char)s[i] >> 2];
+ p[at++] = tbl[a];
+ p[at++] = tbl[b];
+ p[at++] = tbl[c];
+ }
+ return p;
}
static QByteArray b64decode(const QByteArray &s, bool *ok)
{
- // -1 specifies invalid
- // 64 specifies eof
- // everything else specifies data
-
- static signed char tbl[] =
- {
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,
- 52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,
- 15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,
- -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
- 41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
- };
-
- // return value
- QByteArray p;
- *ok = true;
-
- // this should be a multiple of 4
- int len = s.size();
- if(len % 4)
- {
- *ok = false;
- return p;
- }
-
- p.resize(len / 4 * 3);
-
- int i;
- int at = 0;
-
- int a, b, c, d;
- c = d = 0;
-
- for(i = 0; i < len; i += 4)
- {
- a = tbl[(int)s[i]];
- b = tbl[(int)s[i + 1]];
- c = tbl[(int)s[i + 2]];
- d = tbl[(int)s[i + 3]];
- if((a == 64 || b == 64) || (a < 0 || b < 0 || c < 0 || d < 0))
- {
- p.resize(0);
- *ok = false;
- return p;
- }
- p[at++] = ((a & 0x3F) << 2) | ((b >> 4) & 0x03);
- p[at++] = ((b & 0x0F) << 4) | ((c >> 2) & 0x0F);
- p[at++] = ((c & 0x03) << 6) | ((d >> 0) & 0x3F);
- }
-
- if(c & 64)
- p.resize(at - 2);
- else if(d & 64)
- p.resize(at - 1);
-
- return p;
+ // -1 specifies invalid
+ // 64 specifies eof
+ // everything else specifies data
+
+ static signed char tbl[] = {
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
+ 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, 64, -1, -1,
+ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
+ 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
+ -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
+ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
+ };
+
+ // return value
+ QByteArray p;
+ *ok = true;
+
+ // this should be a multiple of 4
+ int len = s.size();
+ if (len % 4) {
+ *ok = false;
+ return p;
+ }
+
+ p.resize(len / 4 * 3);
+
+ int i;
+ int at = 0;
+
+ int a, b, c, d;
+ c = d = 0;
+
+ for (i = 0; i < len; i += 4) {
+ a = tbl[(int)s[i]];
+ b = tbl[(int)s[i + 1]];
+ c = tbl[(int)s[i + 2]];
+ d = tbl[(int)s[i + 3]];
+ if ((a == 64 || b == 64) || (a < 0 || b < 0 || c < 0 || d < 0)) {
+ p.resize(0);
+ *ok = false;
+ return p;
+ }
+ p[at++] = ((a & 0x3F) << 2) | ((b >> 4) & 0x03);
+ p[at++] = ((b & 0x0F) << 4) | ((c >> 2) & 0x0F);
+ p[at++] = ((c & 0x03) << 6) | ((d >> 0) & 0x3F);
+ }
+
+ if (c & 64) {
+ p.resize(at - 2);
+ } else if (d & 64) {
+ p.resize(at - 1);
+ }
+
+ return p;
}
static int findLF(const QByteArray &in, int offset)
{
- for(int n = offset; n < in.size(); ++n)
- {
- if(in[n] == '\n')
- return n;
- }
- return -1;
+ for (int n = offset; n < in.size(); ++n) {
+ if (in[n] == '\n') {
+ return n;
+ }
+ }
+ return -1;
}
static QByteArray insert_linebreaks(const QByteArray &s, int *col, int lfAt)
{
- QByteArray out = s;
+ QByteArray out = s;
- int needed = (out.size() + *col) / lfAt; // how many newlines needed?
- if(needed > 0)
- {
- int firstlen = lfAt - *col; // length of first chunk
- int at = firstlen + (lfAt * (needed - 1)); // position of last newline
- int lastlen = out.size() - at; // length of last chunk
+ int needed = (out.size() + *col) / lfAt; // how many newlines needed?
+ if (needed > 0) {
+ int firstlen = lfAt - *col; // length of first chunk
+ int at = firstlen + (lfAt * (needed - 1)); // position of last newline
+ int lastlen = out.size() - at; // length of last chunk
- //printf("size=%d,needed=%d,firstlen=%d,at=%d,lastlen=%d\n", out.size(), needed, firstlen, at, lastlen);
+ //printf("size=%d,needed=%d,firstlen=%d,at=%d,lastlen=%d\n", out.size(), needed, firstlen, at, lastlen);
- // make room
- out.resize(out.size() + needed);
+ // make room
+ out.resize(out.size() + needed);
- // move backwards
- for(int n = 0; n < needed; ++n)
- {
- char *p = out.data() + at;
- int len;
- if(n == 0)
- len = lastlen;
- else
- len = lfAt;
- memmove(p + needed - n, p, len);
- p[needed - n - 1] = '\n';
- at -= lfAt;
- }
+ // move backwards
+ for (int n = 0; n < needed; ++n) {
+ char *p = out.data() + at;
+ int len;
+ if (n == 0) {
+ len = lastlen;
+ } else {
+ len = lfAt;
+ }
+ memmove(p + needed - n, p, len);
+ p[needed - n - 1] = '\n';
+ at -= lfAt;
+ }
- *col = lastlen;
- }
- else
- *col += out.size();
+ *col = lastlen;
+ } else {
+ *col += out.size();
+ }
- return out;
+ return out;
}
static QByteArray remove_linebreaks(const QByteArray &s)
{
- QByteArray out = s;
-
- int removed = 0;
- int at = findLF(out, 0);
- while(at != -1)
- {
- int next = findLF(out, at + 1);
- int len;
- if(next != -1)
- len = next - at;
- else
- len = out.size() - at;
-
- if(len > 1)
- {
- char *p = out.data() + at;
- memmove(p - removed, p + 1, len - 1);
- }
- ++removed;
- at = next;
- }
- out.resize(out.size() - removed);
-
- return out;
+ QByteArray out = s;
+
+ int removed = 0;
+ int at = findLF(out, 0);
+ while (at != -1) {
+ int next = findLF(out, at + 1);
+ int len;
+ if (next != -1) {
+ len = next - at;
+ } else {
+ len = out.size() - at;
+ }
+
+ if (len > 1) {
+ char *p = out.data() + at;
+ memmove(p - removed, p + 1, len - 1);
+ }
+ ++removed;
+ at = next;
+ }
+ out.resize(out.size() - removed);
+
+ return out;
}
static void appendArray(QByteArray *a, const QByteArray &b)
{
- a->append(b);
+ a->append(b);
}
MemoryRegion Base64::update(const MemoryRegion &m)
{
- QByteArray in;
- if(_dir == Decode && _lb_enabled)
- in = remove_linebreaks(m.toByteArray());
- else
- in = m.toByteArray();
-
- if(in.isEmpty())
- return MemoryRegion();
-
- int chunk;
- if(_dir == Encode)
- chunk = 3;
- else
- chunk = 4;
-
- int size = partial.size() + in.size();
- if(size < chunk)
- {
- appendArray(&partial, in);
- return MemoryRegion();
- }
-
- int eat = size % chunk;
-
- // s = partial + a - eat
- QByteArray s(partial.size() + in.size() - eat, 0);
- memcpy(s.data(), partial.data(), partial.size());
- memcpy(s.data() + partial.size(), in.data(), in.size() - eat);
-
- partial.resize(eat);
- memcpy(partial.data(), in.data() + in.size() - eat, eat);
-
- if(_dir == Encode)
- {
- if(_lb_enabled)
- return insert_linebreaks(b64encode(s), &col, _lb_column);
- else
- return b64encode(s);
- }
- else
- {
- bool ok;
- QByteArray out = b64decode(s, &ok);
- if(!ok)
- _ok = false;
- return out;
- }
+ QByteArray in;
+ if (_dir == Decode && _lb_enabled) {
+ in = remove_linebreaks(m.toByteArray());
+ } else {
+ in = m.toByteArray();
+ }
+
+ if (in.isEmpty()) {
+ return MemoryRegion();
+ }
+
+ int chunk;
+ if (_dir == Encode) {
+ chunk = 3;
+ } else {
+ chunk = 4;
+ }
+
+ int size = partial.size() + in.size();
+ if (size < chunk) {
+ appendArray(&partial, in);
+ return MemoryRegion();
+ }
+
+ int eat = size % chunk;
+
+ // s = partial + a - eat
+ QByteArray s(partial.size() + in.size() - eat, 0);
+ memcpy(s.data(), partial.data(), partial.size());
+ memcpy(s.data() + partial.size(), in.data(), in.size() - eat);
+
+ partial.resize(eat);
+ memcpy(partial.data(), in.data() + in.size() - eat, eat);
+
+ if (_dir == Encode) {
+ if (_lb_enabled) {
+ return insert_linebreaks(b64encode(s), &col, _lb_column);
+ } else {
+ return b64encode(s);
+ }
+ } else {
+ bool ok;
+ QByteArray out = b64decode(s, &ok);
+ if (!ok) {
+ _ok = false;
+ }
+ return out;
+ }
}
MemoryRegion Base64::final()
{
- if(_dir == Encode)
- {
- if(_lb_enabled)
- return insert_linebreaks(b64encode(partial), &col, _lb_column);
- else
- return b64encode(partial);
- }
- else
- {
- bool ok;
- QByteArray out = b64decode(partial, &ok);
- if(!ok)
- _ok = false;
- return out;
- }
+ if (_dir == Encode) {
+ if (_lb_enabled) {
+ return insert_linebreaks(b64encode(partial), &col, _lb_column);
+ } else {
+ return b64encode(partial);
+ }
+ } else {
+ bool ok;
+ QByteArray out = b64decode(partial, &ok);
+ if (!ok) {
+ _ok = false;
+ }
+ return out;
+ }
}
bool Base64::ok() const
{
- return _ok;
+ return _ok;
}
}
diff --git a/src/qca_tools.cpp b/src/qca_tools.cpp
index cef2b790..27d7c7ff 100644
--- a/src/qca_tools.cpp
+++ b/src/qca_tools.cpp
@@ -1,1001 +1,961 @@
/*
* 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
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_tools.h"
#include "qdebug.h"
#ifdef Q_OS_UNIX
# include <stdlib.h>
# include <sys/mman.h>
#endif
#include "botantools/botantools.h"
-namespace QCA {
+namespace QCA
+{
static bool can_lock()
{
#ifdef Q_OS_UNIX
- bool ok = false;
+ bool ok = false;
#ifdef MLOCK_NOT_VOID_PTR
# define MLOCK_TYPE char *
# define MLOCK_TYPE_CAST (MLOCK_TYPE)
#else
# define MLOCK_TYPE void *
# define MLOCK_TYPE_CAST
#endif
- MLOCK_TYPE d = MLOCK_TYPE_CAST malloc(256);
- if(mlock(d, 256) == 0)
- {
- munlock(d, 256);
- ok = true;
- }
- free(d);
- return ok;
+ MLOCK_TYPE d = MLOCK_TYPE_CAST malloc(256);
+ if (mlock(d, 256) == 0) {
+ munlock(d, 256);
+ ok = true;
+ }
+ free(d);
+ return ok;
#else
- return true;
+ return true;
#endif
}
// Botan shouldn't throw any exceptions in our init/deinit.
static Botan::Allocator *alloc = 0;
void botan_throw_abort()
{
- fprintf(stderr, "QCA: Exception from internal Botan\n");
- abort();
+ fprintf(stderr, "QCA: Exception from internal Botan\n");
+ abort();
}
bool botan_init(int prealloc, bool mmap)
{
- // 64k minimum
- if(prealloc < 64)
- prealloc = 64;
-
- bool secmem = false;
-
- try
- {
- Botan::Builtin_Modules modules;
- Botan::Library_State *libstate = new Botan::Library_State(modules.mutex_factory());
- libstate->prealloc_size = prealloc * 1024;
- Botan::set_global_state(libstate);
- Botan::global_state().load(modules);
-
- if(can_lock())
- {
- Botan::global_state().set_default_allocator("locking");
- secmem = true;
- }
- else if(mmap)
- {
- Botan::global_state().set_default_allocator("mmap");
- secmem = true;
- }
- alloc = Botan::Allocator::get(true);
- }
- catch(std::exception &)
- {
- fprintf(stderr, "QCA: Error initializing internal Botan\n");
- abort();
- }
-
- return secmem;
+ // 64k minimum
+ if (prealloc < 64) {
+ prealloc = 64;
+ }
+
+ bool secmem = false;
+
+ try {
+ Botan::Builtin_Modules modules;
+ Botan::Library_State *libstate = new Botan::Library_State(modules.mutex_factory());
+ libstate->prealloc_size = prealloc * 1024;
+ Botan::set_global_state(libstate);
+ Botan::global_state().load(modules);
+
+ if (can_lock()) {
+ Botan::global_state().set_default_allocator("locking");
+ secmem = true;
+ } else if (mmap) {
+ Botan::global_state().set_default_allocator("mmap");
+ secmem = true;
+ }
+ alloc = Botan::Allocator::get(true);
+ } catch (std::exception &) {
+ fprintf(stderr, "QCA: Error initializing internal Botan\n");
+ abort();
+ }
+
+ return secmem;
}
void botan_deinit()
{
- try
- {
- alloc = 0;
- Botan::set_global_state(0);
- }
- catch(std::exception &)
- {
- botan_throw_abort();
- }
+ try {
+ alloc = 0;
+ Botan::set_global_state(0);
+ } catch (std::exception &) {
+ botan_throw_abort();
+ }
}
void *botan_secure_alloc(int bytes)
{
- try
- {
- return alloc->allocate((Botan::u32bit)bytes);
- }
- catch(std::exception &)
- {
- botan_throw_abort();
- }
- return 0; // never get here
+ try {
+ return alloc->allocate((Botan::u32bit)bytes);
+ } catch (std::exception &) {
+ botan_throw_abort();
+ }
+ return 0; // never get here
}
void botan_secure_free(void *p, int bytes)
{
- try
- {
- alloc->deallocate(p, (Botan::u32bit)bytes);
- }
- catch(std::exception &)
- {
- botan_throw_abort();
- }
+ try {
+ alloc->deallocate(p, (Botan::u32bit)bytes);
+ } catch (std::exception &) {
+ botan_throw_abort();
+ }
}
} // end namespace QCA
void *qca_secure_alloc(int bytes)
{
- // allocate enough room to store a size value in front, return a pointer after it
- char *c = (char *)QCA::botan_secure_alloc(bytes + sizeof(int));
- ((int *)c)[0] = bytes + sizeof(int);
- return c + sizeof(int);
+ // allocate enough room to store a size value in front, return a pointer after it
+ char *c = (char *)QCA::botan_secure_alloc(bytes + sizeof(int));
+ ((int *)c)[0] = bytes + sizeof(int);
+ return c + sizeof(int);
}
void qca_secure_free(void *p)
{
- // backtrack to read the size value
- char *c = (char *)p;
- c -= sizeof(int);
- int bytes = ((int *)c)[0];
- QCA::botan_secure_free(c, bytes);
+ // backtrack to read the size value
+ char *c = (char *)p;
+ c -= sizeof(int);
+ int bytes = ((int *)c)[0];
+ QCA::botan_secure_free(c, bytes);
}
void *qca_secure_realloc(void *p, int bytes)
{
- // if null, do a plain alloc (just like how realloc() works)
- if(!p)
- return qca_secure_alloc(bytes);
+ // if null, do a plain alloc (just like how realloc() works)
+ if (!p) {
+ return qca_secure_alloc(bytes);
+ }
- // backtrack to read the size value
- char *c = (char *)p;
- c -= sizeof(int);
- int oldsize = ((int *)c)[0] - sizeof(int);
+ // backtrack to read the size value
+ char *c = (char *)p;
+ c -= sizeof(int);
+ int oldsize = ((int *)c)[0] - sizeof(int);
- // alloc the new chunk
- char *new_p = (char *)qca_secure_alloc(bytes);
- if(!new_p)
- return 0;
+ // alloc the new chunk
+ char *new_p = (char *)qca_secure_alloc(bytes);
+ if (!new_p) {
+ return 0;
+ }
- // move over the memory from the original block
- memmove(new_p, p, qMin(oldsize, bytes));
+ // move over the memory from the original block
+ memmove(new_p, p, qMin(oldsize, bytes));
- // free the original
- qca_secure_free(p);
+ // free the original
+ qca_secure_free(p);
- // done
- return new_p;
+ // done
+ return new_p;
}
-namespace QCA {
+namespace QCA
+{
// secure or non-secure buffer, with trailing 0-byte.
// buffer size of 0 is okay (sbuf/qbuf will be 0).
-struct alloc_info
-{
- bool sec;
- char *data;
- int size;
-
- // internal
- Botan::SecureVector<Botan::byte> *sbuf;
- QByteArray *qbuf;
+struct alloc_info {
+ bool sec;
+ char *data;
+ int size;
+
+ // internal
+ Botan::SecureVector<Botan::byte> *sbuf;
+ QByteArray *qbuf;
};
// note: these functions don't return error if memory allocation/resizing
// fails.. maybe fix this someday?
// ai: uninitialized
// size: >= 0
// note: memory will be initially zero'd out
static bool ai_new(alloc_info *ai, int size, bool sec);
// ai: uninitialized
// from: initialized
static bool ai_copy(alloc_info *ai, const alloc_info *from);
// ai: initialized
// new_size: >= 0
static bool ai_resize(alloc_info *ai, int new_size);
// ai: initialized
static void ai_delete(alloc_info *ai);
bool ai_new(alloc_info *ai, int size, bool sec)
{
- if(size < 0)
- return false;
-
- ai->size = size;
- ai->sec = sec;
-
- if(size == 0)
- {
- ai->sbuf = 0;
- ai->qbuf = 0;
- ai->data = 0;
- return true;
- }
-
- if(sec)
- {
- try
- {
- ai->sbuf = new Botan::SecureVector<Botan::byte>((Botan::u32bit)size + 1);
- }
- catch(std::exception &)
- {
- botan_throw_abort();
- return false; // never get here
- }
-
- (*(ai->sbuf))[size] = 0;
- ai->qbuf = 0;
- Botan::byte *bp = (Botan::byte *)(*(ai->sbuf));
- ai->data = (char *)bp;
- }
- else
- {
- ai->sbuf = 0;
- ai->qbuf = new QByteArray(size, 0);
- ai->data = ai->qbuf->data();
- }
-
- return true;
+ if (size < 0) {
+ return false;
+ }
+
+ ai->size = size;
+ ai->sec = sec;
+
+ if (size == 0) {
+ ai->sbuf = 0;
+ ai->qbuf = 0;
+ ai->data = 0;
+ return true;
+ }
+
+ if (sec) {
+ try {
+ ai->sbuf = new Botan::SecureVector<Botan::byte>((Botan::u32bit)size + 1);
+ } catch (std::exception &) {
+ botan_throw_abort();
+ return false; // never get here
+ }
+
+ (*(ai->sbuf))[size] = 0;
+ ai->qbuf = 0;
+ Botan::byte *bp = (Botan::byte *)(*(ai->sbuf));
+ ai->data = (char *)bp;
+ } else {
+ ai->sbuf = 0;
+ ai->qbuf = new QByteArray(size, 0);
+ ai->data = ai->qbuf->data();
+ }
+
+ return true;
}
bool ai_copy(alloc_info *ai, const alloc_info *from)
{
- ai->size = from->size;
- ai->sec = from->sec;
-
- if(ai->size == 0)
- {
- ai->sbuf = 0;
- ai->qbuf = 0;
- ai->data = 0;
- return true;
- }
-
- if(ai->sec)
- {
- try
- {
- ai->sbuf = new Botan::SecureVector<Botan::byte>(*(from->sbuf));
- }
- catch(std::exception &)
- {
- botan_throw_abort();
- return false; // never get here
- }
-
- ai->qbuf = 0;
- Botan::byte *bp = (Botan::byte *)(*(ai->sbuf));
- ai->data = (char *)bp;
- }
- else
- {
- ai->sbuf = 0;
- ai->qbuf = new QByteArray(*(from->qbuf));
- ai->data = ai->qbuf->data();
- }
-
- return true;
+ ai->size = from->size;
+ ai->sec = from->sec;
+
+ if (ai->size == 0) {
+ ai->sbuf = 0;
+ ai->qbuf = 0;
+ ai->data = 0;
+ return true;
+ }
+
+ if (ai->sec) {
+ try {
+ ai->sbuf = new Botan::SecureVector<Botan::byte>(*(from->sbuf));
+ } catch (std::exception &) {
+ botan_throw_abort();
+ return false; // never get here
+ }
+
+ ai->qbuf = 0;
+ Botan::byte *bp = (Botan::byte *)(*(ai->sbuf));
+ ai->data = (char *)bp;
+ } else {
+ ai->sbuf = 0;
+ ai->qbuf = new QByteArray(*(from->qbuf));
+ ai->data = ai->qbuf->data();
+ }
+
+ return true;
}
bool ai_resize(alloc_info *ai, int new_size)
{
- if(new_size < 0)
- return false;
-
- // new size is empty
- if(new_size == 0)
- {
- // we currently aren't empty
- if(ai->size > 0)
- {
- if(ai->sec)
- {
- delete ai->sbuf;
- ai->sbuf = 0;
- }
- else
- {
- delete ai->qbuf;
- ai->qbuf = 0;
- }
-
- ai->size = 0;
- ai->data = 0;
- }
-
- return true;
- }
-
- if(ai->sec)
- {
- Botan::SecureVector<Botan::byte> *new_buf;
- try
- {
- new_buf = new Botan::SecureVector<Botan::byte>((Botan::u32bit)new_size + 1);
- }
- catch(std::exception &)
- {
- botan_throw_abort();
- return false; // never get here
- }
-
- Botan::byte *new_p = (Botan::byte *)(*new_buf);
- if(ai->size > 0)
- {
- const Botan::byte *old_p = (const Botan::byte *)(*(ai->sbuf));
- memcpy(new_p, old_p, qMin(new_size, ai->size));
- delete ai->sbuf;
- }
- ai->sbuf = new_buf;
- ai->size = new_size;
- (*(ai->sbuf))[new_size] = 0;
- ai->data = (char *)new_p;
- }
- else
- {
- if(ai->size > 0)
- ai->qbuf->resize(new_size);
- else
- ai->qbuf = new QByteArray(new_size, 0);
-
- ai->size = new_size;
- ai->data = ai->qbuf->data();
- }
-
- return true;
+ if (new_size < 0) {
+ return false;
+ }
+
+ // new size is empty
+ if (new_size == 0) {
+ // we currently aren't empty
+ if (ai->size > 0) {
+ if (ai->sec) {
+ delete ai->sbuf;
+ ai->sbuf = 0;
+ } else {
+ delete ai->qbuf;
+ ai->qbuf = 0;
+ }
+
+ ai->size = 0;
+ ai->data = 0;
+ }
+
+ return true;
+ }
+
+ if (ai->sec) {
+ Botan::SecureVector<Botan::byte> *new_buf;
+ try {
+ new_buf = new Botan::SecureVector<Botan::byte>((Botan::u32bit)new_size + 1);
+ } catch (std::exception &) {
+ botan_throw_abort();
+ return false; // never get here
+ }
+
+ Botan::byte *new_p = (Botan::byte *)(*new_buf);
+ if (ai->size > 0) {
+ const Botan::byte *old_p = (const Botan::byte *)(*(ai->sbuf));
+ memcpy(new_p, old_p, qMin(new_size, ai->size));
+ delete ai->sbuf;
+ }
+ ai->sbuf = new_buf;
+ ai->size = new_size;
+ (*(ai->sbuf))[new_size] = 0;
+ ai->data = (char *)new_p;
+ } else {
+ if (ai->size > 0) {
+ ai->qbuf->resize(new_size);
+ } else {
+ ai->qbuf = new QByteArray(new_size, 0);
+ }
+
+ ai->size = new_size;
+ ai->data = ai->qbuf->data();
+ }
+
+ return true;
}
void ai_delete(alloc_info *ai)
{
- if(ai->size > 0)
- {
- if(ai->sec)
- delete ai->sbuf;
- else
- delete ai->qbuf;
- }
+ if (ai->size > 0) {
+ if (ai->sec) {
+ delete ai->sbuf;
+ } else {
+ delete ai->qbuf;
+ }
+ }
}
//----------------------------------------------------------------------------
// MemoryRegion
//----------------------------------------------------------------------------
static char blank[] = "";
class MemoryRegion::Private : public QSharedData
{
public:
- alloc_info ai;
-
- Private(int size, bool sec)
- {
- ai_new(&ai, size, sec);
- }
-
- Private(const QByteArray &from, bool sec)
- {
- ai_new(&ai, from.size(), sec);
- memcpy(ai.data, from.data(), ai.size);
- }
-
- Private(const Private &from) : QSharedData(from)
- {
- ai_copy(&ai, &from.ai);
- }
-
- ~Private()
- {
- ai_delete(&ai);
- }
-
- bool resize(int new_size)
- {
- return ai_resize(&ai, new_size);
- }
-
- void setSecure(bool sec)
- {
- // if same mode, do nothing
- if(ai.sec == sec)
- return;
-
- alloc_info other;
- ai_new(&other, ai.size, sec);
- memcpy(other.data, ai.data, ai.size);
- ai_delete(&ai);
- ai = other;
- }
+ alloc_info ai;
+
+ Private(int size, bool sec)
+ {
+ ai_new(&ai, size, sec);
+ }
+
+ Private(const QByteArray &from, bool sec)
+ {
+ ai_new(&ai, from.size(), sec);
+ memcpy(ai.data, from.data(), ai.size);
+ }
+
+ Private(const Private &from) : QSharedData(from)
+ {
+ ai_copy(&ai, &from.ai);
+ }
+
+ ~Private()
+ {
+ ai_delete(&ai);
+ }
+
+ bool resize(int new_size)
+ {
+ return ai_resize(&ai, new_size);
+ }
+
+ void setSecure(bool sec)
+ {
+ // if same mode, do nothing
+ if (ai.sec == sec) {
+ return;
+ }
+
+ alloc_info other;
+ ai_new(&other, ai.size, sec);
+ memcpy(other.data, ai.data, ai.size);
+ ai_delete(&ai);
+ ai = other;
+ }
};
MemoryRegion::MemoryRegion()
-:_secure(false), d(0)
+ : _secure(false), d(0)
{
}
MemoryRegion::MemoryRegion(const char *str)
-:_secure(false), d(new Private(QByteArray::fromRawData(str, strlen(str)), false))
+ : _secure(false), d(new Private(QByteArray::fromRawData(str, strlen(str)), false))
{
}
MemoryRegion::MemoryRegion(const QByteArray &from)
-:_secure(false), d(new Private(from, false))
+ : _secure(false), d(new Private(from, false))
{
}
MemoryRegion::MemoryRegion(const MemoryRegion &from)
-:_secure(from._secure), d(from.d)
+ : _secure(from._secure), d(from.d)
{
}
MemoryRegion::~MemoryRegion()
{
}
-MemoryRegion & MemoryRegion::operator=(const MemoryRegion &from)
+MemoryRegion &MemoryRegion::operator=(const MemoryRegion &from)
{
- _secure = from._secure;
- d = from.d;
- return *this;
+ _secure = from._secure;
+ d = from.d;
+ return *this;
}
-MemoryRegion & MemoryRegion::operator=(const QByteArray &from)
+MemoryRegion &MemoryRegion::operator=(const QByteArray &from)
{
- set(from, false);
- return *this;
+ set(from, false);
+ return *this;
}
bool MemoryRegion::isNull() const
{
- return (d ? false : true);
+ return (d ? false : true);
}
bool MemoryRegion::isSecure() const
{
- return _secure;
+ return _secure;
}
QByteArray MemoryRegion::toByteArray() const
{
- if(!d)
- return QByteArray();
+ if (!d) {
+ return QByteArray();
+ }
- if(d->ai.sec)
- {
- QByteArray buf(d->ai.size, 0);
- memcpy(buf.data(), d->ai.data, d->ai.size);
- return buf;
- }
- else
- {
- if(d->ai.size > 0)
- return *(d->ai.qbuf);
- else
- return QByteArray((int)0, (char)0);
- }
+ if (d->ai.sec) {
+ QByteArray buf(d->ai.size, 0);
+ memcpy(buf.data(), d->ai.data, d->ai.size);
+ return buf;
+ } else {
+ if (d->ai.size > 0) {
+ return *(d->ai.qbuf);
+ } else {
+ return QByteArray((int)0, (char)0);
+ }
+ }
}
MemoryRegion::MemoryRegion(bool secure)
-:_secure(secure), d(0)
+ : _secure(secure), d(0)
{
}
MemoryRegion::MemoryRegion(int size, bool secure)
-:_secure(secure), d(new Private(size, secure))
+ : _secure(secure), d(new Private(size, secure))
{
}
MemoryRegion::MemoryRegion(const QByteArray &from, bool secure)
-:_secure(secure), d(new Private(from, secure))
+ : _secure(secure), d(new Private(from, secure))
{
}
char *MemoryRegion::data()
{
- if(!d)
- return blank;
- return d->ai.data;
+ if (!d) {
+ return blank;
+ }
+ return d->ai.data;
}
const char *MemoryRegion::data() const
{
- if(!d)
- return blank;
- return d->ai.data;
+ if (!d) {
+ return blank;
+ }
+ return d->ai.data;
}
const char *MemoryRegion::constData() const
{
- if(!d)
- return blank;
- return d->ai.data;
+ if (!d) {
+ return blank;
+ }
+ return d->ai.data;
}
-char & MemoryRegion::at(int index)
+char &MemoryRegion::at(int index)
{
- return *(d->ai.data + index);
+ return *(d->ai.data + index);
}
-const char & MemoryRegion::at(int index) const
+const char &MemoryRegion::at(int index) const
{
- return *(d->ai.data + index);
+ return *(d->ai.data + index);
}
int MemoryRegion::size() const
{
- if(!d)
- return 0;
- return d->ai.size;
+ if (!d) {
+ return 0;
+ }
+ return d->ai.size;
}
bool MemoryRegion::isEmpty() const
{
- if(!d)
- return true;
- return (d->ai.size > 0 ? false : true);
+ if (!d) {
+ return true;
+ }
+ return (d->ai.size > 0 ? false : true);
}
bool MemoryRegion::resize(int size)
{
- if(!d)
- {
- d = new Private(size, _secure);
- return true;
- }
+ if (!d) {
+ d = new Private(size, _secure);
+ return true;
+ }
- if(d->ai.size == size)
- return true;
+ if (d->ai.size == size) {
+ return true;
+ }
- return d->resize(size);
+ return d->resize(size);
}
void MemoryRegion::set(const QByteArray &from, bool secure)
{
- _secure = secure;
+ _secure = secure;
- if(!from.isEmpty())
- d = new Private(from, secure);
- else
- d = new Private(0, secure);
+ if (!from.isEmpty()) {
+ d = new Private(from, secure);
+ } else {
+ d = new Private(0, secure);
+ }
}
void MemoryRegion::setSecure(bool secure)
{
- _secure = secure;
+ _secure = secure;
- if(!d)
- {
- d = new Private(0, secure);
- return;
- }
+ if (!d) {
+ d = new Private(0, secure);
+ return;
+ }
- d->setSecure(secure);
+ d->setSecure(secure);
}
//----------------------------------------------------------------------------
// SecureArray
//----------------------------------------------------------------------------
SecureArray::SecureArray()
-:MemoryRegion(true)
+ : MemoryRegion(true)
{
}
SecureArray::SecureArray(int size, char ch)
-:MemoryRegion(size, true)
+ : MemoryRegion(size, true)
{
- // ai_new fills with zeros for us
- if(ch != 0)
- fill(ch, size);
+ // ai_new fills with zeros for us
+ if (ch != 0) {
+ fill(ch, size);
+ }
}
SecureArray::SecureArray(const char *str)
-:MemoryRegion(QByteArray::fromRawData(str, strlen(str)), true)
+ : MemoryRegion(QByteArray::fromRawData(str, strlen(str)), true)
{
}
SecureArray::SecureArray(const QByteArray &a)
-:MemoryRegion(a, true)
+ : MemoryRegion(a, true)
{
}
SecureArray::SecureArray(const MemoryRegion &a)
-:MemoryRegion(a)
+ : MemoryRegion(a)
{
- setSecure(true);
+ setSecure(true);
}
SecureArray::SecureArray(const SecureArray &from)
-:MemoryRegion(from)
+ : MemoryRegion(from)
{
}
SecureArray::~SecureArray()
{
}
-SecureArray & SecureArray::operator=(const SecureArray &from)
+SecureArray &SecureArray::operator=(const SecureArray &from)
{
- MemoryRegion::operator=(from);
- return *this;
+ MemoryRegion::operator=(from);
+ return *this;
}
-SecureArray & SecureArray::operator=(const QByteArray &from)
+SecureArray &SecureArray::operator=(const QByteArray &from)
{
- MemoryRegion::set(from, true);
- return *this;
+ MemoryRegion::set(from, true);
+ return *this;
}
void SecureArray::clear()
{
- MemoryRegion::resize(0);
+ MemoryRegion::resize(0);
}
bool SecureArray::resize(int size)
{
- return MemoryRegion::resize(size);
+ return MemoryRegion::resize(size);
}
-char & SecureArray::operator[](int index)
+char &SecureArray::operator[](int index)
{
- return at(index);
+ return at(index);
}
-const char & SecureArray::operator[](int index) const
+const char &SecureArray::operator[](int index) const
{
- return at(index);
+ return at(index);
}
-char & SecureArray::at(int index)
+char &SecureArray::at(int index)
{
- return MemoryRegion::at(index);
+ return MemoryRegion::at(index);
}
-const char & SecureArray::at(int index) const
+const char &SecureArray::at(int index) const
{
- return MemoryRegion::at(index);
+ return MemoryRegion::at(index);
}
char *SecureArray::data()
{
- return MemoryRegion::data();
+ return MemoryRegion::data();
}
const char *SecureArray::data() const
{
- return MemoryRegion::data();
+ return MemoryRegion::data();
}
const char *SecureArray::constData() const
{
- return MemoryRegion::constData();
+ return MemoryRegion::constData();
}
int SecureArray::size() const
{
- return MemoryRegion::size();
+ return MemoryRegion::size();
}
bool SecureArray::isEmpty() const
{
- return MemoryRegion::isEmpty();
+ return MemoryRegion::isEmpty();
}
QByteArray SecureArray::toByteArray() const
{
- return MemoryRegion::toByteArray();
+ return MemoryRegion::toByteArray();
}
-SecureArray & SecureArray::append(const SecureArray &a)
+SecureArray &SecureArray::append(const SecureArray &a)
{
- int oldsize = size();
- resize(oldsize + a.size());
- memcpy(data() + oldsize, a.data(), a.size());
- return *this;
+ int oldsize = size();
+ resize(oldsize + a.size());
+ memcpy(data() + oldsize, a.data(), a.size());
+ return *this;
}
bool SecureArray::operator==(const MemoryRegion &other) const
{
- if(this == &other)
- return true;
- if(size() == other.size() && memcmp(data(), other.data(), size()) == 0)
- return true;
- return false;
+ if (this == &other) {
+ return true;
+ }
+ if (size() == other.size() && memcmp(data(), other.data(), size()) == 0) {
+ return true;
+ }
+ return false;
}
-SecureArray & SecureArray::operator+=(const SecureArray &a)
+SecureArray &SecureArray::operator+=(const SecureArray &a)
{
- return append(a);
+ return append(a);
}
void SecureArray::fill(char fillChar, int fillToPosition)
{
- int len = (fillToPosition == -1) ? size() : qMin(fillToPosition, size());
- if(len > 0)
- memset(data(), (int)fillChar, len);
+ int len = (fillToPosition == -1) ? size() : qMin(fillToPosition, size());
+ if (len > 0) {
+ memset(data(), (int)fillChar, len);
+ }
}
void SecureArray::set(const SecureArray &from)
{
- *this = from;
+ *this = from;
}
void SecureArray::set(const QByteArray &from)
{
- *this = from;
+ *this = from;
}
const SecureArray operator+(const SecureArray &a, const SecureArray &b)
{
- SecureArray c = a;
- return c.append(b);
+ SecureArray c = a;
+ return c.append(b);
}
//----------------------------------------------------------------------------
// BigInteger
//----------------------------------------------------------------------------
static void negate_binary(char *a, int size)
{
- // negate = two's compliment + 1
- bool done = false;
- for(int n = size - 1; n >= 0; --n)
- {
- a[n] = ~a[n];
- if(!done)
- {
- if((unsigned char)a[n] < 0xff)
- {
- ++a[n];
- done = true;
- }
- else
- a[n] = 0;
- }
- }
+ // negate = two's compliment + 1
+ bool done = false;
+ for (int n = size - 1; n >= 0; --n) {
+ a[n] = ~a[n];
+ if (!done) {
+ if ((unsigned char)a[n] < 0xff) {
+ ++a[n];
+ done = true;
+ } else {
+ a[n] = 0;
+ }
+ }
+ }
}
class BigInteger::Private : public QSharedData
{
public:
- Botan::BigInt n;
+ Botan::BigInt n;
};
BigInteger::BigInteger()
{
- d = new Private;
+ d = new Private;
}
BigInteger::BigInteger(int i)
{
- d = new Private;
- if(i < 0)
- {
- d->n = Botan::BigInt(i * (-1));
- d->n.set_sign(Botan::BigInt::Negative);
- }
- else
- {
- d->n = Botan::BigInt(i);
- d->n.set_sign(Botan::BigInt::Positive);
- }
+ d = new Private;
+ if (i < 0) {
+ d->n = Botan::BigInt(i * (-1));
+ d->n.set_sign(Botan::BigInt::Negative);
+ } else {
+ d->n = Botan::BigInt(i);
+ d->n.set_sign(Botan::BigInt::Positive);
+ }
}
BigInteger::BigInteger(const char *c)
{
- d = new Private;
- fromString(QString(c));
+ d = new Private;
+ fromString(QString(c));
}
BigInteger::BigInteger(const QString &s)
{
- d = new Private;
- fromString(s);
+ d = new Private;
+ fromString(s);
}
BigInteger::BigInteger(const SecureArray &a)
{
- d = new Private;
- fromArray(a);
+ d = new Private;
+ fromArray(a);
}
BigInteger::BigInteger(const BigInteger &from)
{
- *this = from;
+ *this = from;
}
BigInteger::~BigInteger()
{
}
-BigInteger & BigInteger::operator=(const BigInteger &from)
+BigInteger &BigInteger::operator=(const BigInteger &from)
{
- d = from.d;
- return *this;
+ d = from.d;
+ return *this;
}
-BigInteger & BigInteger::operator+=(const BigInteger &i)
+BigInteger &BigInteger::operator+=(const BigInteger &i)
{
- d->n += i.d->n;
- return *this;
+ d->n += i.d->n;
+ return *this;
}
-BigInteger & BigInteger::operator-=(const BigInteger &i)
+BigInteger &BigInteger::operator-=(const BigInteger &i)
{
- d->n -= i.d->n;
- return *this;
+ d->n -= i.d->n;
+ return *this;
}
-BigInteger & BigInteger::operator*=(const BigInteger &i)
+BigInteger &BigInteger::operator*=(const BigInteger &i)
{
- d->n *= i.d->n;
- return *this;
+ d->n *= i.d->n;
+ return *this;
}
-BigInteger & BigInteger::operator/=(const BigInteger &i)
+BigInteger &BigInteger::operator/=(const BigInteger &i)
{
- try
- {
- d->n /= i.d->n;
- }
- catch(std::exception &)
- {
- fprintf(stderr, "QCA: Botan integer division error\n");
- abort();
- }
- return *this;
+ try {
+ d->n /= i.d->n;
+ } catch (std::exception &) {
+ fprintf(stderr, "QCA: Botan integer division error\n");
+ abort();
+ }
+ return *this;
}
-BigInteger & BigInteger::operator%=(const BigInteger &i)
+BigInteger &BigInteger::operator%=(const BigInteger &i)
{
- try
- {
- d->n %= i.d->n;
- }
- catch(std::exception &)
- {
- fprintf(stderr, "QCA: Botan integer division error\n");
- abort();
- }
- return *this;
+ try {
+ d->n %= i.d->n;
+ } catch (std::exception &) {
+ fprintf(stderr, "QCA: Botan integer division error\n");
+ abort();
+ }
+ return *this;
}
-BigInteger & BigInteger::operator=(const QString &s)
+BigInteger &BigInteger::operator=(const QString &s)
{
- fromString(s);
- return *this;
+ fromString(s);
+ return *this;
}
int BigInteger::compare(const BigInteger &n) const
{
- return ( (d->n).cmp( n.d->n, true) );
+ return ((d->n).cmp(n.d->n, true));
}
-QTextStream &operator<<(QTextStream &stream, const BigInteger& b)
+QTextStream &operator<<(QTextStream &stream, const BigInteger &b)
{
- stream << b.toString();
- return stream;
+ stream << b.toString();
+ return stream;
}
SecureArray BigInteger::toArray() const
{
- int size = d->n.encoded_size(Botan::BigInt::Binary);
+ int size = d->n.encoded_size(Botan::BigInt::Binary);
- // return at least 8 bits
- if(size == 0)
- {
- SecureArray a(1);
- a[0] = 0;
- return a;
- }
+ // return at least 8 bits
+ if (size == 0) {
+ SecureArray a(1);
+ a[0] = 0;
+ return a;
+ }
- int offset = 0;
- SecureArray a;
+ int offset = 0;
+ SecureArray a;
- // make room for a sign bit if needed
- if(d->n.get_bit((size * 8) - 1))
- {
- ++size;
- a.resize(size);
- a[0] = 0;
- ++offset;
- }
- else
- a.resize(size);
+ // make room for a sign bit if needed
+ if (d->n.get_bit((size * 8) - 1)) {
+ ++size;
+ a.resize(size);
+ a[0] = 0;
+ ++offset;
+ } else {
+ a.resize(size);
+ }
- Botan::BigInt::encode((Botan::byte *)a.data() + offset, d->n, Botan::BigInt::Binary);
+ Botan::BigInt::encode((Botan::byte *)a.data() + offset, d->n, Botan::BigInt::Binary);
- if(d->n.is_negative())
- negate_binary(a.data(), a.size());
+ if (d->n.is_negative()) {
+ negate_binary(a.data(), a.size());
+ }
- return a;
+ return a;
}
void BigInteger::fromArray(const SecureArray &_a)
{
- if(_a.isEmpty())
- {
- d->n = Botan::BigInt(0);
- return;
- }
- SecureArray a = _a;
+ if (_a.isEmpty()) {
+ d->n = Botan::BigInt(0);
+ return;
+ }
+ SecureArray a = _a;
- Botan::BigInt::Sign sign = Botan::BigInt::Positive;
- if(a[0] & 0x80)
- sign = Botan::BigInt::Negative;
+ Botan::BigInt::Sign sign = Botan::BigInt::Positive;
+ if (a[0] & 0x80) {
+ sign = Botan::BigInt::Negative;
+ }
- if(sign == Botan::BigInt::Negative)
- negate_binary(a.data(), a.size());
+ if (sign == Botan::BigInt::Negative) {
+ negate_binary(a.data(), a.size());
+ }
- d->n = Botan::BigInt::decode((const Botan::byte *)a.data(), a.size(), Botan::BigInt::Binary);
- d->n.set_sign(sign);
+ d->n = Botan::BigInt::decode((const Botan::byte *)a.data(), a.size(), Botan::BigInt::Binary);
+ d->n.set_sign(sign);
}
QString BigInteger::toString() const
{
- QByteArray cs;
- try
- {
- cs.resize(d->n.encoded_size(Botan::BigInt::Decimal));
- Botan::BigInt::encode((Botan::byte *)cs.data(), d->n, Botan::BigInt::Decimal);
- }
- catch(std::exception &)
- {
- return QString();
- }
+ QByteArray cs;
+ try {
+ cs.resize(d->n.encoded_size(Botan::BigInt::Decimal));
+ Botan::BigInt::encode((Botan::byte *)cs.data(), d->n, Botan::BigInt::Decimal);
+ } catch (std::exception &) {
+ return QString();
+ }
- QString str;
- if(d->n.is_negative())
- str += '-';
- str += QString::fromLatin1(cs);
- return str;
+ QString str;
+ if (d->n.is_negative()) {
+ str += '-';
+ }
+ str += QString::fromLatin1(cs);
+ return str;
}
bool BigInteger::fromString(const QString &s)
{
- if(s.isEmpty())
- return false;
- QByteArray cs = s.toLatin1();
-
- bool neg = false;
- if(s[0] == '-')
- neg = true;
-
- try
- {
- d->n = Botan::BigInt::decode((const Botan::byte *)cs.data() + (neg ? 1 : 0), cs.length() - (neg ? 1 : 0), Botan::BigInt::Decimal);
- }
- catch(std::exception &)
- {
- return false;
- }
-
- if(neg)
- d->n.set_sign(Botan::BigInt::Negative);
- else
- d->n.set_sign(Botan::BigInt::Positive);
- return true;
+ if (s.isEmpty()) {
+ return false;
+ }
+ QByteArray cs = s.toLatin1();
+
+ bool neg = false;
+ if (s[0] == '-') {
+ neg = true;
+ }
+
+ try {
+ d->n = Botan::BigInt::decode((const Botan::byte *)cs.data() + (neg ? 1 : 0), cs.length() - (neg ? 1 : 0), Botan::BigInt::Decimal);
+ } catch (std::exception &) {
+ return false;
+ }
+
+ if (neg) {
+ d->n.set_sign(Botan::BigInt::Negative);
+ } else {
+ d->n.set_sign(Botan::BigInt::Positive);
+ }
+ return true;
}
}
diff --git a/src/support/console.cpp b/src/support/console.cpp
index ee949989..542ca2b7 100644
--- a/src/support/console.cpp
+++ b/src/support/console.cpp
@@ -1,1027 +1,1016 @@
/*
* Copyright (C) 2006,2007 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_support.h"
#include "qpipe.h"
#include "qca_safeobj.h"
#include <QPointer>
#include <QTextCodec>
#include <QMutex>
#ifdef Q_OS_WIN
# include <windows.h>
#else
# ifdef Q_OS_ANDROID
# include <termios.h>
# else
# include <sys/termios.h>
# endif
# include <unistd.h>
# include <fcntl.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#define CONSOLEPROMPT_INPUT_MAX 56
Q_DECLARE_METATYPE(QCA::SecureArray)
-namespace QCA {
+namespace QCA
+{
//----------------------------------------------------------------------------
// ConsoleWorker
//----------------------------------------------------------------------------
class ConsoleWorker : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private:
- QPipeEnd in, out;
- bool started;
- QByteArray in_left, out_left;
+ QPipeEnd in, out;
+ bool started;
+ QByteArray in_left, out_left;
public:
- ConsoleWorker(QObject *parent = 0) : QObject(parent), in(this), out(this)
- {
- started = false;
- }
-
- ~ConsoleWorker()
- {
- stop();
- }
-
- void start(Q_PIPE_ID in_id, Q_PIPE_ID out_id)
- {
- Q_ASSERT(!started);
-
- if(in_id != INVALID_Q_PIPE_ID)
- {
- in.take(in_id, QPipeDevice::Read);
- connect(&in, SIGNAL(readyRead()), SLOT(in_readyRead()));
- connect(&in, SIGNAL(closed()), SLOT(in_closed()));
- connect(&in, SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(in_error(QCA::QPipeEnd::Error)));
- in.enable();
- }
-
- if(out_id != INVALID_Q_PIPE_ID)
- {
- out.take(out_id, QPipeDevice::Write);
- connect(&out, SIGNAL(bytesWritten(int)), SLOT(out_bytesWritten(int)));
- connect(&out, SIGNAL(closed()), SLOT(out_closed()));
- out.enable();
- }
-
- started = true;
- }
-
- void stop()
- {
- if(!started)
- return;
-
- if(in.isValid())
- in.finalizeAndRelease();
- if(out.isValid())
- out.release();
-
- in_left = in.read();
- out_left = out.takeBytesToWrite();
-
- started = false;
- }
+ ConsoleWorker(QObject *parent = 0) : QObject(parent), in(this), out(this)
+ {
+ started = false;
+ }
+
+ ~ConsoleWorker()
+ {
+ stop();
+ }
+
+ void start(Q_PIPE_ID in_id, Q_PIPE_ID out_id)
+ {
+ Q_ASSERT(!started);
+
+ if (in_id != INVALID_Q_PIPE_ID) {
+ in.take(in_id, QPipeDevice::Read);
+ connect(&in, SIGNAL(readyRead()), SLOT(in_readyRead()));
+ connect(&in, SIGNAL(closed()), SLOT(in_closed()));
+ connect(&in, SIGNAL(error(QCA::QPipeEnd::Error)), SLOT(in_error(QCA::QPipeEnd::Error)));
+ in.enable();
+ }
+
+ if (out_id != INVALID_Q_PIPE_ID) {
+ out.take(out_id, QPipeDevice::Write);
+ connect(&out, SIGNAL(bytesWritten(int)), SLOT(out_bytesWritten(int)));
+ connect(&out, SIGNAL(closed()), SLOT(out_closed()));
+ out.enable();
+ }
+
+ started = true;
+ }
+
+ void stop()
+ {
+ if (!started) {
+ return;
+ }
+
+ if (in.isValid()) {
+ in.finalizeAndRelease();
+ }
+ if (out.isValid()) {
+ out.release();
+ }
+
+ in_left = in.read();
+ out_left = out.takeBytesToWrite();
+
+ started = false;
+ }
public slots:
- bool isValid() const
- {
- return in.isValid();
- }
-
- void setSecurityEnabled(bool enabled)
- {
- if(in.isValid())
- in.setSecurityEnabled(enabled);
- if(out.isValid())
- out.setSecurityEnabled(enabled);
- }
-
- QByteArray read(int bytes = -1)
- {
- return in.read(bytes);
- }
-
- void write(const QByteArray &a)
- {
- out.write(a);
- }
-
- QCA::SecureArray readSecure(int bytes = -1)
- {
- return in.readSecure(bytes);
- }
-
- void writeSecure(const QCA::SecureArray &a)
- {
- out.writeSecure(a);
- }
-
- void closeOutput()
- {
- out.close();
- }
-
- int bytesAvailable() const
- {
- return in.bytesAvailable();
- }
-
- int bytesToWrite() const
- {
- return in.bytesToWrite();
- }
+ bool isValid() const
+ {
+ return in.isValid();
+ }
+
+ void setSecurityEnabled(bool enabled)
+ {
+ if (in.isValid()) {
+ in.setSecurityEnabled(enabled);
+ }
+ if (out.isValid()) {
+ out.setSecurityEnabled(enabled);
+ }
+ }
+
+ QByteArray read(int bytes = -1)
+ {
+ return in.read(bytes);
+ }
+
+ void write(const QByteArray &a)
+ {
+ out.write(a);
+ }
+
+ QCA::SecureArray readSecure(int bytes = -1)
+ {
+ return in.readSecure(bytes);
+ }
+
+ void writeSecure(const QCA::SecureArray &a)
+ {
+ out.writeSecure(a);
+ }
+
+ void closeOutput()
+ {
+ out.close();
+ }
+
+ int bytesAvailable() const
+ {
+ return in.bytesAvailable();
+ }
+
+ int bytesToWrite() const
+ {
+ return in.bytesToWrite();
+ }
public:
- QByteArray takeBytesToRead()
- {
- QByteArray a = in_left;
- in_left.clear();
- return a;
- }
-
- QByteArray takeBytesToWrite()
- {
- QByteArray a = out_left;
- out_left.clear();
- return a;
- }
+ QByteArray takeBytesToRead()
+ {
+ QByteArray a = in_left;
+ in_left.clear();
+ return a;
+ }
+
+ QByteArray takeBytesToWrite()
+ {
+ QByteArray a = out_left;
+ out_left.clear();
+ return a;
+ }
signals:
- void readyRead();
- void bytesWritten(int bytes);
- void inputClosed();
- void outputClosed();
+ void readyRead();
+ void bytesWritten(int bytes);
+ void inputClosed();
+ void outputClosed();
private slots:
- void in_readyRead()
- {
- emit readyRead();
- }
-
- void out_bytesWritten(int bytes)
- {
- emit bytesWritten(bytes);
- }
-
- void in_closed()
- {
- emit inputClosed();
- }
-
- void in_error(QCA::QPipeEnd::Error)
- {
- emit inputClosed();
- }
-
- void out_closed()
- {
- emit outputClosed();
- }
+ void in_readyRead()
+ {
+ emit readyRead();
+ }
+
+ void out_bytesWritten(int bytes)
+ {
+ emit bytesWritten(bytes);
+ }
+
+ void in_closed()
+ {
+ emit inputClosed();
+ }
+
+ void in_error(QCA::QPipeEnd::Error)
+ {
+ emit inputClosed();
+ }
+
+ void out_closed()
+ {
+ emit outputClosed();
+ }
};
//----------------------------------------------------------------------------
// ConsoleThread
//----------------------------------------------------------------------------
class ConsoleThread : public SyncThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- ConsoleWorker *worker;
- Q_PIPE_ID _in_id, _out_id;
- QByteArray in_left, out_left;
- QMutex call_mutex;
-
- ConsoleThread(QObject *parent = 0) : SyncThread(parent)
- {
- qRegisterMetaType<SecureArray>("QCA::SecureArray");
- }
-
- ~ConsoleThread()
- {
- stop();
- }
-
- void start(Q_PIPE_ID in_id, Q_PIPE_ID out_id)
- {
- _in_id = in_id;
- _out_id = out_id;
- SyncThread::start();
- }
-
- void stop()
- {
- SyncThread::stop();
- }
-
- QVariant mycall(QObject *obj, const char *method, const QVariantList &args = QVariantList())
- {
- QVariant ret;
- bool ok;
-
- call_mutex.lock();
- ret = call(obj, method, args, &ok);
- call_mutex.unlock();
-
- Q_ASSERT(ok);
- if(!ok)
- {
- fprintf(stderr, "QCA: ConsoleWorker call [%s] failed.\n", method);
- abort();
- return QVariant();
- }
- return ret;
- }
-
- bool isValid()
- {
- return mycall(worker, "isValid").toBool();
- }
-
- void setSecurityEnabled(bool enabled)
- {
- mycall(worker, "setSecurityEnabled", QVariantList() << enabled);
- }
-
- QByteArray read(int bytes = -1)
- {
- return mycall(worker, "read", QVariantList() << bytes).toByteArray();
- }
-
- void write(const QByteArray &a)
- {
- mycall(worker, "write", QVariantList() << a);
- }
-
- SecureArray readSecure(int bytes = -1)
- {
+ ConsoleWorker *worker;
+ Q_PIPE_ID _in_id, _out_id;
+ QByteArray in_left, out_left;
+ QMutex call_mutex;
+
+ ConsoleThread(QObject *parent = 0) : SyncThread(parent)
+ {
+ qRegisterMetaType<SecureArray>("QCA::SecureArray");
+ }
+
+ ~ConsoleThread()
+ {
+ stop();
+ }
+
+ void start(Q_PIPE_ID in_id, Q_PIPE_ID out_id)
+ {
+ _in_id = in_id;
+ _out_id = out_id;
+ SyncThread::start();
+ }
+
+ void stop()
+ {
+ SyncThread::stop();
+ }
+
+ QVariant mycall(QObject *obj, const char *method, const QVariantList &args = QVariantList())
+ {
+ QVariant ret;
+ bool ok;
+
+ call_mutex.lock();
+ ret = call(obj, method, args, &ok);
+ call_mutex.unlock();
+
+ Q_ASSERT(ok);
+ if (!ok) {
+ fprintf(stderr, "QCA: ConsoleWorker call [%s] failed.\n", method);
+ abort();
+ return QVariant();
+ }
+ return ret;
+ }
+
+ bool isValid()
+ {
+ return mycall(worker, "isValid").toBool();
+ }
+
+ void setSecurityEnabled(bool enabled)
+ {
+ mycall(worker, "setSecurityEnabled", QVariantList() << enabled);
+ }
+
+ QByteArray read(int bytes = -1)
+ {
+ return mycall(worker, "read", QVariantList() << bytes).toByteArray();
+ }
+
+ void write(const QByteArray &a)
+ {
+ mycall(worker, "write", QVariantList() << a);
+ }
+
+ SecureArray readSecure(int bytes = -1)
+ {
#if QT_VERSION >= 0x050000
- return mycall(worker, "readSecure", QVariantList() << bytes).value<SecureArray>();
+ return mycall(worker, "readSecure", QVariantList() << bytes).value<SecureArray>();
#else
- return qVariantValue<SecureArray>(mycall(worker, "readSecure", QVariantList() << bytes));
+ return qVariantValue<SecureArray>(mycall(worker, "readSecure", QVariantList() << bytes));
#endif
- }
-
- void writeSecure(const SecureArray &a)
- {
- mycall(worker, "writeSecure", QVariantList() << qVariantFromValue<SecureArray>(a));
- }
-
- void closeOutput()
- {
- mycall(worker, "closeOutput");
- }
-
- int bytesAvailable()
- {
- return mycall(worker, "bytesAvailable").toInt();
- }
-
- int bytesToWrite()
- {
- return mycall(worker, "bytesToWrite").toInt();
- }
-
- QByteArray takeBytesToRead()
- {
- QByteArray a = in_left;
- in_left.clear();
- return a;
- }
-
- QByteArray takeBytesToWrite()
- {
- QByteArray a = out_left;
- out_left.clear();
- return a;
- }
+ }
+
+ void writeSecure(const SecureArray &a)
+ {
+ mycall(worker, "writeSecure", QVariantList() << qVariantFromValue<SecureArray>(a));
+ }
+
+ void closeOutput()
+ {
+ mycall(worker, "closeOutput");
+ }
+
+ int bytesAvailable()
+ {
+ return mycall(worker, "bytesAvailable").toInt();
+ }
+
+ int bytesToWrite()
+ {
+ return mycall(worker, "bytesToWrite").toInt();
+ }
+
+ QByteArray takeBytesToRead()
+ {
+ QByteArray a = in_left;
+ in_left.clear();
+ return a;
+ }
+
+ QByteArray takeBytesToWrite()
+ {
+ QByteArray a = out_left;
+ out_left.clear();
+ return a;
+ }
signals:
- void readyRead();
- void bytesWritten(int);
- void inputClosed();
- void outputClosed();
+ void readyRead();
+ void bytesWritten(int);
+ void inputClosed();
+ void outputClosed();
protected:
- virtual void atStart()
- {
- worker = new ConsoleWorker;
-
- // use direct connections here, so that the emits come from
- // the other thread. we can also connect to our own
- // signals to avoid having to make slots just to emit.
- connect(worker, SIGNAL(readyRead()), SIGNAL(readyRead()), Qt::DirectConnection);
- connect(worker, SIGNAL(bytesWritten(int)), SIGNAL(bytesWritten(int)), Qt::DirectConnection);
- connect(worker, SIGNAL(inputClosed()), SIGNAL(inputClosed()), Qt::DirectConnection);
- connect(worker, SIGNAL(outputClosed()), SIGNAL(outputClosed()), Qt::DirectConnection);
-
- worker->start(_in_id, _out_id);
- }
-
- virtual void atEnd()
- {
- in_left = worker->takeBytesToRead();
- out_left = worker->takeBytesToWrite();
- delete worker;
- }
+ virtual void atStart()
+ {
+ worker = new ConsoleWorker;
+
+ // use direct connections here, so that the emits come from
+ // the other thread. we can also connect to our own
+ // signals to avoid having to make slots just to emit.
+ connect(worker, SIGNAL(readyRead()), SIGNAL(readyRead()), Qt::DirectConnection);
+ connect(worker, SIGNAL(bytesWritten(int)), SIGNAL(bytesWritten(int)), Qt::DirectConnection);
+ connect(worker, SIGNAL(inputClosed()), SIGNAL(inputClosed()), Qt::DirectConnection);
+ connect(worker, SIGNAL(outputClosed()), SIGNAL(outputClosed()), Qt::DirectConnection);
+
+ worker->start(_in_id, _out_id);
+ }
+
+ virtual void atEnd()
+ {
+ in_left = worker->takeBytesToRead();
+ out_left = worker->takeBytesToWrite();
+ delete worker;
+ }
};
//----------------------------------------------------------------------------
// Console
//----------------------------------------------------------------------------
class ConsolePrivate : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- Console *q;
+ Console *q;
- bool started;
- Console::Type type;
- Console::ChannelMode cmode;
- Console::TerminalMode mode;
- ConsoleThread *thread;
- ConsoleReference *ref;
- Q_PIPE_ID in_id;
+ bool started;
+ Console::Type type;
+ Console::ChannelMode cmode;
+ Console::TerminalMode mode;
+ ConsoleThread *thread;
+ ConsoleReference *ref;
+ Q_PIPE_ID in_id;
#ifdef Q_OS_WIN
- DWORD old_mode;
+ DWORD old_mode;
#else
- struct termios old_term_attr;
+ struct termios old_term_attr;
#endif
- ConsolePrivate(Console *_q) : QObject(_q), q(_q)
- {
- started = false;
- mode = Console::Default;
- thread = new ConsoleThread(this);
- ref = 0;
- }
-
- ~ConsolePrivate()
- {
- delete thread;
- setInteractive(Console::Default);
- }
-
- void setInteractive(Console::TerminalMode m)
- {
- // no change
- if(m == mode)
- return;
-
- if(m == Console::Interactive)
- {
+ ConsolePrivate(Console *_q) : QObject(_q), q(_q)
+ {
+ started = false;
+ mode = Console::Default;
+ thread = new ConsoleThread(this);
+ ref = 0;
+ }
+
+ ~ConsolePrivate()
+ {
+ delete thread;
+ setInteractive(Console::Default);
+ }
+
+ void setInteractive(Console::TerminalMode m)
+ {
+ // no change
+ if (m == mode) {
+ return;
+ }
+
+ if (m == Console::Interactive) {
#ifdef Q_OS_WIN
- GetConsoleMode(in_id, &old_mode);
- SetConsoleMode(in_id, old_mode & (~ENABLE_LINE_INPUT & ~ENABLE_ECHO_INPUT));
+ GetConsoleMode(in_id, &old_mode);
+ SetConsoleMode(in_id, old_mode & (~ENABLE_LINE_INPUT & ~ENABLE_ECHO_INPUT));
#else
- int fd = in_id;
- struct termios attr;
- tcgetattr(fd, &attr);
- old_term_attr = attr;
-
- attr.c_lflag &= ~(ECHO); // turn off the echo flag
- attr.c_lflag &= ~(ICANON); // no wait for a newline
- attr.c_cc[VMIN] = 1; // read at least 1 char
- attr.c_cc[VTIME] = 0; // set wait time to zero
-
- // set the new attributes
- tcsetattr(fd, TCSAFLUSH, &attr);
+ int fd = in_id;
+ struct termios attr;
+ tcgetattr(fd, &attr);
+ old_term_attr = attr;
+
+ attr.c_lflag &= ~(ECHO); // turn off the echo flag
+ attr.c_lflag &= ~(ICANON); // no wait for a newline
+ attr.c_cc[VMIN] = 1; // read at least 1 char
+ attr.c_cc[VTIME] = 0; // set wait time to zero
+
+ // set the new attributes
+ tcsetattr(fd, TCSAFLUSH, &attr);
#endif
- }
- else
- {
+ } else {
#ifdef Q_OS_WIN
- SetConsoleMode(in_id, old_mode);
+ SetConsoleMode(in_id, old_mode);
#else
- int fd = in_id;
- tcsetattr(fd, TCSANOW, &old_term_attr);
+ int fd = in_id;
+ tcsetattr(fd, TCSANOW, &old_term_attr);
#endif
- }
+ }
- mode = m;
- }
+ mode = m;
+ }
};
static Console *g_tty_console = 0, *g_stdio_console = 0;
Console::Console(Type type, ChannelMode cmode, TerminalMode tmode, QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- if(type == Tty)
- {
- Q_ASSERT(g_tty_console == 0);
- g_tty_console = this;
- }
- else
- {
- Q_ASSERT(g_stdio_console == 0);
- g_stdio_console = this;
- }
-
- d = new ConsolePrivate(this);
- d->type = type;
- d->cmode = cmode;
-
- Q_PIPE_ID in = INVALID_Q_PIPE_ID;
- Q_PIPE_ID out = INVALID_Q_PIPE_ID;
+ if (type == Tty) {
+ Q_ASSERT(g_tty_console == 0);
+ g_tty_console = this;
+ } else {
+ Q_ASSERT(g_stdio_console == 0);
+ g_stdio_console = this;
+ }
+
+ d = new ConsolePrivate(this);
+ d->type = type;
+ d->cmode = cmode;
+
+ Q_PIPE_ID in = INVALID_Q_PIPE_ID;
+ Q_PIPE_ID out = INVALID_Q_PIPE_ID;
#ifdef Q_OS_WIN
- if(type == Tty)
- {
- in = CreateFileA("CONIN$", GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
- OPEN_EXISTING, 0, NULL);
- }
- else
- {
- in = GetStdHandle(STD_INPUT_HANDLE);
- }
+ if (type == Tty) {
+ in = CreateFileA("CONIN$", GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
+ OPEN_EXISTING, 0, NULL);
+ } else {
+ in = GetStdHandle(STD_INPUT_HANDLE);
+ }
#else
- if(type == Tty)
- {
- in = open("/dev/tty", O_RDONLY);
- }
- else
- {
- in = 0; // stdin
- }
+ if (type == Tty) {
+ in = open("/dev/tty", O_RDONLY);
+ } else {
+ in = 0; // stdin
+ }
#endif
- if(cmode == ReadWrite)
- {
+ if (cmode == ReadWrite) {
#ifdef Q_OS_WIN
- if(type == Tty)
- {
- out = CreateFileA("CONOUT$",
- GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
- OPEN_EXISTING, 0, NULL);
- }
- else
- {
- out = GetStdHandle(STD_OUTPUT_HANDLE);
- }
+ if (type == Tty) {
+ out = CreateFileA("CONOUT$",
+ GENERIC_READ | GENERIC_WRITE,
+ FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
+ OPEN_EXISTING, 0, NULL);
+ } else {
+ out = GetStdHandle(STD_OUTPUT_HANDLE);
+ }
#else
- if(type == Tty)
- {
- out = open("/dev/tty", O_WRONLY);
- }
- else
- {
- out = 1; // stdout
- }
+ if (type == Tty) {
+ out = open("/dev/tty", O_WRONLY);
+ } else {
+ out = 1; // stdout
+ }
#endif
- }
+ }
- d->in_id = in;
- d->setInteractive(tmode);
- d->thread->start(in, out);
+ d->in_id = in;
+ d->setInteractive(tmode);
+ d->thread->start(in, out);
}
Console::~Console()
{
- release();
- Console::Type type = d->type;
- delete d;
- if(type == Tty)
- g_tty_console = 0;
- else
- g_stdio_console = 0;
+ release();
+ Console::Type type = d->type;
+ delete d;
+ if (type == Tty) {
+ g_tty_console = 0;
+ } else {
+ g_stdio_console = 0;
+ }
}
Console::Type Console::type() const
{
- return d->type;
+ return d->type;
}
Console::ChannelMode Console::channelMode() const
{
- return d->cmode;
+ return d->cmode;
}
Console::TerminalMode Console::terminalMode() const
{
- return d->mode;
+ return d->mode;
}
bool Console::isStdinRedirected()
{
#ifdef Q_OS_WIN
- HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
- DWORD mode;
- if(GetConsoleMode(h, &mode))
- return false;
- return true;
+ HANDLE h = GetStdHandle(STD_INPUT_HANDLE);
+ DWORD mode;
+ if (GetConsoleMode(h, &mode)) {
+ return false;
+ }
+ return true;
#else
- return (isatty(0) ? false : true); // 0 == stdin
+ return (isatty(0) ? false : true); // 0 == stdin
#endif
}
bool Console::isStdoutRedirected()
{
#ifdef Q_OS_WIN
- HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
- DWORD mode;
- if(GetConsoleMode(h, &mode))
- return false;
- return true;
+ HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
+ DWORD mode;
+ if (GetConsoleMode(h, &mode)) {
+ return false;
+ }
+ return true;
#else
- return (isatty(1) ? false : true); // 1 == stdout
+ return (isatty(1) ? false : true); // 1 == stdout
#endif
}
Console *Console::ttyInstance()
{
- return g_tty_console;
+ return g_tty_console;
}
Console *Console::stdioInstance()
{
- return g_stdio_console;
+ return g_stdio_console;
}
void Console::release()
{
- d->thread->stop();
+ d->thread->stop();
}
QByteArray Console::bytesLeftToRead()
{
- return d->thread->takeBytesToRead();
+ return d->thread->takeBytesToRead();
}
QByteArray Console::bytesLeftToWrite()
{
- return d->thread->takeBytesToWrite();
+ return d->thread->takeBytesToWrite();
}
//----------------------------------------------------------------------------
// ConsoleReference
//----------------------------------------------------------------------------
class ConsoleReferencePrivate : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- ConsoleReference *q;
-
- Console *console;
- ConsoleThread *thread;
- ConsoleReference::SecurityMode smode;
- SafeTimer lateTrigger;
- bool late_read, late_close;
-
- ConsoleReferencePrivate(ConsoleReference *_q) : QObject(_q), q(_q), lateTrigger(this)
- {
- console = 0;
- thread = 0;
- connect(&lateTrigger, SIGNAL(timeout()), SLOT(doLate()));
- lateTrigger.setSingleShot(true);
- }
+ ConsoleReference *q;
+
+ Console *console;
+ ConsoleThread *thread;
+ ConsoleReference::SecurityMode smode;
+ SafeTimer lateTrigger;
+ bool late_read, late_close;
+
+ ConsoleReferencePrivate(ConsoleReference *_q) : QObject(_q), q(_q), lateTrigger(this)
+ {
+ console = 0;
+ thread = 0;
+ connect(&lateTrigger, SIGNAL(timeout()), SLOT(doLate()));
+ lateTrigger.setSingleShot(true);
+ }
private slots:
- void doLate()
- {
- QPointer<QObject> self = this;
- if(late_read)
- emit q->readyRead();
- if(!self)
- return;
- if(late_close)
- emit q->inputClosed();
- }
+ void doLate()
+ {
+ QPointer<QObject> self = this;
+ if (late_read) {
+ emit q->readyRead();
+ }
+ if (!self) {
+ return;
+ }
+ if (late_close) {
+ emit q->inputClosed();
+ }
+ }
};
ConsoleReference::ConsoleReference(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new ConsoleReferencePrivate(this);
+ d = new ConsoleReferencePrivate(this);
}
ConsoleReference::~ConsoleReference()
{
- stop();
- delete d;
+ stop();
+ delete d;
}
bool ConsoleReference::start(Console *console, SecurityMode mode)
{
- // make sure this reference isn't using a console already
- Q_ASSERT(!d->console);
+ // make sure this reference isn't using a console already
+ Q_ASSERT(!d->console);
- // one console reference at a time
- Q_ASSERT(console->d->ref == 0);
+ // one console reference at a time
+ Q_ASSERT(console->d->ref == 0);
- // let's take it
- d->console = console;
- d->thread = d->console->d->thread;
- d->console->d->ref = this;
+ // let's take it
+ d->console = console;
+ d->thread = d->console->d->thread;
+ d->console->d->ref = this;
- bool valid = d->thread->isValid();
- int avail = d->thread->bytesAvailable();
+ bool valid = d->thread->isValid();
+ int avail = d->thread->bytesAvailable();
- // pipe already closed and no data? consider this an error
- if(!valid && avail == 0)
- {
- d->console->d->ref = 0;
- d->thread = 0;
- d->console = 0;
- return false;
- }
+ // pipe already closed and no data? consider this an error
+ if (!valid && avail == 0) {
+ d->console->d->ref = 0;
+ d->thread = 0;
+ d->console = 0;
+ return false;
+ }
- // enable security? it will last for this active session only
- d->smode = mode;
- if(mode == SecurityEnabled)
- d->thread->setSecurityEnabled(true);
+ // enable security? it will last for this active session only
+ d->smode = mode;
+ if (mode == SecurityEnabled) {
+ d->thread->setSecurityEnabled(true);
+ }
- connect(d->thread, SIGNAL(readyRead()), SIGNAL(readyRead()));
- connect(d->thread, SIGNAL(bytesWritten(int)), SIGNAL(bytesWritten(int)));
- connect(d->thread, SIGNAL(inputClosed()), SIGNAL(inputClosed()));
- connect(d->thread, SIGNAL(outputClosed()), SIGNAL(outputClosed()));
+ connect(d->thread, SIGNAL(readyRead()), SIGNAL(readyRead()));
+ connect(d->thread, SIGNAL(bytesWritten(int)), SIGNAL(bytesWritten(int)));
+ connect(d->thread, SIGNAL(inputClosed()), SIGNAL(inputClosed()));
+ connect(d->thread, SIGNAL(outputClosed()), SIGNAL(outputClosed()));
- d->late_read = false;
- d->late_close = false;
+ d->late_read = false;
+ d->late_close = false;
- if(avail > 0)
- d->late_read = true;
+ if (avail > 0) {
+ d->late_read = true;
+ }
- if(!valid)
- d->late_close = true;
+ if (!valid) {
+ d->late_close = true;
+ }
- if(d->late_read || d->late_close)
- d->lateTrigger.start();
+ if (d->late_read || d->late_close) {
+ d->lateTrigger.start();
+ }
- return true;
+ return true;
}
void ConsoleReference::stop()
{
- if(!d->console)
- return;
+ if (!d->console) {
+ return;
+ }
- d->lateTrigger.stop();
+ d->lateTrigger.stop();
- disconnect(d->thread, 0, this, 0);
+ disconnect(d->thread, 0, this, 0);
- // automatically disable security when we go inactive
- d->thread->setSecurityEnabled(false);
+ // automatically disable security when we go inactive
+ d->thread->setSecurityEnabled(false);
- d->console->d->ref = 0;
- d->thread = 0;
- d->console = 0;
+ d->console->d->ref = 0;
+ d->thread = 0;
+ d->console = 0;
}
Console *ConsoleReference::console() const
{
- return d->console;
+ return d->console;
}
ConsoleReference::SecurityMode ConsoleReference::securityMode() const
{
- return d->smode;
+ return d->smode;
}
QByteArray ConsoleReference::read(int bytes)
{
- return d->thread->read(bytes);
+ return d->thread->read(bytes);
}
void ConsoleReference::write(const QByteArray &a)
{
- d->thread->write(a);
+ d->thread->write(a);
}
SecureArray ConsoleReference::readSecure(int bytes)
{
- return d->thread->readSecure(bytes);
+ return d->thread->readSecure(bytes);
}
void ConsoleReference::writeSecure(const SecureArray &a)
{
- d->thread->writeSecure(a);
+ d->thread->writeSecure(a);
}
void ConsoleReference::closeOutput()
{
- d->thread->closeOutput();
+ d->thread->closeOutput();
}
int ConsoleReference::bytesAvailable() const
{
- return d->thread->bytesAvailable();
+ return d->thread->bytesAvailable();
}
int ConsoleReference::bytesToWrite() const
{
- return d->thread->bytesToWrite();
+ return d->thread->bytesToWrite();
}
//----------------------------------------------------------------------------
// ConsolePrompt
//----------------------------------------------------------------------------
class ConsolePrompt::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- ConsolePrompt *q;
-
- Synchronizer sync;
- Console *con;
- bool own_con;
- ConsoleReference console;
- QString promptStr;
- SecureArray result;
- bool waiting;
- int at;
- bool done;
- bool charMode;
- QTextCodec *codec;
- QTextCodec::ConverterState *encstate, *decstate;
-
- Private(ConsolePrompt *_q) : QObject(_q), q(_q), sync(_q), console(this)
- {
- connect(&console, SIGNAL(readyRead()), SLOT(con_readyRead()));
- connect(&console, SIGNAL(inputClosed()), SLOT(con_inputClosed()));
-
- con = 0;
- own_con = false;
- waiting = false;
+ ConsolePrompt *q;
+
+ Synchronizer sync;
+ Console *con;
+ bool own_con;
+ ConsoleReference console;
+ QString promptStr;
+ SecureArray result;
+ bool waiting;
+ int at;
+ bool done;
+ bool charMode;
+ QTextCodec *codec;
+ QTextCodec::ConverterState *encstate, *decstate;
+
+ Private(ConsolePrompt *_q) : QObject(_q), q(_q), sync(_q), console(this)
+ {
+ connect(&console, SIGNAL(readyRead()), SLOT(con_readyRead()));
+ connect(&console, SIGNAL(inputClosed()), SLOT(con_inputClosed()));
+
+ con = 0;
+ own_con = false;
+ waiting = false;
#ifdef Q_OS_WIN
- codec = QTextCodec::codecForMib(106); // UTF-8
+ codec = QTextCodec::codecForMib(106); // UTF-8
#else
- codec = QTextCodec::codecForLocale();
+ codec = QTextCodec::codecForLocale();
#endif
- encstate = 0;
- decstate = 0;
- }
-
- ~Private()
- {
- reset();
- }
-
- void reset()
- {
- delete encstate;
- encstate = 0;
- delete decstate;
- decstate = 0;
-
- console.stop();
- if(own_con)
- {
- delete con;
- con = 0;
- own_con = false;
- }
- }
-
- bool start(bool _charMode)
- {
- own_con = false;
- con = Console::ttyInstance();
- if(!con)
- {
- con = new Console(Console::Tty, Console::ReadWrite, Console::Interactive);
- own_con = true;
- }
-
- result.clear();
- at = 0;
- done = false;
- charMode = _charMode;
-
- encstate = new QTextCodec::ConverterState(QTextCodec::IgnoreHeader);
- decstate = new QTextCodec::ConverterState(QTextCodec::IgnoreHeader);
-
- if(!console.start(con, ConsoleReference::SecurityEnabled))
- {
- reset();
- fprintf(stderr, "Console input not available or closed\n");
- return false;
- }
-
- if(!charMode)
- writeString(promptStr + ": ");
-
- return true;
- }
-
- void writeString(const QString &str)
- {
- console.writeSecure(codec->fromUnicode(str.unicode(), str.length(), encstate));
- }
-
- // process each char. internally store the result as utf16, which
- // is easier to edit (e.g. backspace)
- bool processChar(QChar c)
- {
- if(charMode)
- {
- appendChar(c);
- done = true;
- return false;
- }
-
- if(c == '\r' || c == '\n')
- {
- writeString("\n");
- done = true;
- return false;
- }
-
- if(c == '\b' || c.unicode() == 0x7f)
- {
- if(at > 0)
- {
- --at;
- writeString("\b \b");
- result.resize(at * sizeof(ushort));
- }
- return true;
- }
- else if(c < 0x20)
- return true;
-
- if(at >= CONSOLEPROMPT_INPUT_MAX)
- return true;
-
- appendChar(c);
-
- writeString("*");
- return true;
- }
-
- void appendChar(QChar c)
- {
- if((at + 1) * (int)sizeof(ushort) > result.size())
- result.resize((at + 1) * sizeof(ushort));
- ushort *p = (ushort *)result.data();
- p[at++] = c.unicode();
- }
-
- void convertToUtf8()
- {
- // convert result from utf16 to utf8, securely
- QTextCodec *codec = QTextCodec::codecForMib(106);
- QTextCodec::ConverterState cstate(QTextCodec::IgnoreHeader);
- SecureArray out;
- ushort *ustr = (ushort *)result.data();
- int len = result.size() / sizeof(ushort);
- for(int n = 0; n < len; ++n)
- {
- QChar c(ustr[n]);
- out += codec->fromUnicode(&c, 1, &cstate);
- }
- result = out;
- }
+ encstate = 0;
+ decstate = 0;
+ }
+
+ ~Private()
+ {
+ reset();
+ }
+
+ void reset()
+ {
+ delete encstate;
+ encstate = 0;
+ delete decstate;
+ decstate = 0;
+
+ console.stop();
+ if (own_con) {
+ delete con;
+ con = 0;
+ own_con = false;
+ }
+ }
+
+ bool start(bool _charMode)
+ {
+ own_con = false;
+ con = Console::ttyInstance();
+ if (!con) {
+ con = new Console(Console::Tty, Console::ReadWrite, Console::Interactive);
+ own_con = true;
+ }
+
+ result.clear();
+ at = 0;
+ done = false;
+ charMode = _charMode;
+
+ encstate = new QTextCodec::ConverterState(QTextCodec::IgnoreHeader);
+ decstate = new QTextCodec::ConverterState(QTextCodec::IgnoreHeader);
+
+ if (!console.start(con, ConsoleReference::SecurityEnabled)) {
+ reset();
+ fprintf(stderr, "Console input not available or closed\n");
+ return false;
+ }
+
+ if (!charMode) {
+ writeString(promptStr + ": ");
+ }
+
+ return true;
+ }
+
+ void writeString(const QString &str)
+ {
+ console.writeSecure(codec->fromUnicode(str.unicode(), str.length(), encstate));
+ }
+
+ // process each char. internally store the result as utf16, which
+ // is easier to edit (e.g. backspace)
+ bool processChar(QChar c)
+ {
+ if (charMode) {
+ appendChar(c);
+ done = true;
+ return false;
+ }
+
+ if (c == '\r' || c == '\n') {
+ writeString("\n");
+ done = true;
+ return false;
+ }
+
+ if (c == '\b' || c.unicode() == 0x7f) {
+ if (at > 0) {
+ --at;
+ writeString("\b \b");
+ result.resize(at * sizeof(ushort));
+ }
+ return true;
+ } else if (c < 0x20) {
+ return true;
+ }
+
+ if (at >= CONSOLEPROMPT_INPUT_MAX) {
+ return true;
+ }
+
+ appendChar(c);
+
+ writeString("*");
+ return true;
+ }
+
+ void appendChar(QChar c)
+ {
+ if ((at + 1) * (int)sizeof(ushort) > result.size()) {
+ result.resize((at + 1) * sizeof(ushort));
+ }
+ ushort *p = (ushort *)result.data();
+ p[at++] = c.unicode();
+ }
+
+ void convertToUtf8()
+ {
+ // convert result from utf16 to utf8, securely
+ QTextCodec *codec = QTextCodec::codecForMib(106);
+ QTextCodec::ConverterState cstate(QTextCodec::IgnoreHeader);
+ SecureArray out;
+ ushort *ustr = (ushort *)result.data();
+ int len = result.size() / sizeof(ushort);
+ for (int n = 0; n < len; ++n) {
+ QChar c(ustr[n]);
+ out += codec->fromUnicode(&c, 1, &cstate);
+ }
+ result = out;
+ }
private slots:
- void con_readyRead()
- {
- while(console.bytesAvailable() > 0)
- {
- SecureArray buf = console.readSecure(1);
- if(buf.isEmpty())
- break;
-
- // convert to unicode and process
- QString str = codec->toUnicode(buf.data(), 1, decstate);
- bool quit = false;
- for(int n = 0; n < str.length(); ++n)
- {
- if(!processChar(str[n]))
- {
- quit = true;
- break;
- }
- }
- if(quit)
- break;
- }
-
- if(done)
- {
- convertToUtf8();
-
- reset();
- if(waiting)
- sync.conditionMet();
- else
- emit q->finished();
- }
- }
-
- void con_inputClosed()
- {
- fprintf(stderr, "Console input closed\n");
- if(!done)
- {
- done = true;
- result.clear();
-
- reset();
- if(waiting)
- sync.conditionMet();
- else
- emit q->finished();
- }
- }
+ void con_readyRead()
+ {
+ while (console.bytesAvailable() > 0) {
+ SecureArray buf = console.readSecure(1);
+ if (buf.isEmpty()) {
+ break;
+ }
+
+ // convert to unicode and process
+ QString str = codec->toUnicode(buf.data(), 1, decstate);
+ bool quit = false;
+ for (int n = 0; n < str.length(); ++n) {
+ if (!processChar(str[n])) {
+ quit = true;
+ break;
+ }
+ }
+ if (quit) {
+ break;
+ }
+ }
+
+ if (done) {
+ convertToUtf8();
+
+ reset();
+ if (waiting) {
+ sync.conditionMet();
+ } else {
+ emit q->finished();
+ }
+ }
+ }
+
+ void con_inputClosed()
+ {
+ fprintf(stderr, "Console input closed\n");
+ if (!done) {
+ done = true;
+ result.clear();
+
+ reset();
+ if (waiting) {
+ sync.conditionMet();
+ } else {
+ emit q->finished();
+ }
+ }
+ }
};
ConsolePrompt::ConsolePrompt(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
ConsolePrompt::~ConsolePrompt()
{
- delete d;
+ delete d;
}
void ConsolePrompt::getHidden(const QString &promptStr)
{
- d->reset();
-
- d->promptStr = promptStr;
- if(!d->start(false))
- {
- QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
- return;
- }
+ d->reset();
+
+ d->promptStr = promptStr;
+ if (!d->start(false)) {
+ QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
+ return;
+ }
}
void ConsolePrompt::getChar()
{
- d->reset();
+ d->reset();
- if(!d->start(true))
- {
- QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
- return;
- }
+ if (!d->start(true)) {
+ QMetaObject::invokeMethod(this, "finished", Qt::QueuedConnection);
+ return;
+ }
}
void ConsolePrompt::waitForFinished()
{
- // reparent the Console under us (for Synchronizer)
- QObject *orig_parent = d->con->parent();
- d->con->setParent(this);
-
- // block while prompting
- d->waiting = true;
- d->sync.waitForCondition();
- d->waiting = false;
-
- // restore parent (if con still exists)
- if(d->con)
- d->con->setParent(orig_parent);
+ // reparent the Console under us (for Synchronizer)
+ QObject *orig_parent = d->con->parent();
+ d->con->setParent(this);
+
+ // block while prompting
+ d->waiting = true;
+ d->sync.waitForCondition();
+ d->waiting = false;
+
+ // restore parent (if con still exists)
+ if (d->con) {
+ d->con->setParent(orig_parent);
+ }
}
SecureArray ConsolePrompt::result() const
{
- return d->result;
+ return d->result;
}
QChar ConsolePrompt::resultChar() const
{
- QString str = QString::fromUtf8(d->result.toByteArray());
+ QString str = QString::fromUtf8(d->result.toByteArray());
- // this will never happen if getChar completes
- if(str.isEmpty())
- return QChar();
+ // this will never happen if getChar completes
+ if (str.isEmpty()) {
+ return QChar();
+ }
- return str[0];
+ return str[0];
}
}
#include "console.moc"
diff --git a/src/support/dirwatch.cpp b/src/support/dirwatch.cpp
index ad47bfc4..71bd11b9 100644
--- a/src/support/dirwatch.cpp
+++ b/src/support/dirwatch.cpp
@@ -1,255 +1,252 @@
/*
* Copyright (C) 2003-2008 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_support.h"
#include <QFileSystemWatcher>
#include <QFileInfo>
#include <QDir>
#include <QList>
#include <QDateTime>
#include "qca_safeobj.h"
-namespace QCA {
+namespace QCA
+{
// this gets us DOR-SS and SR, provided we delete the object between uses.
// we assume QFileSystemWatcher complies to DS,NE.
class QFileSystemWatcherRelay : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- QFileSystemWatcher *watcher;
+ QFileSystemWatcher *watcher;
- QFileSystemWatcherRelay(QFileSystemWatcher *_watcher, QObject *parent = 0)
- :QObject(parent), watcher(_watcher)
- {
- connect(watcher, SIGNAL(directoryChanged(const QString &)), SIGNAL(directoryChanged(const QString &)), Qt::QueuedConnection);
- connect(watcher, SIGNAL(fileChanged(const QString &)), SIGNAL(fileChanged(const QString &)), Qt::QueuedConnection);
- }
+ QFileSystemWatcherRelay(QFileSystemWatcher *_watcher, QObject *parent = 0)
+ : QObject(parent), watcher(_watcher)
+ {
+ connect(watcher, SIGNAL(directoryChanged(QString)), SIGNAL(directoryChanged(QString)), Qt::QueuedConnection);
+ connect(watcher, SIGNAL(fileChanged(QString)), SIGNAL(fileChanged(QString)), Qt::QueuedConnection);
+ }
signals:
- void directoryChanged(const QString &path);
- void fileChanged(const QString &path);
+ void directoryChanged(const QString &path);
+ void fileChanged(const QString &path);
};
//----------------------------------------------------------------------------
// DirWatch
//----------------------------------------------------------------------------
class DirWatch::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- DirWatch *q;
- QFileSystemWatcher *watcher;
- QFileSystemWatcherRelay *watcher_relay;
- QString dirName;
+ DirWatch *q;
+ QFileSystemWatcher *watcher;
+ QFileSystemWatcherRelay *watcher_relay;
+ QString dirName;
- Private(DirWatch *_q) : QObject(_q), q(_q), watcher(0), watcher_relay(0)
- {
- }
+ Private(DirWatch *_q) : QObject(_q), q(_q), watcher(0), watcher_relay(0)
+ {
+ }
private slots:
- void watcher_changed(const QString &path)
- {
- Q_UNUSED(path);
- emit q->changed();
- }
+ void watcher_changed(const QString &path)
+ {
+ Q_UNUSED(path);
+ emit q->changed();
+ }
};
DirWatch::DirWatch(const QString &dir, QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
- setDirName(dir);
+ d = new Private(this);
+ setDirName(dir);
}
DirWatch::~DirWatch()
{
- delete d;
+ delete d;
}
QString DirWatch::dirName() const
{
- return d->dirName;
+ return d->dirName;
}
void DirWatch::setDirName(const QString &dir)
{
- if(d->watcher)
- {
- delete d->watcher;
- delete d->watcher_relay;
- d->watcher = 0;
- d->watcher_relay = 0;
- }
-
- d->dirName = dir;
-
- if(!d->dirName.isEmpty() && QFileInfo(d->dirName).isDir())
- {
- d->watcher = new QFileSystemWatcher(this);
- d->watcher_relay = new QFileSystemWatcherRelay(d->watcher, this);
- connect(d->watcher_relay, SIGNAL(directoryChanged(const QString &)), d, SLOT(watcher_changed(const QString &)));
-
- d->watcher->addPath(d->dirName);
- }
+ if (d->watcher) {
+ delete d->watcher;
+ delete d->watcher_relay;
+ d->watcher = 0;
+ d->watcher_relay = 0;
+ }
+
+ d->dirName = dir;
+
+ if (!d->dirName.isEmpty() && QFileInfo(d->dirName).isDir()) {
+ d->watcher = new QFileSystemWatcher(this);
+ d->watcher_relay = new QFileSystemWatcherRelay(d->watcher, this);
+ connect(d->watcher_relay, SIGNAL(directoryChanged(QString)), d, SLOT(watcher_changed(QString)));
+
+ d->watcher->addPath(d->dirName);
+ }
}
//----------------------------------------------------------------------------
// FileWatch
//----------------------------------------------------------------------------
class FileWatch::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- FileWatch *q;
- QFileSystemWatcher *watcher;
- QFileSystemWatcherRelay *watcher_relay;
- QString fileName; // file (optionally w/ path) as provided by user
- QString filePath; // absolute path of file, calculated by us
- bool fileExisted;
-
- Private(FileWatch *_q) : QObject(_q), q(_q), watcher(0), watcher_relay(0)
- {
- }
-
- void start(const QString &_fileName)
- {
- fileName = _fileName;
-
- watcher = new QFileSystemWatcher(this);
- watcher_relay = new QFileSystemWatcherRelay(watcher, this);
- connect(watcher_relay, SIGNAL(directoryChanged(const QString &)), SLOT(dir_changed(const QString &)));
- connect(watcher_relay, SIGNAL(fileChanged(const QString &)), SLOT(file_changed(const QString &)));
-
- QFileInfo fi(fileName);
- fi.makeAbsolute();
- filePath = fi.filePath();
- QDir dir = fi.dir();
-
- // we watch both the directory and the file itself. the
- // reason we watch the directory is so we can detect when
- // the file is deleted/created
-
- // we don't bother checking for dir existence before adding,
- // since there isn't an atomic way to do both at once. if
- // it turns out that the dir doesn't exist, then the
- // monitoring will just silently not work at all.
-
- watcher->addPath(dir.path());
-
- // can't watch for non-existent directory
- if(!watcher->directories().contains(dir.path()))
- {
- stop();
- return;
- }
-
- // save whether or not the file exists
- fileExisted = fi.exists();
-
- // add only if file existent
- // if no it will be added on directoryChanged signal
- if(fileExisted)
- watcher->addPath(filePath);
-
- // TODO: address race conditions and think about error
- // reporting instead of silently failing. probably this
- // will require a Qt API update.
- }
-
- void stop()
- {
- if(watcher)
- {
- delete watcher;
- delete watcher_relay;
- watcher = 0;
- watcher_relay = 0;
- }
-
- fileName.clear();
- filePath.clear();
- }
+ FileWatch *q;
+ QFileSystemWatcher *watcher;
+ QFileSystemWatcherRelay *watcher_relay;
+ QString fileName; // file (optionally w/ path) as provided by user
+ QString filePath; // absolute path of file, calculated by us
+ bool fileExisted;
+
+ Private(FileWatch *_q) : QObject(_q), q(_q), watcher(0), watcher_relay(0)
+ {
+ }
+
+ void start(const QString &_fileName)
+ {
+ fileName = _fileName;
+
+ watcher = new QFileSystemWatcher(this);
+ watcher_relay = new QFileSystemWatcherRelay(watcher, this);
+ connect(watcher_relay, SIGNAL(directoryChanged(QString)), SLOT(dir_changed(QString)));
+ connect(watcher_relay, SIGNAL(fileChanged(QString)), SLOT(file_changed(QString)));
+
+ QFileInfo fi(fileName);
+ fi.makeAbsolute();
+ filePath = fi.filePath();
+ QDir dir = fi.dir();
+
+ // we watch both the directory and the file itself. the
+ // reason we watch the directory is so we can detect when
+ // the file is deleted/created
+
+ // we don't bother checking for dir existence before adding,
+ // since there isn't an atomic way to do both at once. if
+ // it turns out that the dir doesn't exist, then the
+ // monitoring will just silently not work at all.
+
+ watcher->addPath(dir.path());
+
+ // can't watch for non-existent directory
+ if (!watcher->directories().contains(dir.path())) {
+ stop();
+ return;
+ }
+
+ // save whether or not the file exists
+ fileExisted = fi.exists();
+
+ // add only if file existent
+ // if no it will be added on directoryChanged signal
+ if (fileExisted) {
+ watcher->addPath(filePath);
+ }
+
+ // TODO: address race conditions and think about error
+ // reporting instead of silently failing. probably this
+ // will require a Qt API update.
+ }
+
+ void stop()
+ {
+ if (watcher) {
+ delete watcher;
+ delete watcher_relay;
+ watcher = 0;
+ watcher_relay = 0;
+ }
+
+ fileName.clear();
+ filePath.clear();
+ }
private slots:
- void dir_changed(const QString &path)
- {
- Q_UNUSED(path);
- QFileInfo fi(filePath);
- bool exists = fi.exists();
- if(exists && !fileExisted)
- {
- // this means the file was created. put a
- // watch on it.
- fileExisted = true;
- watcher->addPath(filePath);
- emit q->changed();
- }
- }
-
- void file_changed(const QString &path)
- {
- Q_UNUSED(path);
- QFileInfo fi(filePath);
- if (!fi.exists() && !fileExisted) {
- // Got a file changed signal on a file that does not exist
- // and is not actively watched. This happens when we
- // previously watched a file but it was deleted and after
- // the original deletion changed-signal we get another one
- // (for example because of bad signal timing). In this scenario
- // we must ignore the change as the change, whatever it may
- // have been, is of no interest to us because we don't watch
- // the file and furthermore the file does not even exist.
- return;
- } else if (!fi.exists()) {
- fileExisted = false;
- };
- emit q->changed();
- }
+ void dir_changed(const QString &path)
+ {
+ Q_UNUSED(path);
+ QFileInfo fi(filePath);
+ bool exists = fi.exists();
+ if (exists && !fileExisted) {
+ // this means the file was created. put a
+ // watch on it.
+ fileExisted = true;
+ watcher->addPath(filePath);
+ emit q->changed();
+ }
+ }
+
+ void file_changed(const QString &path)
+ {
+ Q_UNUSED(path);
+ QFileInfo fi(filePath);
+ if (!fi.exists() && !fileExisted) {
+ // Got a file changed signal on a file that does not exist
+ // and is not actively watched. This happens when we
+ // previously watched a file but it was deleted and after
+ // the original deletion changed-signal we get another one
+ // (for example because of bad signal timing). In this scenario
+ // we must ignore the change as the change, whatever it may
+ // have been, is of no interest to us because we don't watch
+ // the file and furthermore the file does not even exist.
+ return;
+ } else if (!fi.exists()) {
+ fileExisted = false;
+ };
+ emit q->changed();
+ }
};
FileWatch::FileWatch(const QString &file, QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
- d->start(file);
+ d = new Private(this);
+ d->start(file);
}
FileWatch::~FileWatch()
{
- delete d;
+ delete d;
}
QString FileWatch::fileName() const
{
- return d->fileName;
+ return d->fileName;
}
void FileWatch::setFileName(const QString &file)
{
- d->stop();
- d->start(file);
+ d->stop();
+ d->start(file);
}
}
#include "dirwatch.moc"
diff --git a/src/support/logger.cpp b/src/support/logger.cpp
index e9fd1b1e..55f18928 100644
--- a/src/support/logger.cpp
+++ b/src/support/logger.cpp
@@ -1,119 +1,113 @@
/*
* Copyright (C) 2007 Brad Hards <bradh@frogmouth.net>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_support.h"
-namespace QCA {
+namespace QCA
+{
AbstractLogDevice::AbstractLogDevice(const QString &name, QObject *parent) :
- QObject( parent ), m_name( name )
+ QObject(parent), m_name(name)
{
}
AbstractLogDevice::~AbstractLogDevice()
{}
QString AbstractLogDevice::name() const
{
- return m_name;
+ return m_name;
}
-void AbstractLogDevice::logTextMessage( const QString &message, Logger::Severity severity )
+void AbstractLogDevice::logTextMessage(const QString &message, Logger::Severity severity)
{
- Q_UNUSED( message );
- Q_UNUSED( severity );
+ Q_UNUSED(message);
+ Q_UNUSED(severity);
}
-void AbstractLogDevice::logBinaryMessage( const QByteArray &blob, Logger::Severity severity )
+void AbstractLogDevice::logBinaryMessage(const QByteArray &blob, Logger::Severity severity)
{
- Q_UNUSED( blob );
- Q_UNUSED( severity );
+ Q_UNUSED(blob);
+ Q_UNUSED(severity);
}
Logger::Logger()
{
- // d pointer?
- m_logLevel = Logger::Notice;
+ // d pointer?
+ m_logLevel = Logger::Notice;
}
Logger::~Logger()
{
- // delete d;
+ // delete d;
}
QStringList Logger::currentLogDevices() const
{
- return m_loggerNames;
+ return m_loggerNames;
}
-void Logger::registerLogDevice(AbstractLogDevice* logger)
+void Logger::registerLogDevice(AbstractLogDevice *logger)
{
- m_loggers.append( logger );
- m_loggerNames.append( logger->name() );
+ m_loggers.append(logger);
+ m_loggerNames.append(logger->name());
}
void Logger::unregisterLogDevice(const QString &loggerName)
{
- for ( int i = 0; i < m_loggers.size(); ++i )
- {
- if ( m_loggers[i]->name() == loggerName )
- {
- m_loggers.removeAt( i );
- --i; // we backstep, to make sure we check the new entry in this position.
- }
+ for (int i = 0; i < m_loggers.size(); ++i) {
+ if (m_loggers[i]->name() == loggerName) {
+ m_loggers.removeAt(i);
+ --i; // we backstep, to make sure we check the new entry in this position.
}
- for ( int i = 0; i < m_loggerNames.size(); ++i )
- {
- if ( m_loggerNames[i] == loggerName )
- {
- m_loggerNames.removeAt( i );
- --i; // we backstep, to make sure we check the new entry in this position.
- }
+ }
+ for (int i = 0; i < m_loggerNames.size(); ++i) {
+ if (m_loggerNames[i] == loggerName) {
+ m_loggerNames.removeAt(i);
+ --i; // we backstep, to make sure we check the new entry in this position.
}
+ }
}
-void Logger::setLevel (Severity level)
+void Logger::setLevel(Severity level)
{
- m_logLevel = level;
+ m_logLevel = level;
}
-void Logger::logTextMessage(const QString &message, Severity severity )
+void Logger::logTextMessage(const QString &message, Severity severity)
{
- if (severity <= level ()) {
- for ( int i = 0; i < m_loggers.size(); ++i )
- {
- m_loggers[i]->logTextMessage( message, severity );
- }
- }
+ if (severity <= level()) {
+ for (int i = 0; i < m_loggers.size(); ++i) {
+ m_loggers[i]->logTextMessage(message, severity);
+ }
+ }
}
-void Logger::logBinaryMessage(const QByteArray &blob, Severity severity )
+void Logger::logBinaryMessage(const QByteArray &blob, Severity severity)
{
- if (severity <= level ()) {
- for ( int i = 0; i < m_loggers.size(); ++i )
- {
- m_loggers[i]->logBinaryMessage( blob, severity );
- }
- }
+ if (severity <= level()) {
+ for (int i = 0; i < m_loggers.size(); ++i) {
+ m_loggers[i]->logBinaryMessage(blob, severity);
+ }
+ }
}
}
-
diff --git a/src/support/qpipe.cpp b/src/support/qpipe.cpp
index 0fe89f56..146c5d29 100644
--- a/src/support/qpipe.cpp
+++ b/src/support/qpipe.cpp
@@ -1,2174 +1,2165 @@
/*
* Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
// Note: if we ever enable the threaded backend, we need to protect:
// QPipeDevice read and bytesAvailable
// QPipeEnd finalize
// Note: we never use the return value for QPipeWriter::stop, but I don't
// think this matters much
#include "qpipe.h"
#include <stdlib.h>
#include <limits.h>
// sorry, i've added this dependency for now, but it's easy enough to take
// with you if you want qpipe independent of qca
#include "qca_safeobj.h"
#ifdef Q_OS_WIN
# include <QThread>
# include <QMutex>
# include <QWaitCondition>
# include <QTextCodec>
# include <QTextEncoder>
# include <QTextDecoder>
#else
# include <QMutex>
#endif
#ifdef Q_OS_UNIX
# include <unistd.h>
# include <fcntl.h>
# include <errno.h>
# include <sys/ioctl.h>
# include <signal.h>
# ifdef HAVE_SYS_FILIO_H
# include <sys/filio.h>
# endif
#endif
#define USE_POLL
#define CONSOLE_CHAREXPAND 5
#define PIPEWRITER_POLL 1000
#define PIPEREADER_POLL 100
#define PIPEWRITER_BLOCK 8192
#define PIPEEND_BLOCK 8192
#define PIPEEND_READBUF 16384
#define PIPEEND_READBUF_SEC 1024
-namespace QCA {
+namespace QCA
+{
#ifdef Q_OS_UNIX
// adapted from qt
Q_GLOBAL_STATIC(QMutex, ign_mutex)
static bool ign_sigpipe = false;
static void ignore_sigpipe()
{
- // Set to ignore SIGPIPE once only.
+ // Set to ignore SIGPIPE once only.
//#if QT_VERSION < 0x040400
- QMutexLocker locker(ign_mutex());
- if(!ign_sigpipe)
- {
- ign_sigpipe = true;
+ QMutexLocker locker(ign_mutex());
+ if (!ign_sigpipe) {
+ ign_sigpipe = true;
//#else
-// static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0);
-// if(atom.testAndSetRelaxed(0, 1))
-// {
+// static QBasicAtomicInt atom = Q_BASIC_ATOMIC_INITIALIZER(0);
+// if(atom.testAndSetRelaxed(0, 1))
+// {
//#endif
- struct sigaction noaction;
- memset(&noaction, 0, sizeof(noaction));
- noaction.sa_handler = SIG_IGN;
- sigaction(SIGPIPE, &noaction, 0);
- }
+ struct sigaction noaction;
+ memset(&noaction, 0, sizeof(noaction));
+ noaction.sa_handler = SIG_IGN;
+ sigaction(SIGPIPE, &noaction, 0);
+ }
}
#endif
#ifdef Q_OS_WIN
static int pipe_dword_cap_to_int(DWORD dw)
{
- if(sizeof(int) <= sizeof(DWORD))
- return (int)((dw > INT_MAX) ? INT_MAX : dw);
- else
- return (int)dw;
+ if (sizeof(int) <= sizeof(DWORD)) {
+ return (int)((dw > INT_MAX) ? INT_MAX : dw);
+ } else {
+ return (int)dw;
+ }
}
static bool pipe_dword_overflows_int(DWORD dw)
{
- if(sizeof(int) <= sizeof(DWORD))
- return (dw > INT_MAX) ? true : false;
- else
- return false;
+ if (sizeof(int) <= sizeof(DWORD)) {
+ return (dw > INT_MAX) ? true : false;
+ } else {
+ return false;
+ }
}
#endif
#ifdef Q_OS_UNIX
static int pipe_size_t_cap_to_int(size_t size)
{
- if(sizeof(int) <= sizeof(size_t))
- return (int)((size > INT_MAX) ? INT_MAX : size);
- else // maybe silly.. can int ever be larger than size_t?
- return (int)size;
+ if (sizeof(int) <= sizeof(size_t)) {
+ return (int)((size > INT_MAX) ? INT_MAX : size);
+ } else { // maybe silly.. can int ever be larger than size_t?
+ return (int)size;
+ }
}
#endif
static bool pipe_set_blocking(Q_PIPE_ID pipe, bool b)
{
#ifdef Q_OS_WIN
- DWORD flags = 0;
- if(!b)
- flags |= PIPE_NOWAIT;
- if(!SetNamedPipeHandleState(pipe, &flags, NULL, NULL))
- return false;
- return true;
+ DWORD flags = 0;
+ if (!b) {
+ flags |= PIPE_NOWAIT;
+ }
+ if (!SetNamedPipeHandleState(pipe, &flags, NULL, NULL)) {
+ return false;
+ }
+ return true;
#endif
#ifdef Q_OS_UNIX
- int flags = fcntl(pipe, F_GETFL);
- if(!b)
- flags |= O_NONBLOCK;
- else
- flags &= ~O_NONBLOCK;
- if(fcntl(pipe, F_SETFL, flags) == -1)
- return false;
- return true;
+ int flags = fcntl(pipe, F_GETFL);
+ if (!b) {
+ flags |= O_NONBLOCK;
+ } else {
+ flags &= ~O_NONBLOCK;
+ }
+ if (fcntl(pipe, F_SETFL, flags) == -1) {
+ return false;
+ }
+ return true;
#endif
}
// on windows, the pipe is closed and the new pipe is returned in newPipe
static bool pipe_set_inheritable(Q_PIPE_ID pipe, bool b, Q_PIPE_ID *newPipe = 0)
{
#ifdef Q_OS_WIN
- // windows is required to accept a new pipe id
- if(!newPipe)
- return false;
- HANDLE h;
- if(!DuplicateHandle(GetCurrentProcess(), pipe, GetCurrentProcess(), &h, 0, b, DUPLICATE_SAME_ACCESS))
- return false;
- *newPipe = h;
- return true;
+ // windows is required to accept a new pipe id
+ if (!newPipe) {
+ return false;
+ }
+ HANDLE h;
+ if (!DuplicateHandle(GetCurrentProcess(), pipe, GetCurrentProcess(), &h, 0, b, DUPLICATE_SAME_ACCESS)) {
+ return false;
+ }
+ *newPipe = h;
+ return true;
#endif
#ifdef Q_OS_UNIX
- if(newPipe)
- *newPipe = pipe;
- int flags = fcntl(pipe, F_GETFD);
- if(!b)
- flags |= FD_CLOEXEC;
- else
- flags &= ~FD_CLOEXEC;
- if(fcntl(pipe, F_SETFD, flags) == -1)
- return false;
- return true;
+ if (newPipe) {
+ *newPipe = pipe;
+ }
+ int flags = fcntl(pipe, F_GETFD);
+ if (!b) {
+ flags |= FD_CLOEXEC;
+ } else {
+ flags &= ~FD_CLOEXEC;
+ }
+ if (fcntl(pipe, F_SETFD, flags) == -1) {
+ return false;
+ }
+ return true;
#endif
}
// returns number of bytes available
static int pipe_read_avail(Q_PIPE_ID pipe)
{
- int bytesAvail = 0;
+ int bytesAvail = 0;
#ifdef Q_OS_WIN
- DWORD i = 0;
- if(PeekNamedPipe(pipe, 0, 0, 0, &i, 0))
- bytesAvail = pipe_dword_cap_to_int(i);
+ DWORD i = 0;
+ if (PeekNamedPipe(pipe, 0, 0, 0, &i, 0)) {
+ bytesAvail = pipe_dword_cap_to_int(i);
+ }
#endif
#ifdef Q_OS_UNIX
- size_t nbytes = 0;
- if(ioctl(pipe, FIONREAD, (char *)&nbytes) >= 0)
- bytesAvail = pipe_size_t_cap_to_int(nbytes);
+ size_t nbytes = 0;
+ if (ioctl(pipe, FIONREAD, (char *)&nbytes) >= 0) {
+ bytesAvail = pipe_size_t_cap_to_int(nbytes);
+ }
#endif
- return bytesAvail;
+ return bytesAvail;
}
// returns number of bytes actually read, no more than 'max'.
// -1 on error. 0 means no data, NOT EOF.
// note: even though this function looks like it can return data and EOF
// at the same time, it never actually does.
static int pipe_read(Q_PIPE_ID pipe, char *data, int max, bool *eof)
{
- int bytesRead = 0;
- if(eof)
- *eof = false;
- if(max < 1)
- return 0;
+ int bytesRead = 0;
+ if (eof) {
+ *eof = false;
+ }
+ if (max < 1) {
+ return 0;
+ }
#ifdef Q_OS_WIN
- DWORD maxread = max;
- DWORD r = 0;
- if(!ReadFile(pipe, data, maxread, &r, 0))
- {
- DWORD err = GetLastError();
- if(err == ERROR_HANDLE_EOF)
- {
- if(eof)
- *eof = true;
- }
- else if(err == ERROR_NO_DATA)
- {
- r = 0;
- }
- else
- return -1;
- }
- bytesRead = (int)r; // safe to cast, since 'max' is signed
+ DWORD maxread = max;
+ DWORD r = 0;
+ if (!ReadFile(pipe, data, maxread, &r, 0)) {
+ DWORD err = GetLastError();
+ if (err == ERROR_HANDLE_EOF) {
+ if (eof) {
+ *eof = true;
+ }
+ } else if (err == ERROR_NO_DATA) {
+ r = 0;
+ } else {
+ return -1;
+ }
+ }
+ bytesRead = (int)r; // safe to cast, since 'max' is signed
#endif
#ifdef Q_OS_UNIX
- int r = 0;
- int ret = read(pipe, data, max);
- if(ret == -1)
- {
- if(errno != EAGAIN)
- return -1;
- }
- else if(ret == 0)
- {
- if(eof)
- *eof = true;
- }
- else
- r = ret;
-
- bytesRead = r;
-#endif
- return bytesRead;
+ int r = 0;
+ int ret = read(pipe, data, max);
+ if (ret == -1) {
+ if (errno != EAGAIN) {
+ return -1;
+ }
+ } else if (ret == 0) {
+ if (eof) {
+ *eof = true;
+ }
+ } else {
+ r = ret;
+ }
+
+ bytesRead = r;
+#endif
+ return bytesRead;
}
// returns number of bytes actually written.
// for blocking pipes, this should always be 'size'.
// -1 on error.
static int pipe_write(Q_PIPE_ID pipe, const char *data, int size)
{
#ifdef Q_OS_WIN
- DWORD written;
- if(!WriteFile(pipe, data, size, &written, 0))
- return -1;
- return (int)written; // safe to cast, since 'size' is signed
+ DWORD written;
+ if (!WriteFile(pipe, data, size, &written, 0)) {
+ return -1;
+ }
+ return (int)written; // safe to cast, since 'size' is signed
#endif
#ifdef Q_OS_UNIX
- ignore_sigpipe();
- int r = 0;
- int ret = write(pipe, data, size);
- if(ret == -1)
- {
- if(errno != EAGAIN)
- return -1;
- }
- else
- r = ret;
- return r;
+ ignore_sigpipe();
+ int r = 0;
+ int ret = write(pipe, data, size);
+ if (ret == -1) {
+ if (errno != EAGAIN) {
+ return -1;
+ }
+ } else {
+ r = ret;
+ }
+ return r;
#endif
}
// Windows Console functions
#ifdef Q_OS_WIN
static bool pipe_is_a_console(Q_PIPE_ID pipe)
{
- DWORD mode;
- if(GetConsoleMode(pipe, &mode))
- return true;
- return false;
+ DWORD mode;
+ if (GetConsoleMode(pipe, &mode)) {
+ return true;
+ }
+ return false;
}
// returns the number of keypress events in the console input queue,
// or -1 if there is an error (don't forget this!!)
static int pipe_read_avail_console(Q_PIPE_ID pipe)
{
- DWORD count, i;
- INPUT_RECORD *rec;
- int n, icount, total;
+ DWORD count, i;
+ INPUT_RECORD *rec;
+ int n, icount, total;
- // how many events are there?
- if(!GetNumberOfConsoleInputEvents(pipe, &count))
- return -1;
+ // how many events are there?
+ if (!GetNumberOfConsoleInputEvents(pipe, &count)) {
+ return -1;
+ }
- // peek them all
- rec = (INPUT_RECORD *)malloc(count * sizeof(INPUT_RECORD));
- BOOL ret;
+ // peek them all
+ rec = (INPUT_RECORD *)malloc(count * sizeof(INPUT_RECORD));
+ BOOL ret;
#if QT_VERSION >= 0x050000
- ret = PeekConsoleInputW(pipe, rec, count, &i);
+ ret = PeekConsoleInputW(pipe, rec, count, &i);
#else
- QT_WA(
- ret = PeekConsoleInputW(pipe, rec, count, &i);
- ,
- ret = PeekConsoleInputA(pipe, rec, count, &i);
- )
-#endif
- if(!ret)
- {
- free(rec);
- return -1;
- }
-
- icount = pipe_dword_cap_to_int(i); // process only the amount returned
-
- // see which ones are normal keypress events
- total = 0;
- for(n = 0; n < icount; ++n)
- {
- if(rec[n].EventType == KEY_EVENT)
- {
- KEY_EVENT_RECORD *ke = &rec[n].Event.KeyEvent;
- if(ke->bKeyDown && ke->uChar.AsciiChar != 0)
- total += ke->wRepeatCount;
- }
- }
-
- free(rec);
- return total;
+ QT_WA(
+ ret = PeekConsoleInputW(pipe, rec, count, &i);
+ ,
+ ret = PeekConsoleInputA(pipe, rec, count, &i);
+ )
+#endif
+ if (!ret) {
+ free(rec);
+ return -1;
+ }
+
+ icount = pipe_dword_cap_to_int(i); // process only the amount returned
+
+ // see which ones are normal keypress events
+ total = 0;
+ for (n = 0; n < icount; ++n) {
+ if (rec[n].EventType == KEY_EVENT) {
+ KEY_EVENT_RECORD *ke = &rec[n].Event.KeyEvent;
+ if (ke->bKeyDown && ke->uChar.AsciiChar != 0) {
+ total += ke->wRepeatCount;
+ }
+ }
+ }
+
+ free(rec);
+ return total;
}
// pass dec to keep a long-running decoder, else 0
static int pipe_read_console(Q_PIPE_ID pipe, ushort *data, int max, bool *eof, QTextDecoder *dec = 0)
{
- int n, size, count;
- bool own_decoder;
-
- if(eof)
- *eof = false;
- if(max < 1)
- return 0;
-
- count = pipe_read_avail_console(pipe);
- if(count == -1)
- return -1;
- if(count == 0)
- return 0;
-
- if(dec)
- {
- own_decoder = false;
- }
- else
- {
+ int n, size, count;
+ bool own_decoder;
+
+ if (eof) {
+ *eof = false;
+ }
+ if (max < 1) {
+ return 0;
+ }
+
+ count = pipe_read_avail_console(pipe);
+ if (count == -1) {
+ return -1;
+ }
+ if (count == 0) {
+ return 0;
+ }
+
+ if (dec) {
+ own_decoder = false;
+ } else {
#if QT_VERSION >= 0x050000
- dec = 0;
+ dec = 0;
#else
- QT_WA(
- dec = 0;
- ,
- dec = QTextCodec::codecForLocale()->makeDecoder();
- )
-#endif
- own_decoder = true;
- }
-
- size = 0;
- for(n = 0; n < count && size < max; ++n)
- {
- bool use_uni = true;
- quint16 uni = 0;
- quint8 ansi = 0;
-
- BOOL ret;
- DWORD i;
+ QT_WA(
+ dec = 0;
+ ,
+ dec = QTextCodec::codecForLocale()->makeDecoder();
+ )
+#endif
+ own_decoder = true;
+ }
+
+ size = 0;
+ for (n = 0; n < count && size < max; ++n) {
+ bool use_uni = true;
+ quint16 uni = 0;
+ quint8 ansi = 0;
+
+ BOOL ret;
+ DWORD i;
#if QT_VERSION >= 0x050000
- ret = ReadConsoleW(pipe, &uni, 1, &i, NULL);
+ ret = ReadConsoleW(pipe, &uni, 1, &i, NULL);
#else
- QT_WA(
- ret = ReadConsoleW(pipe, &uni, 1, &i, NULL);
- ,
- ret = ReadConsoleA(pipe, &ansi, 1, &i, NULL);
- use_uni = false;
- )
-#endif
- if(!ret)
- {
- // if the first read is an error, then report error
- if(n == 0)
- {
- delete dec;
- return -1;
- }
- // if we have some data, don't count this as an error.
- // we'll probably get it again next time around...
- else
- break;
- }
-
- QString substr;
- if(use_uni)
- substr = QChar(uni);
- else
- substr = dec->toUnicode((const char *)&ansi, 1);
-
- for(int k = 0; k < substr.length() && size < max; ++k)
- {
- QChar c = substr[k];
- if(c == QChar(0x1A)) // EOF?
- {
- if(eof)
- *eof = true;
- break;
- }
- data[size++] = substr[k].unicode();
- }
- }
- if(own_decoder)
- delete dec;
-
- return size;
+ QT_WA(
+ ret = ReadConsoleW(pipe, &uni, 1, &i, NULL);
+ ,
+ ret = ReadConsoleA(pipe, &ansi, 1, &i, NULL);
+ use_uni = false;
+ )
+#endif
+ if (!ret) {
+ // if the first read is an error, then report error
+ if (n == 0) {
+ delete dec;
+ return -1;
+ }
+ // if we have some data, don't count this as an error.
+ // we'll probably get it again next time around...
+ else {
+ break;
+ }
+ }
+
+ QString substr;
+ if (use_uni) {
+ substr = QChar(uni);
+ } else {
+ substr = dec->toUnicode((const char *)&ansi, 1);
+ }
+
+ for (int k = 0; k < substr.length() && size < max; ++k) {
+ QChar c = substr[k];
+ if (c == QChar(0x1A)) { // EOF?
+ if (eof) {
+ *eof = true;
+ }
+ break;
+ }
+ data[size++] = substr[k].unicode();
+ }
+ }
+ if (own_decoder) {
+ delete dec;
+ }
+
+ return size;
}
static int pipe_write_console(Q_PIPE_ID pipe, const ushort *data, int size)
{
- DWORD i;
- BOOL ret;
+ DWORD i;
+ BOOL ret;
#if QT_VERSION >= 0x050000
- ret = WriteConsoleW(pipe, data, size, &i, NULL);
+ ret = WriteConsoleW(pipe, data, size, &i, NULL);
#else
- QT_WA(
- ret = WriteConsoleW(pipe, data, size, &i, NULL);
- ,
- // Note: we lose security by converting to QString here, but
- // who really cares if we're writing to a *display* ? :)
- QByteArray out = QString::fromUtf16(data, size).toLocal8Bit();
- ret = WriteConsoleA(pipe, out.data(), out.size(), &i, NULL);
- if(ret)
- {
- // convert number of bytes to number of unicode chars
- i = (DWORD)QString::fromLocal8Bit(out.mid(0, i)).length();
- if(pipe_dword_overflows_int(i))
- return -1;
- }
- )
-#endif
- if(!ret)
- return -1;
- return (int)i; // safe to cast since 'size' is signed
+ QT_WA(
+ ret = WriteConsoleW(pipe, data, size, &i, NULL);
+ ,
+ // Note: we lose security by converting to QString here, but
+ // who really cares if we're writing to a *display* ? :)
+ QByteArray out = QString::fromUtf16(data, size).toLocal8Bit();
+ ret = WriteConsoleA(pipe, out.data(), out.size(), &i, NULL);
+ if (ret) {
+ // convert number of bytes to number of unicode chars
+ i = (DWORD)QString::fromLocal8Bit(out.mid(0, i)).length();
+ if (pipe_dword_overflows_int(i)) {
+ return -1;
+ }
+ }
+ )
+#endif
+ if (!ret) {
+ return -1;
+ }
+ return (int)i; // safe to cast since 'size' is signed
}
#endif
#ifdef Q_OS_WIN
// Here is the multi-backend stuff for windows. QPipeWriter and QPipeReader
// define a common interface, and then subclasses (like QPipeWriterThread)
// are used by QPipeDevice. The base classes inherit from QThread, even
// if threads aren't used, so that I can define signals without dealing
// with multiple QObject inheritance in the thread subclasses (it is also
// possible that I'm missing something obvious and don't need to do this).
// Note:
// QPipeWriterThread and QPipeReaderThread require the pipes to be in
// blocking mode. QPipeWriterPoll and QPipeReaderPoll require the pipes
// to be in non-blocking mode.
//----------------------------------------------------------------------------
// QPipeWriter
//----------------------------------------------------------------------------
class QPipeWriter : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- QPipeWriter(QObject *parent = 0) : QThread(parent)
- {
- }
+ QPipeWriter(QObject *parent = 0) : QThread(parent)
+ {
+ }
- virtual ~QPipeWriter()
- {
- }
+ virtual ~QPipeWriter()
+ {
+ }
- // start
- virtual void start() = 0;
+ // start
+ virtual void start() = 0;
- // stop, and return number of bytes written so far
- virtual int stop() = 0;
+ // stop, and return number of bytes written so far
+ virtual int stop() = 0;
- // data pointer needs to remain until canWrite is emitted
- virtual int write(const char *data, int size) = 0;
+ // data pointer needs to remain until canWrite is emitted
+ virtual int write(const char *data, int size) = 0;
signals:
- // result values:
- // = 0 : success
- // = -1 : error
- void canWrite(int result, int bytesWritten);
+ // result values:
+ // = 0 : success
+ // = -1 : error
+ void canWrite(int result, int bytesWritten);
protected:
- virtual void run()
- {
- // implement a default to satisfy the polling subclass
- }
+ virtual void run()
+ {
+ // implement a default to satisfy the polling subclass
+ }
};
//----------------------------------------------------------------------------
// QPipeReader
//----------------------------------------------------------------------------
class QPipeReader : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- QPipeReader(QObject *parent = 0) : QThread(parent)
- {
- }
+ QPipeReader(QObject *parent = 0) : QThread(parent)
+ {
+ }
- virtual ~QPipeReader()
- {
- }
+ virtual ~QPipeReader()
+ {
+ }
- // start
- virtual void start() = 0;
+ // start
+ virtual void start() = 0;
- // to be called after every read
- virtual void resume() = 0;
+ // to be called after every read
+ virtual void resume() = 0;
signals:
- // result values:
- // >= 0 : readAhead
- // = -1 : atEnd
- // = -2 : atError
- // = -3 : data available, but no readAhead
- void canRead(int result);
+ // result values:
+ // >= 0 : readAhead
+ // = -1 : atEnd
+ // = -2 : atError
+ // = -3 : data available, but no readAhead
+ void canRead(int result);
protected:
- virtual void run()
- {
- // implement a default to satisfy the polling subclass
- }
+ virtual void run()
+ {
+ // implement a default to satisfy the polling subclass
+ }
};
//----------------------------------------------------------------------------
// QPipeWriterThread
//----------------------------------------------------------------------------
class QPipeWriterThread : public QPipeWriter
{
- Q_OBJECT
+ Q_OBJECT
public:
- Q_PIPE_ID pipe;
- QMutex m;
- QWaitCondition w;
- bool do_quit;
- const char *data;
- int size;
-
- QPipeWriterThread(Q_PIPE_ID id, QObject *parent = 0) : QPipeWriter(parent)
- {
- do_quit = false;
- data = 0;
- connect(this, SIGNAL(canWrite_p(int, int)), SIGNAL(canWrite(int, int)));
- DuplicateHandle(GetCurrentProcess(), id, GetCurrentProcess(), &pipe, 0, false, DUPLICATE_SAME_ACCESS);
- }
-
- virtual ~QPipeWriterThread()
- {
- stop();
- CloseHandle(pipe);
- }
-
- virtual void start()
- {
- pipe_set_blocking(pipe, true);
- QThread::start();
- }
-
- virtual int stop()
- {
- if(isRunning())
- {
- m.lock();
- do_quit = true;
- w.wakeOne();
- m.unlock();
- if(!wait(100))
- terminate();
- do_quit = false;
- data = 0;
- }
- return size;
- }
-
- virtual int write(const char *_data, int _size)
- {
- if(!isRunning())
- return -1;
-
- QMutexLocker locker(&m);
- if(data)
- return 0;
-
- data = _data;
- size = _size;
- w.wakeOne();
- return _size;
- }
+ Q_PIPE_ID pipe;
+ QMutex m;
+ QWaitCondition w;
+ bool do_quit;
+ const char *data;
+ int size;
+
+ QPipeWriterThread(Q_PIPE_ID id, QObject *parent = 0) : QPipeWriter(parent)
+ {
+ do_quit = false;
+ data = 0;
+ connect(this, SIGNAL(canWrite_p(int,int)), SIGNAL(canWrite(int,int)));
+ DuplicateHandle(GetCurrentProcess(), id, GetCurrentProcess(), &pipe, 0, false, DUPLICATE_SAME_ACCESS);
+ }
+
+ virtual ~QPipeWriterThread()
+ {
+ stop();
+ CloseHandle(pipe);
+ }
+
+ virtual void start()
+ {
+ pipe_set_blocking(pipe, true);
+ QThread::start();
+ }
+
+ virtual int stop()
+ {
+ if (isRunning()) {
+ m.lock();
+ do_quit = true;
+ w.wakeOne();
+ m.unlock();
+ if (!wait(100)) {
+ terminate();
+ }
+ do_quit = false;
+ data = 0;
+ }
+ return size;
+ }
+
+ virtual int write(const char *_data, int _size)
+ {
+ if (!isRunning()) {
+ return -1;
+ }
+
+ QMutexLocker locker(&m);
+ if (data) {
+ return 0;
+ }
+
+ data = _data;
+ size = _size;
+ w.wakeOne();
+ return _size;
+ }
protected:
- virtual void run()
- {
- while(1)
- {
- m.lock();
+ virtual void run()
+ {
+ while (1) {
+ m.lock();
- while(!data && !do_quit)
- w.wait(&m);
+ while (!data && !do_quit) {
+ w.wait(&m);
+ }
- if(do_quit)
- {
- m.unlock();
- break;
- }
+ if (do_quit) {
+ m.unlock();
+ break;
+ }
- const char *p = data;
- int len = size;
+ const char *p = data;
+ int len = size;
- m.unlock();
+ m.unlock();
- int ret = internalWrite(p, len);
+ int ret = internalWrite(p, len);
- m.lock();
- data = 0;
- size = ret;
- m.unlock();
+ m.lock();
+ data = 0;
+ size = ret;
+ m.unlock();
- emit canWrite_p(ret < len ? -1 : 0, ret);
- }
- }
+ emit canWrite_p(ret < len ? -1 : 0, ret);
+ }
+ }
private:
- // attempts to write len bytes. value returned is number of bytes written.
- // any return value less than len means a write error was encountered
- int internalWrite(const char *p, int len)
- {
- int total = 0;
- while(total < len)
- {
- m.lock();
- if(do_quit)
- {
- m.unlock();
- return 0;
- }
- m.unlock();
-
- int ret = pipe_write(pipe, p + total, qMin(PIPEWRITER_BLOCK, len - total));
- if(ret == -1)
- {
- // from qt, don't know why
- if(GetLastError() == 0xE8) // NT_STATUS_INVALID_USER_BUFFER
- {
- // give the os a rest
- msleep(100);
- continue;
- }
-
- // on any other error, end thread
- return total;
- }
- total += ret;
- }
- return total;
- }
+ // attempts to write len bytes. value returned is number of bytes written.
+ // any return value less than len means a write error was encountered
+ int internalWrite(const char *p, int len)
+ {
+ int total = 0;
+ while (total < len) {
+ m.lock();
+ if (do_quit) {
+ m.unlock();
+ return 0;
+ }
+ m.unlock();
+
+ int ret = pipe_write(pipe, p + total, qMin(PIPEWRITER_BLOCK, len - total));
+ if (ret == -1) {
+ // from qt, don't know why
+ if (GetLastError() == 0xE8) { // NT_STATUS_INVALID_USER_BUFFER
+ // give the os a rest
+ msleep(100);
+ continue;
+ }
+
+ // on any other error, end thread
+ return total;
+ }
+ total += ret;
+ }
+ return total;
+ }
signals:
- void canWrite_p(int result, int bytesWritten);
+ void canWrite_p(int result, int bytesWritten);
};
//----------------------------------------------------------------------------
// QPipeWriterPoll
//----------------------------------------------------------------------------
class QPipeWriterPoll : public QPipeWriter
{
- Q_OBJECT
+ Q_OBJECT
public:
- Q_PIPE_ID pipe;
- const char *data;
- int size;
- SafeTimer timer;
- int total;
-
- QPipeWriterPoll(Q_PIPE_ID id, QObject *parent = 0) : QPipeWriter(parent), timer(this)
- {
- pipe = id;
- data = 0;
- connect(&timer, SIGNAL(timeout()), SLOT(tryNextWrite()));
- }
-
- virtual ~QPipeWriterPoll()
- {
- }
-
- virtual void start()
- {
- pipe_set_blocking(pipe, false);
- }
-
- // return number of bytes written
- virtual int stop()
- {
- timer.stop();
- data = 0;
- return total;
- }
-
- // data pointer needs to remain until canWrite is emitted
- virtual int write(const char *_data, int _size)
- {
- total = 0;
- data = _data;
- size = _size;
- timer.start(0); // write at next event loop
- return _size;
- }
+ Q_PIPE_ID pipe;
+ const char *data;
+ int size;
+ SafeTimer timer;
+ int total;
+
+ QPipeWriterPoll(Q_PIPE_ID id, QObject *parent = 0) : QPipeWriter(parent), timer(this)
+ {
+ pipe = id;
+ data = 0;
+ connect(&timer, SIGNAL(timeout()), SLOT(tryNextWrite()));
+ }
+
+ virtual ~QPipeWriterPoll()
+ {
+ }
+
+ virtual void start()
+ {
+ pipe_set_blocking(pipe, false);
+ }
+
+ // return number of bytes written
+ virtual int stop()
+ {
+ timer.stop();
+ data = 0;
+ return total;
+ }
+
+ // data pointer needs to remain until canWrite is emitted
+ virtual int write(const char *_data, int _size)
+ {
+ total = 0;
+ data = _data;
+ size = _size;
+ timer.start(0); // write at next event loop
+ return _size;
+ }
private slots:
- void tryNextWrite()
- {
- int written = pipe_write(pipe, data + total, size - total);
- bool error = false;
- if(written == -1)
- {
- error = true;
- written = 0; // no bytes written on error
-
- // from qt, they don't count it as fatal
- if(GetLastError() == 0xE8) // NT_STATUS_INVALID_USER_BUFFER
- error = false;
- }
-
- total += written;
- if(error || total == size)
- {
- timer.stop();
- data = 0;
- emit canWrite(error ? -1 : 0, total);
- return;
- }
-
- timer.setInterval(PIPEWRITER_POLL);
- }
+ void tryNextWrite()
+ {
+ int written = pipe_write(pipe, data + total, size - total);
+ bool error = false;
+ if (written == -1) {
+ error = true;
+ written = 0; // no bytes written on error
+
+ // from qt, they don't count it as fatal
+ if (GetLastError() == 0xE8) { // NT_STATUS_INVALID_USER_BUFFER
+ error = false;
+ }
+ }
+
+ total += written;
+ if (error || total == size) {
+ timer.stop();
+ data = 0;
+ emit canWrite(error ? -1 : 0, total);
+ return;
+ }
+
+ timer.setInterval(PIPEWRITER_POLL);
+ }
};
//----------------------------------------------------------------------------
// QPipeReaderThread
//----------------------------------------------------------------------------
class QPipeReaderThread : public QPipeReader
{
- Q_OBJECT
+ Q_OBJECT
public:
- Q_PIPE_ID pipe;
- QMutex m;
- QWaitCondition w;
- bool do_quit, active;
-
- QPipeReaderThread(Q_PIPE_ID id, QObject *parent = 0) : QPipeReader(parent)
- {
- do_quit = false;
- active = true;
- connect(this, SIGNAL(canRead_p(int)), SIGNAL(canRead(int)));
- DuplicateHandle(GetCurrentProcess(), id, GetCurrentProcess(), &pipe, 0, false, DUPLICATE_SAME_ACCESS);
- }
-
- virtual ~QPipeReaderThread()
- {
- if(isRunning())
- {
- m.lock();
- do_quit = true;
- w.wakeOne();
- m.unlock();
- if(!wait(100))
- terminate();
- }
- CloseHandle(pipe);
- }
-
- virtual void start()
- {
- pipe_set_blocking(pipe, true);
- QThread::start();
- }
-
- virtual void resume()
- {
- QMutexLocker locker(&m);
- pipe_set_blocking(pipe, true);
- active = true;
- w.wakeOne();
- }
+ Q_PIPE_ID pipe;
+ QMutex m;
+ QWaitCondition w;
+ bool do_quit, active;
+
+ QPipeReaderThread(Q_PIPE_ID id, QObject *parent = 0) : QPipeReader(parent)
+ {
+ do_quit = false;
+ active = true;
+ connect(this, SIGNAL(canRead_p(int)), SIGNAL(canRead(int)));
+ DuplicateHandle(GetCurrentProcess(), id, GetCurrentProcess(), &pipe, 0, false, DUPLICATE_SAME_ACCESS);
+ }
+
+ virtual ~QPipeReaderThread()
+ {
+ if (isRunning()) {
+ m.lock();
+ do_quit = true;
+ w.wakeOne();
+ m.unlock();
+ if (!wait(100)) {
+ terminate();
+ }
+ }
+ CloseHandle(pipe);
+ }
+
+ virtual void start()
+ {
+ pipe_set_blocking(pipe, true);
+ QThread::start();
+ }
+
+ virtual void resume()
+ {
+ QMutexLocker locker(&m);
+ pipe_set_blocking(pipe, true);
+ active = true;
+ w.wakeOne();
+ }
protected:
- virtual void run()
- {
- while(1)
- {
- m.lock();
-
- while(!active && !do_quit)
- w.wait(&m);
-
- if(do_quit)
- {
- m.unlock();
- break;
- }
-
- m.unlock();
-
- while(1)
- {
- unsigned char c;
- bool done;
- int ret = pipe_read(pipe, (char *)&c, 1, &done);
- if(done || ret != 0) // eof, error, or data?
- {
- int result;
-
- if(done) // we got EOF?
- result = -1;
- else if(ret == -1) // we got an error?
- result = -2;
- else if(ret >= 1) // we got some data?? queue it
- result = c;
- else // will never happen
- result = -2;
-
- m.lock();
- active = false;
- pipe_set_blocking(pipe, false);
- m.unlock();
-
- emit canRead_p(result);
- break;
- }
- }
- }
- }
+ virtual void run()
+ {
+ while (1) {
+ m.lock();
+
+ while (!active && !do_quit) {
+ w.wait(&m);
+ }
+
+ if (do_quit) {
+ m.unlock();
+ break;
+ }
+
+ m.unlock();
+
+ while (1) {
+ unsigned char c;
+ bool done;
+ int ret = pipe_read(pipe, (char *)&c, 1, &done);
+ if (done || ret != 0) { // eof, error, or data?
+ int result;
+
+ if (done) { // we got EOF?
+ result = -1;
+ } else if (ret == -1) { // we got an error?
+ result = -2;
+ } else if (ret >= 1) { // we got some data?? queue it
+ result = c;
+ } else { // will never happen
+ result = -2;
+ }
+
+ m.lock();
+ active = false;
+ pipe_set_blocking(pipe, false);
+ m.unlock();
+
+ emit canRead_p(result);
+ break;
+ }
+ }
+ }
+ }
signals:
- void canRead_p(int result);
+ void canRead_p(int result);
};
//----------------------------------------------------------------------------
// QPipeReaderPoll
//----------------------------------------------------------------------------
class QPipeReaderPoll : public QPipeReader
{
- Q_OBJECT
+ Q_OBJECT
public:
- Q_PIPE_ID pipe;
- SafeTimer timer;
- bool consoleMode;
-
- QPipeReaderPoll(Q_PIPE_ID id, QObject *parent = 0) : QPipeReader(parent), timer(this)
- {
- pipe = id;
- connect(&timer, SIGNAL(timeout()), SLOT(tryRead()));
- }
-
- virtual ~QPipeReaderPoll()
- {
- }
-
- virtual void start()
- {
- pipe_set_blocking(pipe, false);
- consoleMode = pipe_is_a_console(pipe);
- resume();
- }
-
- virtual void resume()
- {
- timer.start(0);
- }
+ Q_PIPE_ID pipe;
+ SafeTimer timer;
+ bool consoleMode;
+
+ QPipeReaderPoll(Q_PIPE_ID id, QObject *parent = 0) : QPipeReader(parent), timer(this)
+ {
+ pipe = id;
+ connect(&timer, SIGNAL(timeout()), SLOT(tryRead()));
+ }
+
+ virtual ~QPipeReaderPoll()
+ {
+ }
+
+ virtual void start()
+ {
+ pipe_set_blocking(pipe, false);
+ consoleMode = pipe_is_a_console(pipe);
+ resume();
+ }
+
+ virtual void resume()
+ {
+ timer.start(0);
+ }
private slots:
- void tryRead()
- {
- if(consoleMode)
- tryReadConsole();
- else
- tryReadPipe();
- }
+ void tryRead()
+ {
+ if (consoleMode) {
+ tryReadConsole();
+ } else {
+ tryReadPipe();
+ }
+ }
private:
- void tryReadPipe()
- {
- // is there data available for reading? if so, signal.
- int bytes = pipe_read_avail(pipe);
- if(bytes > 0)
- {
- timer.stop();
- emit canRead(-3); // no readAhead
- return;
- }
-
- // no data available? probe for EOF/error
- unsigned char c;
- bool done;
- int ret = pipe_read(pipe, (char *)&c, 1, &done);
- if(done || ret != 0) // eof, error, or data?
- {
- int result;
-
- if(done) // we got EOF?
- result = -1;
- else if(ret == -1) // we got an error?
- result = -2;
- else if(ret >= 1) // we got some data?? queue it
- result = c;
- else // will never happen
- result = -2;
-
- timer.stop();
- emit canRead(result);
- return;
- }
-
- timer.setInterval(PIPEREADER_POLL);
- }
-
- void tryReadConsole()
- {
- // is there data available for reading? if so, signal.
- int count = pipe_read_avail_console(pipe);
- if(count > 0)
- {
- timer.stop();
- emit canRead(-3); // no readAhead
- return;
- }
-
- timer.setInterval(PIPEREADER_POLL);
- }
+ void tryReadPipe()
+ {
+ // is there data available for reading? if so, signal.
+ int bytes = pipe_read_avail(pipe);
+ if (bytes > 0) {
+ timer.stop();
+ emit canRead(-3); // no readAhead
+ return;
+ }
+
+ // no data available? probe for EOF/error
+ unsigned char c;
+ bool done;
+ int ret = pipe_read(pipe, (char *)&c, 1, &done);
+ if (done || ret != 0) { // eof, error, or data?
+ int result;
+
+ if (done) { // we got EOF?
+ result = -1;
+ } else if (ret == -1) { // we got an error?
+ result = -2;
+ } else if (ret >= 1) { // we got some data?? queue it
+ result = c;
+ } else { // will never happen
+ result = -2;
+ }
+
+ timer.stop();
+ emit canRead(result);
+ return;
+ }
+
+ timer.setInterval(PIPEREADER_POLL);
+ }
+
+ void tryReadConsole()
+ {
+ // is there data available for reading? if so, signal.
+ int count = pipe_read_avail_console(pipe);
+ if (count > 0) {
+ timer.stop();
+ emit canRead(-3); // no readAhead
+ return;
+ }
+
+ timer.setInterval(PIPEREADER_POLL);
+ }
};
// end of windows pipe writer/reader implementations
#endif
//----------------------------------------------------------------------------
// QPipeDevice
//----------------------------------------------------------------------------
class QPipeDevice::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- QPipeDevice *q;
- Q_PIPE_ID pipe;
- QPipeDevice::Type type;
- bool enabled;
- bool blockReadNotify;
- bool canWrite;
- int writeResult;
- int lastTaken, lastWritten;
+ QPipeDevice *q;
+ Q_PIPE_ID pipe;
+ QPipeDevice::Type type;
+ bool enabled;
+ bool blockReadNotify;
+ bool canWrite;
+ int writeResult;
+ int lastTaken, lastWritten;
#ifdef Q_OS_WIN
- bool atEnd, atError, forceNotify;
- int readAhead;
- SafeTimer *readTimer;
- QTextDecoder *dec;
- bool consoleMode;
- QPipeWriter *pipeWriter;
- QPipeReader *pipeReader;
+ bool atEnd, atError, forceNotify;
+ int readAhead;
+ SafeTimer *readTimer;
+ QTextDecoder *dec;
+ bool consoleMode;
+ QPipeWriter *pipeWriter;
+ QPipeReader *pipeReader;
#endif
#ifdef Q_OS_UNIX
- SafeSocketNotifier *sn_read, *sn_write;
+ SafeSocketNotifier *sn_read, *sn_write;
#endif
- Private(QPipeDevice *_q) : QObject(_q), q(_q), pipe(INVALID_Q_PIPE_ID)
- {
+ Private(QPipeDevice *_q) : QObject(_q), q(_q), pipe(INVALID_Q_PIPE_ID)
+ {
#ifdef Q_OS_WIN
- readTimer = 0;
- pipeWriter = 0;
- pipeReader = 0;
- dec = 0;
+ readTimer = 0;
+ pipeWriter = 0;
+ pipeReader = 0;
+ dec = 0;
#endif
#ifdef Q_OS_UNIX
- sn_read = 0;
- sn_write = 0;
+ sn_read = 0;
+ sn_write = 0;
#endif
- }
+ }
- ~Private()
- {
- reset();
- }
+ ~Private()
+ {
+ reset();
+ }
- void reset()
- {
+ void reset()
+ {
#ifdef Q_OS_WIN
- atEnd = false;
- atError = false;
- forceNotify = false;
- readAhead = -1;
- delete readTimer;
- readTimer = 0;
- delete pipeWriter;
- pipeWriter = 0;
- delete pipeReader;
- pipeReader = 0;
- delete dec;
- dec = 0;
- consoleMode = false;
+ atEnd = false;
+ atError = false;
+ forceNotify = false;
+ readAhead = -1;
+ delete readTimer;
+ readTimer = 0;
+ delete pipeWriter;
+ pipeWriter = 0;
+ delete pipeReader;
+ pipeReader = 0;
+ delete dec;
+ dec = 0;
+ consoleMode = false;
#endif
#ifdef Q_OS_UNIX
- delete sn_read;
- sn_read = 0;
- delete sn_write;
- sn_write = 0;
+ delete sn_read;
+ sn_read = 0;
+ delete sn_write;
+ sn_write = 0;
#endif
- if(pipe != INVALID_Q_PIPE_ID)
- {
+ if (pipe != INVALID_Q_PIPE_ID) {
#ifdef Q_OS_WIN
- CloseHandle(pipe);
+ CloseHandle(pipe);
#endif
#ifdef Q_OS_UNIX
- ::close(pipe);
+ ::close(pipe);
#endif
- pipe = INVALID_Q_PIPE_ID;
- }
+ pipe = INVALID_Q_PIPE_ID;
+ }
- enabled = false;
- blockReadNotify = false;
- canWrite = true;
- writeResult = -1;
- }
+ enabled = false;
+ blockReadNotify = false;
+ canWrite = true;
+ writeResult = -1;
+ }
- void setup(Q_PIPE_ID id, QPipeDevice::Type _type)
- {
- pipe = id;
- type = _type;
- }
+ void setup(Q_PIPE_ID id, QPipeDevice::Type _type)
+ {
+ pipe = id;
+ type = _type;
+ }
- void enable()
- {
- if(enabled)
- return;
+ void enable()
+ {
+ if (enabled) {
+ return;
+ }
- enabled = true;
+ enabled = true;
- if(type == QPipeDevice::Read)
- {
+ if (type == QPipeDevice::Read) {
#ifdef Q_OS_WIN
- // for windows, the blocking mode is chosen by the QPipeReader
+ // for windows, the blocking mode is chosen by the QPipeReader
- // console might need a decoder
- if(consoleMode)
- {
+ // console might need a decoder
+ if (consoleMode) {
#if QT_VERSION >= 0x050000
- dec = 0;
+ dec = 0;
#else
- QT_WA(
- dec = 0;
- ,
- dec = QTextCodec::codecForLocale()->makeDecoder();
- )
+ QT_WA(
+ dec = 0;
+ ,
+ dec = QTextCodec::codecForLocale()->makeDecoder();
+ )
#endif
- }
+ }
- // pipe reader
+ // pipe reader
#ifdef USE_POLL
- pipeReader = new QPipeReaderPoll(pipe, this);
+ pipeReader = new QPipeReaderPoll(pipe, this);
#else
- // console always polls, no matter what
- if(consoleMode)
- pipeReader = new QPipeReaderPoll(pipe, this);
- else
- pipeReader = new QPipeReaderThread(pipe, this);
+ // console always polls, no matter what
+ if (consoleMode) {
+ pipeReader = new QPipeReaderPoll(pipe, this);
+ } else {
+ pipeReader = new QPipeReaderThread(pipe, this);
+ }
#endif
- connect(pipeReader, SIGNAL(canRead(int)), this, SLOT(pr_canRead(int)));
- pipeReader->start();
+ connect(pipeReader, SIGNAL(canRead(int)), this, SLOT(pr_canRead(int)));
+ pipeReader->start();
- // polling timer
- readTimer = new SafeTimer(this);
- connect(readTimer, SIGNAL(timeout()), SLOT(t_timeout()));
+ // polling timer
+ readTimer = new SafeTimer(this);
+ connect(readTimer, SIGNAL(timeout()), SLOT(t_timeout()));
- // updated: now that we have pipeReader, this no longer
- // polls for data. it only does delayed singleshot
- // notifications.
- readTimer->setSingleShot(true);
+ // updated: now that we have pipeReader, this no longer
+ // polls for data. it only does delayed singleshot
+ // notifications.
+ readTimer->setSingleShot(true);
#endif
#ifdef Q_OS_UNIX
- pipe_set_blocking(pipe, false);
+ pipe_set_blocking(pipe, false);
- // socket notifier
- sn_read = new SafeSocketNotifier(pipe, QSocketNotifier::Read, this);
- connect(sn_read, SIGNAL(activated(int)), SLOT(sn_read_activated(int)));
+ // socket notifier
+ sn_read = new SafeSocketNotifier(pipe, QSocketNotifier::Read, this);
+ connect(sn_read, SIGNAL(activated(int)), SLOT(sn_read_activated(int)));
#endif
- }
- else
- {
- // for windows, the blocking mode is chosen by the QPipeWriter
+ } else {
+ // for windows, the blocking mode is chosen by the QPipeWriter
#ifdef Q_OS_UNIX
- pipe_set_blocking(pipe, false);
+ pipe_set_blocking(pipe, false);
- // socket notifier
- sn_write = new SafeSocketNotifier(pipe, QSocketNotifier::Write, this);
- connect(sn_write, SIGNAL(activated(int)), SLOT(sn_write_activated(int)));
- sn_write->setEnabled(false);
+ // socket notifier
+ sn_write = new SafeSocketNotifier(pipe, QSocketNotifier::Write, this);
+ connect(sn_write, SIGNAL(activated(int)), SLOT(sn_write_activated(int)));
+ sn_write->setEnabled(false);
#endif
- }
- }
+ }
+ }
public slots:
- void t_timeout()
- {
+ void t_timeout()
+ {
#ifdef Q_OS_WIN
- if(blockReadNotify)
- return;
-
- // were we forced to notify? this can happen if we want to
- // spread out results across two reads. whatever caused
- // the forceNotify already knows what to do, so all we do
- // is signal.
- if(forceNotify)
- {
- forceNotify = false;
- blockReadNotify = true;
- emit q->notify();
- return;
- }
-#endif
- }
-
- void pw_canWrite(int result, int bytesWritten)
- {
+ if (blockReadNotify) {
+ return;
+ }
+
+ // were we forced to notify? this can happen if we want to
+ // spread out results across two reads. whatever caused
+ // the forceNotify already knows what to do, so all we do
+ // is signal.
+ if (forceNotify) {
+ forceNotify = false;
+ blockReadNotify = true;
+ emit q->notify();
+ return;
+ }
+#endif
+ }
+
+ void pw_canWrite(int result, int bytesWritten)
+ {
#ifdef Q_OS_WIN
- if(result == 0)
- {
- writeResult = 0;
- lastWritten = lastTaken; // success means all bytes
- }
- else
- {
- writeResult = -1;
- lastWritten = bytesWritten;
- }
-
- canWrite = true;
- emit q->notify();
+ if (result == 0) {
+ writeResult = 0;
+ lastWritten = lastTaken; // success means all bytes
+ } else {
+ writeResult = -1;
+ lastWritten = bytesWritten;
+ }
+
+ canWrite = true;
+ emit q->notify();
#else
- Q_UNUSED(result);
- Q_UNUSED(bytesWritten);
+ Q_UNUSED(result);
+ Q_UNUSED(bytesWritten);
#endif
- }
+ }
- void pr_canRead(int result)
- {
+ void pr_canRead(int result)
+ {
#ifdef Q_OS_WIN
- blockReadNotify = true;
- if(result == -1)
- atEnd = true;
- else if(result == -2)
- atError = true;
- else if(result != -3)
- readAhead = result;
- emit q->notify();
+ blockReadNotify = true;
+ if (result == -1) {
+ atEnd = true;
+ } else if (result == -2) {
+ atError = true;
+ } else if (result != -3) {
+ readAhead = result;
+ }
+ emit q->notify();
#else
- Q_UNUSED(result);
+ Q_UNUSED(result);
#endif
- }
+ }
- void sn_read_activated(int)
- {
+ void sn_read_activated(int)
+ {
#ifdef Q_OS_UNIX
- if(blockReadNotify)
- return;
+ if (blockReadNotify) {
+ return;
+ }
- blockReadNotify = true;
- emit q->notify();
+ blockReadNotify = true;
+ emit q->notify();
#endif
- }
+ }
- void sn_write_activated(int)
- {
+ void sn_write_activated(int)
+ {
#ifdef Q_OS_UNIX
- writeResult = 0;
- lastWritten = lastTaken;
+ writeResult = 0;
+ lastWritten = lastTaken;
- canWrite = true;
- sn_write->setEnabled(false);
- emit q->notify();
+ canWrite = true;
+ sn_write->setEnabled(false);
+ emit q->notify();
#endif
- }
+ }
};
QPipeDevice::QPipeDevice(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
QPipeDevice::~QPipeDevice()
{
- delete d;
+ delete d;
}
QPipeDevice::Type QPipeDevice::type() const
{
- return d->type;
+ return d->type;
}
bool QPipeDevice::isValid() const
{
- return (d->pipe != INVALID_Q_PIPE_ID);
+ return (d->pipe != INVALID_Q_PIPE_ID);
}
Q_PIPE_ID QPipeDevice::id() const
{
- return d->pipe;
+ return d->pipe;
}
int QPipeDevice::idAsInt() const
{
#ifdef Q_OS_WIN
- DWORD dw;
- memcpy(&dw, &d->pipe, sizeof(DWORD));
- return (int)dw; // FIXME? assumes handle value fits in signed int
+ DWORD dw;
+ memcpy(&dw, &d->pipe, sizeof(DWORD));
+ return (int)dw; // FIXME? assumes handle value fits in signed int
#endif
#ifdef Q_OS_UNIX
- return d->pipe;
+ return d->pipe;
#endif
}
void QPipeDevice::take(Q_PIPE_ID id, Type t)
{
- close();
- d->setup(id, t);
+ close();
+ d->setup(id, t);
}
void QPipeDevice::enable()
{
#ifdef Q_OS_WIN
- d->consoleMode = pipe_is_a_console(d->pipe);
+ d->consoleMode = pipe_is_a_console(d->pipe);
#endif
- d->enable();
+ d->enable();
}
void QPipeDevice::close()
{
- d->reset();
+ d->reset();
}
void QPipeDevice::release()
{
- d->pipe = INVALID_Q_PIPE_ID;
- d->reset();
+ d->pipe = INVALID_Q_PIPE_ID;
+ d->reset();
}
bool QPipeDevice::setInheritable(bool enabled)
{
#ifdef Q_OS_WIN
- Q_PIPE_ID newPipe;
- if(!pipe_set_inheritable(d->pipe, enabled, &newPipe))
- return false;
- d->pipe = newPipe;
+ Q_PIPE_ID newPipe;
+ if (!pipe_set_inheritable(d->pipe, enabled, &newPipe)) {
+ return false;
+ }
+ d->pipe = newPipe;
#ifdef USE_POLL
- if(d->pipeReader)
- static_cast<QPipeReaderPoll*>(d->pipeReader)->pipe = d->pipe;
- if(d->pipeWriter)
- static_cast<QPipeWriterPoll*>(d->pipeWriter)->pipe = d->pipe;
+ if (d->pipeReader) {
+ static_cast<QPipeReaderPoll *>(d->pipeReader)->pipe = d->pipe;
+ }
+ if (d->pipeWriter) {
+ static_cast<QPipeWriterPoll *>(d->pipeWriter)->pipe = d->pipe;
+ }
#endif
- return true;
+ return true;
#endif
#ifdef Q_OS_UNIX
- return pipe_set_inheritable(d->pipe, enabled, 0);
+ return pipe_set_inheritable(d->pipe, enabled, 0);
#endif
}
int QPipeDevice::bytesAvailable() const
{
- int n;
+ int n;
#ifdef Q_OS_WIN
- if(d->consoleMode)
- n = pipe_read_avail_console(d->pipe);
- else
- n = pipe_read_avail(d->pipe);
- if(d->readAhead != -1)
- ++n;
+ if (d->consoleMode) {
+ n = pipe_read_avail_console(d->pipe);
+ } else {
+ n = pipe_read_avail(d->pipe);
+ }
+ if (d->readAhead != -1) {
+ ++n;
+ }
#else
- n = pipe_read_avail(d->pipe);
+ n = pipe_read_avail(d->pipe);
#endif
- return n;
+ return n;
}
int QPipeDevice::read(char *data, int maxsize)
{
- if(d->type != QPipeDevice::Read)
- return -1;
+ if (d->type != QPipeDevice::Read) {
+ return -1;
+ }
- // must read at least 1 byte
- if(maxsize < 1)
- return -1;
+ // must read at least 1 byte
+ if (maxsize < 1) {
+ return -1;
+ }
#ifdef Q_OS_WIN
- // for windows console:
- // the number of bytes in utf8 can exceed the number of actual
- // characters it represents. to be safe, we'll assume that
- // utf8 could outnumber characters X:1. this does mean that
- // the maxsize parameter needs to be at least X to do
- // anything. (X = CONSOLE_CHAREXPAND)
- if(d->consoleMode && maxsize < CONSOLE_CHAREXPAND)
- return -1;
+ // for windows console:
+ // the number of bytes in utf8 can exceed the number of actual
+ // characters it represents. to be safe, we'll assume that
+ // utf8 could outnumber characters X:1. this does mean that
+ // the maxsize parameter needs to be at least X to do
+ // anything. (X = CONSOLE_CHAREXPAND)
+ if (d->consoleMode && maxsize < CONSOLE_CHAREXPAND) {
+ return -1;
+ }
- // for resuming the pipeReader
- bool wasBlocked = d->blockReadNotify;
+ // for resuming the pipeReader
+ bool wasBlocked = d->blockReadNotify;
#endif
- d->blockReadNotify = false;
+ d->blockReadNotify = false;
#ifdef Q_OS_WIN
- // predetermined results
- if(d->atEnd)
- {
- close();
- return 0;
- }
- if(d->atError)
- {
- close();
- return -1;
- }
-
- int offset = 0;
- int size = maxsize;
-
- // prepend readAhead if we have it
- if(d->readAhead != -1)
- {
- unsigned char c = (unsigned char)d->readAhead;
- d->readAhead = -1;
- memcpy(&data[0], &c, 1);
- ++offset;
- --size;
-
- // readAhead was enough data for the caller?
- if(size == 0)
- {
- if(wasBlocked)
- d->pipeReader->resume();
- return offset;
- }
- }
-
- // read from the pipe now
- bool done;
- int ret;
- if(d->consoleMode)
- {
- // read a fraction of the number of characters as requested,
- // to guarantee the result fits
- int num = size / CONSOLE_CHAREXPAND;
+ // predetermined results
+ if (d->atEnd) {
+ close();
+ return 0;
+ }
+ if (d->atError) {
+ close();
+ return -1;
+ }
+
+ int offset = 0;
+ int size = maxsize;
+
+ // prepend readAhead if we have it
+ if (d->readAhead != -1) {
+ unsigned char c = (unsigned char)d->readAhead;
+ d->readAhead = -1;
+ memcpy(&data[0], &c, 1);
+ ++offset;
+ --size;
+
+ // readAhead was enough data for the caller?
+ if (size == 0) {
+ if (wasBlocked) {
+ d->pipeReader->resume();
+ }
+ return offset;
+ }
+ }
+
+ // read from the pipe now
+ bool done;
+ int ret;
+ if (d->consoleMode) {
+ // read a fraction of the number of characters as requested,
+ // to guarantee the result fits
+ int num = size / CONSOLE_CHAREXPAND;
#ifdef QPIPE_SECURE
- SecureArray destbuf(num * sizeof(ushort), 0);
+ SecureArray destbuf(num * sizeof(ushort), 0);
#else
- QByteArray destbuf(num * sizeof(ushort), 0);
-#endif
- ushort *dest = (ushort *)destbuf.data();
-
- ret = pipe_read_console(d->pipe, dest, num, &done, d->dec);
- if(ret != -1)
- {
- // for security, encode one character at a time without
- // performing a QString conversion of the whole thing
- QTextCodec *codec = QTextCodec::codecForMib(106);
- QTextCodec::ConverterState cstate(QTextCodec::IgnoreHeader);
- int at = 0;
- for(int n = 0; n < ret; ++n)
- {
- QChar c(dest[n]);
- QByteArray out = codec->fromUnicode(&c, 1, &cstate);
- memcpy(data + offset + at, out.data(), out.size());
- at += out.size();
- }
- ret = at; // change ret to actual bytes
- }
- }
- else
- ret = pipe_read(d->pipe, data + offset, size, &done);
- if(done || ret == -1) // eof or error
- {
- // did we already have some data? if so, defer the eof/error
- if(offset)
- {
- d->forceNotify = true;
- if(done)
- d->atEnd = true;
- else
- d->atError = true;
-
- // readTimer is a singleshot, so we have to start it
- // for forceNotify to work
- d->readTimer->start();
- }
- // otherwise, bail
- else
- {
- close();
- if(done)
- return 0;
- else
- return -1;
- }
- }
- else
- offset += ret;
-
- // pipe still active? resume the pipeReader
- if(wasBlocked && !d->atEnd && !d->atError)
- d->pipeReader->resume();
-
- // no data means error
- if(offset == 0)
- return -1;
-
- return offset;
+ QByteArray destbuf(num * sizeof(ushort), 0);
+#endif
+ ushort *dest = (ushort *)destbuf.data();
+
+ ret = pipe_read_console(d->pipe, dest, num, &done, d->dec);
+ if (ret != -1) {
+ // for security, encode one character at a time without
+ // performing a QString conversion of the whole thing
+ QTextCodec *codec = QTextCodec::codecForMib(106);
+ QTextCodec::ConverterState cstate(QTextCodec::IgnoreHeader);
+ int at = 0;
+ for (int n = 0; n < ret; ++n) {
+ QChar c(dest[n]);
+ QByteArray out = codec->fromUnicode(&c, 1, &cstate);
+ memcpy(data + offset + at, out.data(), out.size());
+ at += out.size();
+ }
+ ret = at; // change ret to actual bytes
+ }
+ } else {
+ ret = pipe_read(d->pipe, data + offset, size, &done);
+ }
+ if (done || ret == -1) { // eof or error
+ // did we already have some data? if so, defer the eof/error
+ if (offset) {
+ d->forceNotify = true;
+ if (done) {
+ d->atEnd = true;
+ } else {
+ d->atError = true;
+ }
+
+ // readTimer is a singleshot, so we have to start it
+ // for forceNotify to work
+ d->readTimer->start();
+ }
+ // otherwise, bail
+ else {
+ close();
+ if (done) {
+ return 0;
+ } else {
+ return -1;
+ }
+ }
+ } else {
+ offset += ret;
+ }
+
+ // pipe still active? resume the pipeReader
+ if (wasBlocked && !d->atEnd && !d->atError) {
+ d->pipeReader->resume();
+ }
+
+ // no data means error
+ if (offset == 0) {
+ return -1;
+ }
+
+ return offset;
#endif
#ifdef Q_OS_UNIX
- bool done;
- int r = pipe_read(d->pipe, data, maxsize, &done);
- if(done)
- {
- close();
- return 0;
- }
- if(r == -1)
- {
- close();
- return -1;
- }
-
- // no data means error
- if(r == 0)
- return -1;
-
- return r;
+ bool done;
+ int r = pipe_read(d->pipe, data, maxsize, &done);
+ if (done) {
+ close();
+ return 0;
+ }
+ if (r == -1) {
+ close();
+ return -1;
+ }
+
+ // no data means error
+ if (r == 0) {
+ return -1;
+ }
+
+ return r;
#endif
}
int QPipeDevice::write(const char *data, int size)
{
- if(d->type != QPipeDevice::Write)
- return -1;
+ if (d->type != QPipeDevice::Write) {
+ return -1;
+ }
- // allowed to write?
- if(!d->canWrite)
- return -1;
+ // allowed to write?
+ if (!d->canWrite) {
+ return -1;
+ }
- // if size is zero, don't bother
- if(size == 0)
- return 0;
+ // if size is zero, don't bother
+ if (size == 0) {
+ return 0;
+ }
- int r;
+ int r;
#ifdef Q_OS_WIN
- if(!d->pipeWriter)
- {
+ if (!d->pipeWriter) {
#ifdef USE_POLL
- d->pipeWriter = new QPipeWriterPoll(d->pipe, d);
+ d->pipeWriter = new QPipeWriterPoll(d->pipe, d);
#else
- // console always polls, no matter what
- if(d->consoleMode)
- d->pipeWriter = new QPipeReaderPoll(d->pipe, d);
- else
- d->pipeWriter = new QPipeWriterThread(d->pipe, d);
-#endif
- connect(d->pipeWriter, SIGNAL(canWrite(int, int)), d, SLOT(pw_canWrite(int, int)));
- d->pipeWriter->start();
- }
-
- if(d->consoleMode)
- {
- // Note: we convert to QString here, but it should not be a
- // security issue (see pipe_write_console comment above)
-
- // for console, just write direct. we won't use pipewriter
- QString out = QString::fromUtf8(QByteArray(data, size));
- r = pipe_write_console(d->pipe, out.utf16(), out.length());
- if(r == -1)
- return -1;
-
- // convert characters to bytes
- r = out.mid(0, r).toUtf8().size();
-
- // simulate. we invoke the signal of pipewriter rather than our
- // own slot, so that the invoke can be cancelled.
- d->canWrite = false;
- QMetaObject::invokeMethod(d->pipeWriter, "canWrite", Qt::QueuedConnection, Q_ARG(int, 0), Q_ARG(int, r));
- }
- else
- {
- d->canWrite = false;
- r = d->pipeWriter->write(data, size);
- }
-
- d->lastTaken = r;
- if(r == -1)
- {
- close();
- return -1;
- }
+ // console always polls, no matter what
+ if (d->consoleMode) {
+ d->pipeWriter = new QPipeReaderPoll(d->pipe, d);
+ } else {
+ d->pipeWriter = new QPipeWriterThread(d->pipe, d);
+ }
+#endif
+ connect(d->pipeWriter, SIGNAL(canWrite(int,int)), d, SLOT(pw_canWrite(int,int)));
+ d->pipeWriter->start();
+ }
+
+ if (d->consoleMode) {
+ // Note: we convert to QString here, but it should not be a
+ // security issue (see pipe_write_console comment above)
+
+ // for console, just write direct. we won't use pipewriter
+ QString out = QString::fromUtf8(QByteArray(data, size));
+ r = pipe_write_console(d->pipe, out.utf16(), out.length());
+ if (r == -1) {
+ return -1;
+ }
+
+ // convert characters to bytes
+ r = out.mid(0, r).toUtf8().size();
+
+ // simulate. we invoke the signal of pipewriter rather than our
+ // own slot, so that the invoke can be cancelled.
+ d->canWrite = false;
+ QMetaObject::invokeMethod(d->pipeWriter, "canWrite", Qt::QueuedConnection, Q_ARG(int, 0), Q_ARG(int, r));
+ } else {
+ d->canWrite = false;
+ r = d->pipeWriter->write(data, size);
+ }
+
+ d->lastTaken = r;
+ if (r == -1) {
+ close();
+ return -1;
+ }
#endif
#ifdef Q_OS_UNIX
- r = pipe_write(d->pipe, data, size);
- d->lastTaken = r;
- if(r == -1)
- {
- close();
- return -1;
- }
-
- d->canWrite = false;
- d->sn_write->setEnabled(true);
-#endif
- return r;
+ r = pipe_write(d->pipe, data, size);
+ d->lastTaken = r;
+ if (r == -1) {
+ close();
+ return -1;
+ }
+
+ d->canWrite = false;
+ d->sn_write->setEnabled(true);
+#endif
+ return r;
}
int QPipeDevice::writeResult(int *written) const
{
- if(written)
- *written = d->lastWritten;
- return d->writeResult;
+ if (written) {
+ *written = d->lastWritten;
+ }
+ return d->writeResult;
}
//----------------------------------------------------------------------------
// QPipeEnd
//----------------------------------------------------------------------------
-enum ResetMode
-{
- ResetSession = 0,
- ResetSessionAndData = 1,
- ResetAll = 2
+enum ResetMode {
+ ResetSession = 0,
+ ResetSessionAndData = 1,
+ ResetAll = 2
};
class QPipeEnd::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- QPipeEnd *q;
- QPipeDevice pipe;
- QPipeDevice::Type type;
- QByteArray buf;
- QByteArray curWrite;
+ QPipeEnd *q;
+ QPipeDevice pipe;
+ QPipeDevice::Type type;
+ QByteArray buf;
+ QByteArray curWrite;
#ifdef Q_OS_WIN
- bool consoleMode;
+ bool consoleMode;
#endif
#ifdef QPIPE_SECURE
- bool secure;
- SecureArray sec_buf;
- SecureArray sec_curWrite;
-#endif
- SafeTimer readTrigger, writeTrigger, closeTrigger, writeErrorTrigger;
- bool canRead, activeWrite;
- int lastWrite;
- bool closeLater;
- bool closing;
-
- Private(QPipeEnd *_q) : QObject(_q), q(_q), pipe(this), readTrigger(this), writeTrigger(this), closeTrigger(this), writeErrorTrigger(this)
- {
- readTrigger.setSingleShot(true);
- writeTrigger.setSingleShot(true);
- closeTrigger.setSingleShot(true);
- writeErrorTrigger.setSingleShot(true);
- connect(&pipe, SIGNAL(notify()), SLOT(pipe_notify()));
- connect(&readTrigger, SIGNAL(timeout()), SLOT(doRead()));
- connect(&writeTrigger, SIGNAL(timeout()), SLOT(doWrite()));
- connect(&closeTrigger, SIGNAL(timeout()), SLOT(doClose()));
- connect(&writeErrorTrigger, SIGNAL(timeout()), SLOT(doWriteError()));
- reset(ResetSessionAndData);
- }
-
- void reset(ResetMode mode)
- {
- pipe.close();
- readTrigger.stop();
- writeTrigger.stop();
- closeTrigger.stop();
- writeErrorTrigger.stop();
- canRead = false;
- activeWrite = false;
- lastWrite = 0;
- closeLater = false;
- closing = false;
- curWrite.clear();
+ bool secure;
+ SecureArray sec_buf;
+ SecureArray sec_curWrite;
+#endif
+ SafeTimer readTrigger, writeTrigger, closeTrigger, writeErrorTrigger;
+ bool canRead, activeWrite;
+ int lastWrite;
+ bool closeLater;
+ bool closing;
+
+ Private(QPipeEnd *_q) : QObject(_q), q(_q), pipe(this), readTrigger(this), writeTrigger(this), closeTrigger(this), writeErrorTrigger(this)
+ {
+ readTrigger.setSingleShot(true);
+ writeTrigger.setSingleShot(true);
+ closeTrigger.setSingleShot(true);
+ writeErrorTrigger.setSingleShot(true);
+ connect(&pipe, SIGNAL(notify()), SLOT(pipe_notify()));
+ connect(&readTrigger, SIGNAL(timeout()), SLOT(doRead()));
+ connect(&writeTrigger, SIGNAL(timeout()), SLOT(doWrite()));
+ connect(&closeTrigger, SIGNAL(timeout()), SLOT(doClose()));
+ connect(&writeErrorTrigger, SIGNAL(timeout()), SLOT(doWriteError()));
+ reset(ResetSessionAndData);
+ }
+
+ void reset(ResetMode mode)
+ {
+ pipe.close();
+ readTrigger.stop();
+ writeTrigger.stop();
+ closeTrigger.stop();
+ writeErrorTrigger.stop();
+ canRead = false;
+ activeWrite = false;
+ lastWrite = 0;
+ closeLater = false;
+ closing = false;
+ curWrite.clear();
#ifdef QPIPE_SECURE
- secure = false;
- sec_curWrite.clear();
+ secure = false;
+ sec_curWrite.clear();
#endif
- if(mode >= ResetSessionAndData)
- {
- buf.clear();
+ if (mode >= ResetSessionAndData) {
+ buf.clear();
#ifdef QPIPE_SECURE
- sec_buf.clear();
+ sec_buf.clear();
#endif
- }
- }
+ }
+ }
- void setup(Q_PIPE_ID id, QPipeDevice::Type _type)
- {
- type = _type;
+ void setup(Q_PIPE_ID id, QPipeDevice::Type _type)
+ {
+ type = _type;
#ifdef Q_OS_WIN
- consoleMode = pipe_is_a_console(id);
+ consoleMode = pipe_is_a_console(id);
#endif
- pipe.take(id, type);
- }
+ pipe.take(id, type);
+ }
- int pendingSize() const
- {
+ int pendingSize() const
+ {
#ifdef QPIPE_SECURE
- if(secure)
- return sec_buf.size();
- else
+ if (secure) {
+ return sec_buf.size();
+ } else
#endif
- return buf.size();
- }
+ return buf.size();
+ }
- int pendingFreeSize() const
- {
+ int pendingFreeSize() const
+ {
#ifdef QPIPE_SECURE
- if(secure)
- return qMax(PIPEEND_READBUF_SEC - sec_buf.size(), 0);
- else
+ if (secure) {
+ return qMax(PIPEEND_READBUF_SEC - sec_buf.size(), 0);
+ } else
#endif
- return qMax(PIPEEND_READBUF - buf.size(), 0);
- }
+ return qMax(PIPEEND_READBUF - buf.size(), 0);
+ }
- void appendArray(QByteArray *a, const QByteArray &b)
- {
- (*a) += b;
- }
+ void appendArray(QByteArray *a, const QByteArray &b)
+ {
+ (*a) += b;
+ }
#ifdef QPIPE_SECURE
- void appendArray(SecureArray *a, const SecureArray &b)
- {
- a->append(b);
- }
+ void appendArray(SecureArray *a, const SecureArray &b)
+ {
+ a->append(b);
+ }
#endif
- void takeArray(QByteArray *a, int len)
- {
- char *p = a->data();
- int newsize = a->size() - len;
- memmove(p, p + len, newsize);
- a->resize(newsize);
- }
+ void takeArray(QByteArray *a, int len)
+ {
+ char *p = a->data();
+ int newsize = a->size() - len;
+ memmove(p, p + len, newsize);
+ a->resize(newsize);
+ }
#ifdef QPIPE_SECURE
- void takeArray(SecureArray *a, int len)
- {
- char *p = a->data();
- int newsize = a->size() - len;
- memmove(p, p + len, newsize);
- a->resize(newsize);
- }
-#endif
-
- void setupNextRead()
- {
- if(pipe.isValid() && canRead)
- {
- canRead = false;
- readTrigger.start(0);
- }
- }
-
- void setupNextWrite()
- {
- if(!activeWrite)
- {
- activeWrite = true;
- writeTrigger.start(0);
- }
- }
-
- QByteArray read(QByteArray *buf, int bytes)
- {
- QByteArray a;
- if(bytes == -1 || bytes > buf->size())
- {
- a = *buf;
- }
- else
- {
- a.resize(bytes);
- memcpy(a.data(), buf->data(), a.size());
- }
-
- takeArray(buf, a.size());
- setupNextRead();
- return a;
- }
-
- void write(QByteArray *buf, const QByteArray &a)
- {
- appendArray(buf, a);
- setupNextWrite();
- }
+ void takeArray(SecureArray *a, int len)
+ {
+ char *p = a->data();
+ int newsize = a->size() - len;
+ memmove(p, p + len, newsize);
+ a->resize(newsize);
+ }
+#endif
+
+ void setupNextRead()
+ {
+ if (pipe.isValid() && canRead) {
+ canRead = false;
+ readTrigger.start(0);
+ }
+ }
+
+ void setupNextWrite()
+ {
+ if (!activeWrite) {
+ activeWrite = true;
+ writeTrigger.start(0);
+ }
+ }
+
+ QByteArray read(QByteArray *buf, int bytes)
+ {
+ QByteArray a;
+ if (bytes == -1 || bytes > buf->size()) {
+ a = *buf;
+ } else {
+ a.resize(bytes);
+ memcpy(a.data(), buf->data(), a.size());
+ }
+
+ takeArray(buf, a.size());
+ setupNextRead();
+ return a;
+ }
+
+ void write(QByteArray *buf, const QByteArray &a)
+ {
+ appendArray(buf, a);
+ setupNextWrite();
+ }
#ifdef QPIPE_SECURE
- SecureArray readSecure(SecureArray *buf, int bytes)
- {
- SecureArray a;
- if(bytes == -1 || bytes > buf->size())
- {
- a = *buf;
- }
- else
- {
- a.resize(bytes);
- memcpy(a.data(), buf->data(), a.size());
- }
-
- takeArray(buf, a.size());
- setupNextRead();
- return a;
- }
-
- void writeSecure(SecureArray *buf, const SecureArray &a)
- {
- appendArray(buf, a);
- setupNextWrite();
- }
+ SecureArray readSecure(SecureArray *buf, int bytes)
+ {
+ SecureArray a;
+ if (bytes == -1 || bytes > buf->size()) {
+ a = *buf;
+ } else {
+ a.resize(bytes);
+ memcpy(a.data(), buf->data(), a.size());
+ }
+
+ takeArray(buf, a.size());
+ setupNextRead();
+ return a;
+ }
+
+ void writeSecure(SecureArray *buf, const SecureArray &a)
+ {
+ appendArray(buf, a);
+ setupNextWrite();
+ }
#endif
public slots:
- void pipe_notify()
- {
- if(pipe.type() == QPipeDevice::Read)
- {
- doRead();
- }
- else
- {
- int x;
- int writeResult = pipe.writeResult(&x);
- if(writeResult == -1)
- lastWrite = x; // if error, we may have written less bytes
-
- // remove what we just wrote
- bool moreData = false;
+ void pipe_notify()
+ {
+ if (pipe.type() == QPipeDevice::Read) {
+ doRead();
+ } else {
+ int x;
+ int writeResult = pipe.writeResult(&x);
+ if (writeResult == -1) {
+ lastWrite = x; // if error, we may have written less bytes
+ }
+
+ // remove what we just wrote
+ bool moreData = false;
#ifdef QPIPE_SECURE
- if(secure)
- {
- takeArray(&sec_buf, lastWrite);
- moreData = !sec_buf.isEmpty();
- }
- else
-#endif
- {
- takeArray(&buf, lastWrite);
- moreData = !buf.isEmpty();
- }
+ if (secure) {
+ takeArray(&sec_buf, lastWrite);
+ moreData = !sec_buf.isEmpty();
+ } else
+#endif
+ {
+ takeArray(&buf, lastWrite);
+ moreData = !buf.isEmpty();
+ }
#ifdef QPIPE_SECURE
- sec_curWrite.clear();
-#endif
- curWrite.clear();
-
- x = lastWrite;
- lastWrite = 0;
-
- if(writeResult == 0)
- {
- // more to write? do it
- if(moreData)
- {
- writeTrigger.start(0);
- }
- // done with all writing
- else
- {
- activeWrite = false;
- if(closeLater)
- {
- closeLater = false;
- closeTrigger.start(0);
- }
- }
- }
- else
- writeErrorTrigger.start();
-
- if(x > 0)
- emit q->bytesWritten(x);
- }
- }
-
- void doRead()
- {
- doReadActual(true);
- }
-
- void doReadActual(bool sigs)
- {
- int left = pendingFreeSize();
- if(left == 0)
- {
- canRead = true;
- return;
- }
-
- int max;
+ sec_curWrite.clear();
+#endif
+ curWrite.clear();
+
+ x = lastWrite;
+ lastWrite = 0;
+
+ if (writeResult == 0) {
+ // more to write? do it
+ if (moreData) {
+ writeTrigger.start(0);
+ }
+ // done with all writing
+ else {
+ activeWrite = false;
+ if (closeLater) {
+ closeLater = false;
+ closeTrigger.start(0);
+ }
+ }
+ } else {
+ writeErrorTrigger.start();
+ }
+
+ if (x > 0) {
+ emit q->bytesWritten(x);
+ }
+ }
+ }
+
+ void doRead()
+ {
+ doReadActual(true);
+ }
+
+ void doReadActual(bool sigs)
+ {
+ int left = pendingFreeSize();
+ if (left == 0) {
+ canRead = true;
+ return;
+ }
+
+ int max;
#ifdef Q_OS_WIN
- if(consoleMode)
- {
- // need a minimum amount for console
- if(left < CONSOLE_CHAREXPAND)
- {
- canRead = true;
- return;
- }
-
- // don't use pipe.bytesAvailable() for console mode,
- // as it is somewhat bogus. fortunately, there is
- // no problem with overreading from the console.
- max = qMin(left, 32);
- }
- else
-#endif
- {
- max = qMin(left, pipe.bytesAvailable());
- }
-
- int ret;
+ if (consoleMode) {
+ // need a minimum amount for console
+ if (left < CONSOLE_CHAREXPAND) {
+ canRead = true;
+ return;
+ }
+
+ // don't use pipe.bytesAvailable() for console mode,
+ // as it is somewhat bogus. fortunately, there is
+ // no problem with overreading from the console.
+ max = qMin(left, 32);
+ } else
+#endif
+ {
+ max = qMin(left, pipe.bytesAvailable());
+ }
+
+ int ret;
#ifdef QPIPE_SECURE
- if(secure)
- {
- SecureArray a(max);
- ret = pipe.read(a.data(), a.size());
- if(ret >= 1)
- {
- a.resize(ret);
- sec_buf.append(a);
- }
- }
- else
-#endif
- {
- QByteArray a(max, 0);
- ret = pipe.read(a.data(), a.size());
- if(ret >= 1)
- {
- a.resize(ret);
- buf += a;
- }
- }
-
- if(ret < 1)
- {
- reset(ResetSession);
- if(sigs)
- {
- if(ret == 0)
- emit q->error(QPipeEnd::ErrorEOF);
- else
- emit q->error(QPipeEnd::ErrorBroken);
- }
- return;
- }
-
- if(sigs)
- emit q->readyRead();
- }
-
- void doWrite()
- {
- int ret;
+ if (secure) {
+ SecureArray a(max);
+ ret = pipe.read(a.data(), a.size());
+ if (ret >= 1) {
+ a.resize(ret);
+ sec_buf.append(a);
+ }
+ } else
+#endif
+ {
+ QByteArray a(max, 0);
+ ret = pipe.read(a.data(), a.size());
+ if (ret >= 1) {
+ a.resize(ret);
+ buf += a;
+ }
+ }
+
+ if (ret < 1) {
+ reset(ResetSession);
+ if (sigs) {
+ if (ret == 0) {
+ emit q->error(QPipeEnd::ErrorEOF);
+ } else {
+ emit q->error(QPipeEnd::ErrorBroken);
+ }
+ }
+ return;
+ }
+
+ if (sigs) {
+ emit q->readyRead();
+ }
+ }
+
+ void doWrite()
+ {
+ int ret;
#ifdef QPIPE_SECURE
- if(secure)
- {
- sec_curWrite.resize(qMin(PIPEEND_BLOCK, sec_buf.size()));
- memcpy(sec_curWrite.data(), sec_buf.data(), sec_curWrite.size());
-
- ret = pipe.write(sec_curWrite.data(), sec_curWrite.size());
- }
- else
-#endif
- {
- curWrite.resize(qMin(PIPEEND_BLOCK, buf.size()));
- memcpy(curWrite.data(), buf.data(), curWrite.size());
-
- ret = pipe.write(curWrite.data(), curWrite.size());
- }
-
- if(ret == -1)
- {
- reset(ResetSession);
- emit q->error(QPipeEnd::ErrorBroken);
- return;
- }
-
- lastWrite = ret;
- }
-
- void doClose()
- {
- reset(ResetSession);
- emit q->closed();
- }
-
- void doWriteError()
- {
- reset(ResetSession);
- emit q->error(QPipeEnd::ErrorBroken);
- }
+ if (secure) {
+ sec_curWrite.resize(qMin(PIPEEND_BLOCK, sec_buf.size()));
+ memcpy(sec_curWrite.data(), sec_buf.data(), sec_curWrite.size());
+
+ ret = pipe.write(sec_curWrite.data(), sec_curWrite.size());
+ } else
+#endif
+ {
+ curWrite.resize(qMin(PIPEEND_BLOCK, buf.size()));
+ memcpy(curWrite.data(), buf.data(), curWrite.size());
+
+ ret = pipe.write(curWrite.data(), curWrite.size());
+ }
+
+ if (ret == -1) {
+ reset(ResetSession);
+ emit q->error(QPipeEnd::ErrorBroken);
+ return;
+ }
+
+ lastWrite = ret;
+ }
+
+ void doClose()
+ {
+ reset(ResetSession);
+ emit q->closed();
+ }
+
+ void doWriteError()
+ {
+ reset(ResetSession);
+ emit q->error(QPipeEnd::ErrorBroken);
+ }
};
QPipeEnd::QPipeEnd(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(this);
+ d = new Private(this);
}
QPipeEnd::~QPipeEnd()
{
- delete d;
+ delete d;
}
void QPipeEnd::reset()
{
- d->reset(ResetAll);
+ d->reset(ResetAll);
}
QPipeDevice::Type QPipeEnd::type() const
{
- return d->pipe.type();
+ return d->pipe.type();
}
bool QPipeEnd::isValid() const
{
- return d->pipe.isValid();
+ return d->pipe.isValid();
}
Q_PIPE_ID QPipeEnd::id() const
{
- return d->pipe.id();
+ return d->pipe.id();
}
int QPipeEnd::idAsInt() const
{
- return d->pipe.idAsInt();
+ return d->pipe.idAsInt();
}
void QPipeEnd::take(Q_PIPE_ID id, QPipeDevice::Type t)
{
- reset();
- d->setup(id, t);
+ reset();
+ d->setup(id, t);
}
#ifdef QPIPE_SECURE
void QPipeEnd::setSecurityEnabled(bool secure)
{
- // no change
- if(d->secure == secure)
- return;
-
- if(secure)
- {
- d->sec_buf = d->buf;
- d->buf.clear();
- }
- else
- {
- d->buf = d->sec_buf.toByteArray();
- d->sec_buf.clear();
- }
-
- d->secure = secure;
+ // no change
+ if (d->secure == secure) {
+ return;
+ }
+
+ if (secure) {
+ d->sec_buf = d->buf;
+ d->buf.clear();
+ } else {
+ d->buf = d->sec_buf.toByteArray();
+ d->sec_buf.clear();
+ }
+
+ d->secure = secure;
}
#endif
void QPipeEnd::enable()
{
- d->pipe.enable();
+ d->pipe.enable();
}
void QPipeEnd::close()
{
- if(!isValid() || d->closing)
- return;
+ if (!isValid() || d->closing) {
+ return;
+ }
- d->closing = true;
+ d->closing = true;
- if(d->activeWrite)
- d->closeLater = true;
- else
- d->closeTrigger.start(0);
+ if (d->activeWrite) {
+ d->closeLater = true;
+ } else {
+ d->closeTrigger.start(0);
+ }
}
void QPipeEnd::release()
{
- if(!isValid())
- return;
+ if (!isValid()) {
+ return;
+ }
- d->pipe.release();
- d->reset(ResetSession);
+ d->pipe.release();
+ d->reset(ResetSession);
}
bool QPipeEnd::setInheritable(bool enabled)
{
- return d->pipe.setInheritable(enabled);
+ return d->pipe.setInheritable(enabled);
}
void QPipeEnd::finalize()
{
- if(!isValid())
- return;
+ if (!isValid()) {
+ return;
+ }
- if(d->pipe.bytesAvailable())
- d->doReadActual(false);
- d->reset(ResetSession);
+ if (d->pipe.bytesAvailable()) {
+ d->doReadActual(false);
+ }
+ d->reset(ResetSession);
}
void QPipeEnd::finalizeAndRelease()
{
- if(!isValid())
- return;
+ if (!isValid()) {
+ return;
+ }
- if(d->pipe.bytesAvailable())
- d->doReadActual(false);
- d->pipe.release();
- d->reset(ResetSession);
+ if (d->pipe.bytesAvailable()) {
+ d->doReadActual(false);
+ }
+ d->pipe.release();
+ d->reset(ResetSession);
}
int QPipeEnd::bytesAvailable() const
{
- return d->pendingSize();
+ return d->pendingSize();
}
int QPipeEnd::bytesToWrite() const
{
- return d->pendingSize();
+ return d->pendingSize();
}
QByteArray QPipeEnd::read(int bytes)
{
- return d->read(&d->buf, bytes);
+ return d->read(&d->buf, bytes);
}
void QPipeEnd::write(const QByteArray &buf)
{
- if(!isValid() || d->closing)
- return;
+ if (!isValid() || d->closing) {
+ return;
+ }
- if(buf.isEmpty())
- return;
+ if (buf.isEmpty()) {
+ return;
+ }
#ifdef QPIPE_SECURE
- if(d->secure) // call writeSecure() instead
- return;
+ if (d->secure) { // call writeSecure() instead
+ return;
+ }
#endif
- d->write(&d->buf, buf);
+ d->write(&d->buf, buf);
}
#ifdef QPIPE_SECURE
SecureArray QPipeEnd::readSecure(int bytes)
{
- return d->readSecure(&d->sec_buf, bytes);
+ return d->readSecure(&d->sec_buf, bytes);
}
void QPipeEnd::writeSecure(const SecureArray &buf)
{
- if(!isValid() || d->closing)
- return;
+ if (!isValid() || d->closing) {
+ return;
+ }
- if(buf.isEmpty())
- return;
+ if (buf.isEmpty()) {
+ return;
+ }
- if(!d->secure) // call write() instead
- return;
+ if (!d->secure) { // call write() instead
+ return;
+ }
- d->writeSecure(&d->sec_buf, buf);
+ d->writeSecure(&d->sec_buf, buf);
}
#endif
QByteArray QPipeEnd::takeBytesToWrite()
{
- // only call this on inactive sessions
- if(isValid())
- return QByteArray();
+ // only call this on inactive sessions
+ if (isValid()) {
+ return QByteArray();
+ }
- QByteArray a = d->buf;
- d->buf.clear();
- return a;
+ QByteArray a = d->buf;
+ d->buf.clear();
+ return a;
}
#ifdef QPIPE_SECURE
SecureArray QPipeEnd::takeBytesToWriteSecure()
{
- // only call this on inactive sessions
- if(isValid())
- return SecureArray();
+ // only call this on inactive sessions
+ if (isValid()) {
+ return SecureArray();
+ }
- SecureArray a = d->sec_buf;
- d->sec_buf.clear();
- return a;
+ SecureArray a = d->sec_buf;
+ d->sec_buf.clear();
+ return a;
}
#endif
//----------------------------------------------------------------------------
// QPipe
//----------------------------------------------------------------------------
QPipe::QPipe(QObject *parent)
-:i(parent), o(parent)
+ : i(parent), o(parent)
{
}
QPipe::~QPipe()
{
}
void QPipe::reset()
{
- i.reset();
- o.reset();
+ i.reset();
+ o.reset();
}
#ifdef QPIPE_SECURE
bool QPipe::create(bool secure)
#else
bool QPipe::create()
#endif
{
- reset();
+ reset();
#ifdef Q_OS_WIN
- SECURITY_ATTRIBUTES secAttr;
- memset(&secAttr, 0, sizeof secAttr);
- secAttr.nLength = sizeof secAttr;
- secAttr.bInheritHandle = false;
+ SECURITY_ATTRIBUTES secAttr;
+ memset(&secAttr, 0, sizeof secAttr);
+ secAttr.nLength = sizeof secAttr;
+ secAttr.bInheritHandle = false;
- HANDLE r, w;
- if(!CreatePipe(&r, &w, &secAttr, 0))
- return false;
- i.take(r, QPipeDevice::Read);
- o.take(w, QPipeDevice::Write);
+ HANDLE r, w;
+ if (!CreatePipe(&r, &w, &secAttr, 0)) {
+ return false;
+ }
+ i.take(r, QPipeDevice::Read);
+ o.take(w, QPipeDevice::Write);
#endif
#ifdef Q_OS_UNIX
- int p[2];
- if(pipe(p) == -1)
- return false;
- if(!pipe_set_inheritable(p[0], false, 0) ||
- !pipe_set_inheritable(p[1], false, 0))
- {
- close(p[0]);
- close(p[1]);
- return false;
- }
- i.take(p[0], QPipeDevice::Read);
- o.take(p[1], QPipeDevice::Write);
+ int p[2];
+ if (pipe(p) == -1) {
+ return false;
+ }
+ if (!pipe_set_inheritable(p[0], false, 0) ||
+ !pipe_set_inheritable(p[1], false, 0)) {
+ close(p[0]);
+ close(p[1]);
+ return false;
+ }
+ i.take(p[0], QPipeDevice::Read);
+ o.take(p[1], QPipeDevice::Write);
#endif
#ifdef QPIPE_SECURE
- i.setSecurityEnabled(secure);
- o.setSecurityEnabled(secure);
+ i.setSecurityEnabled(secure);
+ o.setSecurityEnabled(secure);
#endif
- return true;
+ return true;
}
}
#include "qpipe.moc"
diff --git a/src/support/synchronizer.cpp b/src/support/synchronizer.cpp
index 69a13d0d..227cb7e5 100644
--- a/src/support/synchronizer.cpp
+++ b/src/support/synchronizer.cpp
@@ -1,534 +1,526 @@
/*
* Copyright (C) 2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_support.h"
#include "qca_safetimer.h"
#include <QAbstractEventDispatcher>
#include <QCoreApplication>
#include <QEvent>
#include <QMutex>
#include <QPair>
#include <QTime>
#include <QWaitCondition>
//#define TIMERFIXER_DEBUG
#ifdef TIMERFIXER_DEBUG
#include <stdio.h>
#endif
-namespace QCA {
+namespace QCA
+{
//----------------------------------------------------------------------------
// TimerFixer
//----------------------------------------------------------------------------
class TimerFixer : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- struct TimerInfo
- {
- int id;
- int interval;
- QTime time;
- bool fixInterval;
+ struct TimerInfo {
+ int id;
+ int interval;
+ QTime time;
+ bool fixInterval;
- TimerInfo() : fixInterval(false) {}
- };
+ TimerInfo() : fixInterval(false) {}
+ };
- TimerFixer *fixerParent;
- QList<TimerFixer*> fixerChildren;
+ TimerFixer *fixerParent;
+ QList<TimerFixer *> fixerChildren;
- QObject *target;
- QAbstractEventDispatcher *ed;
- QList<TimerInfo> timers;
+ QObject *target;
+ QAbstractEventDispatcher *ed;
+ QList<TimerInfo> timers;
- static bool haveFixer(QObject *obj)
- {
- return obj->findChild<TimerFixer *>() ? true : false;
- }
+ static bool haveFixer(QObject *obj)
+ {
+ return obj->findChild<TimerFixer *>() ? true : false;
+ }
- TimerFixer(QObject *_target, TimerFixer *_fp = 0) : QObject(_target)
- {
- ed = 0;
+ TimerFixer(QObject *_target, TimerFixer *_fp = 0) : QObject(_target)
+ {
+ ed = 0;
- target = _target;
- fixerParent = _fp;
- if(fixerParent)
- fixerParent->fixerChildren.append(this);
+ target = _target;
+ fixerParent = _fp;
+ if (fixerParent) {
+ fixerParent->fixerChildren.append(this);
+ }
#ifdef TIMERFIXER_DEBUG
- printf("TimerFixer[%p] pairing with %p (%s)\n", this, target, target->metaObject()->className());
+ printf("TimerFixer[%p] pairing with %p (%s)\n", this, target, target->metaObject()->className());
#endif
- edlink();
- target->installEventFilter(this);
-
- QObjectList list = target->children();
- for(int n = 0; n < list.count(); ++n)
- hook(list[n]);
- }
-
- ~TimerFixer()
- {
- if(fixerParent)
- fixerParent->fixerChildren.removeAll(this);
-
- QList<TimerFixer*> list = fixerChildren;
- for(int n = 0; n < list.count(); ++n)
- delete list[n];
- list.clear();
-
- updateTimerList(); // do this just to trip debug output
-
- target->removeEventFilter(this);
- edunlink();
+ edlink();
+ target->installEventFilter(this);
+
+ QObjectList list = target->children();
+ for (int n = 0; n < list.count(); ++n) {
+ hook(list[n]);
+ }
+ }
+
+ ~TimerFixer()
+ {
+ if (fixerParent) {
+ fixerParent->fixerChildren.removeAll(this);
+ }
+
+ QList<TimerFixer *> list = fixerChildren;
+ for (int n = 0; n < list.count(); ++n) {
+ delete list[n];
+ }
+ list.clear();
+
+ updateTimerList(); // do this just to trip debug output
+
+ target->removeEventFilter(this);
+ edunlink();
#ifdef TIMERFIXER_DEBUG
- printf("TimerFixer[%p] unpaired with %p (%s)\n", this, target, target->metaObject()->className());
+ printf("TimerFixer[%p] unpaired with %p (%s)\n", this, target, target->metaObject()->className());
#endif
- }
-
- virtual bool event(QEvent *e)
- {
- switch(e->type())
- {
- case QEvent::ThreadChange: // this happens second
- //printf("TimerFixer[%p] self changing threads\n", this);
- edunlink();
- QMetaObject::invokeMethod(this, "fixTimers", Qt::QueuedConnection);
- break;
- default:
- break;
- }
-
- return QObject::event(e);
- }
-
- virtual bool eventFilter(QObject *, QEvent *e)
- {
- switch(e->type())
- {
- case QEvent::ChildAdded:
- hook(((QChildEvent *)e)->child());
- break;
- case QEvent::ChildRemoved:
- unhook(((QChildEvent *)e)->child());
- break;
- case QEvent::Timer:
- handleTimerEvent(((QTimerEvent *)e)->timerId());
- break;
- case QEvent::ThreadChange: // this happens first
+ }
+
+ virtual bool event(QEvent *e)
+ {
+ switch (e->type()) {
+ case QEvent::ThreadChange: // this happens second
+ //printf("TimerFixer[%p] self changing threads\n", this);
+ edunlink();
+ QMetaObject::invokeMethod(this, "fixTimers", Qt::QueuedConnection);
+ break;
+ default:
+ break;
+ }
+
+ return QObject::event(e);
+ }
+
+ virtual bool eventFilter(QObject *, QEvent *e)
+ {
+ switch (e->type()) {
+ case QEvent::ChildAdded:
+ hook(((QChildEvent *)e)->child());
+ break;
+ case QEvent::ChildRemoved:
+ unhook(((QChildEvent *)e)->child());
+ break;
+ case QEvent::Timer:
+ handleTimerEvent(((QTimerEvent *)e)->timerId());
+ break;
+ case QEvent::ThreadChange: // this happens first
#ifdef TIMERFIXER_DEBUG
- printf("TimerFixer[%p] target changing threads\n", this);
+ printf("TimerFixer[%p] target changing threads\n", this);
#endif
- break;
- default:
- break;
- }
+ break;
+ default:
+ break;
+ }
- return false;
- }
+ return false;
+ }
private slots:
- void edlink()
- {
- ed = QAbstractEventDispatcher::instance();
- //printf("TimerFixer[%p] linking to dispatcher %p\n", this, ed);
- connect(ed, SIGNAL(aboutToBlock()), SLOT(ed_aboutToBlock()));
- }
-
- void edunlink()
- {
- //printf("TimerFixer[%p] unlinking from dispatcher %p\n", this, ed);
- if(ed)
- {
- disconnect(ed, SIGNAL(aboutToBlock()), this, SLOT(ed_aboutToBlock()));
- ed = 0;
- }
- }
-
- void ed_aboutToBlock()
- {
- //printf("TimerFixer[%p] aboutToBlock\n", this);
- updateTimerList();
- }
-
- void fixTimers()
- {
- updateTimerList();
- edlink();
-
- for(int n = 0; n < timers.count(); ++n)
- {
- TimerInfo &info = timers[n];
-
- QThread *objectThread = target->thread();
- QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(objectThread);
-
- int timeLeft = qMax(info.interval - info.time.elapsed(), 0);
- info.fixInterval = true;
- ed->unregisterTimer(info.id);
+ void edlink()
+ {
+ ed = QAbstractEventDispatcher::instance();
+ //printf("TimerFixer[%p] linking to dispatcher %p\n", this, ed);
+ connect(ed, SIGNAL(aboutToBlock()), SLOT(ed_aboutToBlock()));
+ }
+
+ void edunlink()
+ {
+ //printf("TimerFixer[%p] unlinking from dispatcher %p\n", this, ed);
+ if (ed) {
+ disconnect(ed, SIGNAL(aboutToBlock()), this, SLOT(ed_aboutToBlock()));
+ ed = 0;
+ }
+ }
+
+ void ed_aboutToBlock()
+ {
+ //printf("TimerFixer[%p] aboutToBlock\n", this);
+ updateTimerList();
+ }
+
+ void fixTimers()
+ {
+ updateTimerList();
+ edlink();
+
+ for (int n = 0; n < timers.count(); ++n) {
+ TimerInfo &info = timers[n];
+
+ QThread *objectThread = target->thread();
+ QAbstractEventDispatcher *ed = QAbstractEventDispatcher::instance(objectThread);
+
+ int timeLeft = qMax(info.interval - info.time.elapsed(), 0);
+ info.fixInterval = true;
+ ed->unregisterTimer(info.id);
#if QT_VERSION >= 0x050000
- info.id = ed->registerTimer(timeLeft, Qt::CoarseTimer, target);
+ info.id = ed->registerTimer(timeLeft, Qt::CoarseTimer, target);
#else
- info.id = ed->registerTimer(timeLeft, target);
+ info.id = ed->registerTimer(timeLeft, target);
#endif
#ifdef TIMERFIXER_DEBUG
- printf("TimerFixer[%p] adjusting [%d] to %d\n", this, info.id, timeLeft);
+ printf("TimerFixer[%p] adjusting [%d] to %d\n", this, info.id, timeLeft);
#endif
- }
- }
+ }
+ }
private:
- void hook(QObject *obj)
- {
- // don't watch a fixer or any object that already has one
- // SafeTimer has own method to fix timers, skip it too
- if(obj == this || qobject_cast<TimerFixer *>(obj) || haveFixer(obj) || qobject_cast<SafeTimer*>(obj))
- return;
-
- new TimerFixer(obj, this);
- }
-
- void unhook(QObject *obj)
- {
- TimerFixer *t = 0;
- for(int n = 0; n < fixerChildren.count(); ++n)
- {
- if(fixerChildren[n]->target == obj)
- t = fixerChildren[n];
- }
- delete t;
- }
-
- void handleTimerEvent(int id)
- {
- bool found = false;
- int n;
- for(n = 0; n < timers.count(); ++n)
- {
- if(timers[n].id == id)
- {
- found = true;
- break;
- }
- }
- if(!found)
- {
- //printf("*** unrecognized timer [%d] activated ***\n", id);
- return;
- }
-
- TimerInfo &info = timers[n];
+ void hook(QObject *obj)
+ {
+ // don't watch a fixer or any object that already has one
+ // SafeTimer has own method to fix timers, skip it too
+ if (obj == this || qobject_cast<TimerFixer *>(obj) || haveFixer(obj) || qobject_cast<SafeTimer *>(obj)) {
+ return;
+ }
+
+ new TimerFixer(obj, this);
+ }
+
+ void unhook(QObject *obj)
+ {
+ TimerFixer *t = 0;
+ for (int n = 0; n < fixerChildren.count(); ++n) {
+ if (fixerChildren[n]->target == obj) {
+ t = fixerChildren[n];
+ }
+ }
+ delete t;
+ }
+
+ void handleTimerEvent(int id)
+ {
+ bool found = false;
+ int n;
+ for (n = 0; n < timers.count(); ++n) {
+ if (timers[n].id == id) {
+ found = true;
+ break;
+ }
+ }
+ if (!found) {
+ //printf("*** unrecognized timer [%d] activated ***\n", id);
+ return;
+ }
+
+ TimerInfo &info = timers[n];
#ifdef TIMERFIXER_DEBUG
- printf("TimerFixer[%p] timer [%d] activated!\n", this, info.id);
+ printf("TimerFixer[%p] timer [%d] activated!\n", this, info.id);
#endif
- if(info.fixInterval)
- {
+ if (info.fixInterval) {
#ifdef TIMERFIXER_DEBUG
- printf("restoring correct interval (%d)\n", info.interval);
+ printf("restoring correct interval (%d)\n", info.interval);
#endif
- info.fixInterval = false;
- ed->unregisterTimer(info.id);
+ info.fixInterval = false;
+ ed->unregisterTimer(info.id);
#if QT_VERSION >= 0x050000
- info.id = ed->registerTimer(info.interval, Qt::CoarseTimer, target);
+ info.id = ed->registerTimer(info.interval, Qt::CoarseTimer, target);
#else
- info.id = ed->registerTimer(info.interval, target);
+ info.id = ed->registerTimer(info.interval, target);
#endif
- }
-
- info.time.start();
- }
-
- void updateTimerList()
- {
- QList<QAbstractEventDispatcher::TimerInfo> edtimers;
- if(ed)
- edtimers = ed->registeredTimers(target);
-
- // removed?
- for(int n = 0; n < timers.count(); ++n)
- {
- bool found = false;
- int id = timers[n].id;
- for(int i = 0; i < edtimers.count(); ++i)
- {
+ }
+
+ info.time.start();
+ }
+
+ void updateTimerList()
+ {
+ QList<QAbstractEventDispatcher::TimerInfo> edtimers;
+ if (ed) {
+ edtimers = ed->registeredTimers(target);
+ }
+
+ // removed?
+ for (int n = 0; n < timers.count(); ++n) {
+ bool found = false;
+ int id = timers[n].id;
+ for (int i = 0; i < edtimers.count(); ++i) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- if(edtimers[i].timerId == id)
+ if (edtimers[i].timerId == id)
#else
- if(edtimers[i].first == id)
+ if (edtimers[i].first == id)
#endif
- {
- found = true;
- break;
- }
- }
-
- if(!found)
- {
- timers.removeAt(n);
- --n;
+ {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found) {
+ timers.removeAt(n);
+ --n;
#ifdef TIMERFIXER_DEBUG
- printf("TimerFixer[%p] timer [%d] removed\n", this, id);
+ printf("TimerFixer[%p] timer [%d] removed\n", this, id);
#endif
- }
- }
+ }
+ }
- // added?
- for(int n = 0; n < edtimers.count(); ++n)
- {
+ // added?
+ for (int n = 0; n < edtimers.count(); ++n) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- int id = edtimers[n].timerId;
+ int id = edtimers[n].timerId;
#else
- int id = edtimers[n].first;
+ int id = edtimers[n].first;
#endif
- bool found = false;
- for(int i = 0; i < timers.count(); ++i)
- {
- if(timers[i].id == id)
- {
- found = true;
- break;
- }
- }
-
- if(!found)
- {
- TimerInfo info;
- info.id = id;
+ bool found = false;
+ for (int i = 0; i < timers.count(); ++i) {
+ if (timers[i].id == id) {
+ found = true;
+ break;
+ }
+ }
+
+ if (!found) {
+ TimerInfo info;
+ info.id = id;
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- info.interval = edtimers[n].interval;
+ info.interval = edtimers[n].interval;
#else
- info.interval = edtimers[n].second;
+ info.interval = edtimers[n].second;
#endif
- info.time.start();
- timers += info;
+ info.time.start();
+ timers += info;
#ifdef TIMERFIXER_DEBUG
- printf("TimerFixer[%p] timer [%d] added (interval=%d)\n", this, info.id, info.interval);
+ printf("TimerFixer[%p] timer [%d] added (interval=%d)\n", this, info.id, info.interval);
#endif
- }
- }
- }
+ }
+ }
+ }
};
//----------------------------------------------------------------------------
// Synchronizer
//----------------------------------------------------------------------------
class SynchronizerAgent : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SynchronizerAgent(QObject *parent = 0) : QObject(parent)
- {
- QMetaObject::invokeMethod(this, "started", Qt::QueuedConnection);
- }
+ SynchronizerAgent(QObject *parent = 0) : QObject(parent)
+ {
+ QMetaObject::invokeMethod(this, "started", Qt::QueuedConnection);
+ }
signals:
- void started();
+ void started();
};
class Synchronizer::Private : public QThread
{
- Q_OBJECT
+ Q_OBJECT
public:
- Synchronizer *q;
-
- bool active;
- bool do_quit;
- bool cond_met;
-
- QObject *obj;
- QEventLoop *loop;
- SynchronizerAgent *agent;
- TimerFixer *fixer;
- QMutex m;
- QWaitCondition w;
- QThread *orig_thread;
-
- Private(QObject *_obj, Synchronizer *_q)
- : QThread(_q)
- , q(_q)
- , active(false)
- , do_quit(false)
- , cond_met(false)
- , obj(_obj)
- , loop(0)
- , agent(0)
- , fixer(0)
- , m(QMutex::NonRecursive)
- , w()
- , orig_thread(0)
- {
- // SafeTimer has own method to fix timers, skip it too
- if (!qobject_cast<SafeTimer*>(obj))
- fixer = new TimerFixer(obj);
- }
-
- ~Private()
- {
- stop();
- delete fixer;
- }
-
- void start()
- {
- if(active)
- return;
-
- m.lock();
- active = true;
- do_quit = false;
- QThread::start();
- w.wait(&m);
- m.unlock();
- }
-
- void stop()
- {
- if(!active)
- return;
-
- m.lock();
- do_quit = true;
- w.wakeOne();
- m.unlock();
- wait();
- active = false;
- }
-
- bool waitForCondition(int msecs)
- {
- unsigned long time = ULONG_MAX;
- if(msecs != -1)
- time = msecs;
-
- // move object to the worker thread
- cond_met = false;
- orig_thread = QThread::currentThread();
- q->setParent(0); // don't follow the object
- QObject *orig_parent = obj->parent();
- obj->setParent(0); // unparent the target or the move will fail
- obj->moveToThread(this);
-
- // tell the worker thread to start, wait for completion
- m.lock();
- w.wakeOne();
- if(!w.wait(&m, time))
- {
- if(loop)
- {
- // if we timed out, tell the worker to quit
- QMetaObject::invokeMethod(loop, "quit");
- w.wait(&m);
- }
- }
-
- // at this point the worker is done. cleanup and return
- m.unlock();
-
- // restore parents
- obj->setParent(orig_parent);
- q->setParent(obj);
-
- return cond_met;
- }
-
- void conditionMet()
- {
- if(!loop)
- return;
- loop->quit();
- cond_met = true;
- }
+ Synchronizer *q;
+
+ bool active;
+ bool do_quit;
+ bool cond_met;
+
+ QObject *obj;
+ QEventLoop *loop;
+ SynchronizerAgent *agent;
+ TimerFixer *fixer;
+ QMutex m;
+ QWaitCondition w;
+ QThread *orig_thread;
+
+ Private(QObject *_obj, Synchronizer *_q)
+ : QThread(_q)
+ , q(_q)
+ , active(false)
+ , do_quit(false)
+ , cond_met(false)
+ , obj(_obj)
+ , loop(0)
+ , agent(0)
+ , fixer(0)
+ , m(QMutex::NonRecursive)
+ , w()
+ , orig_thread(0)
+ {
+ // SafeTimer has own method to fix timers, skip it too
+ if (!qobject_cast<SafeTimer *>(obj)) {
+ fixer = new TimerFixer(obj);
+ }
+ }
+
+ ~Private()
+ {
+ stop();
+ delete fixer;
+ }
+
+ void start()
+ {
+ if (active) {
+ return;
+ }
+
+ m.lock();
+ active = true;
+ do_quit = false;
+ QThread::start();
+ w.wait(&m);
+ m.unlock();
+ }
+
+ void stop()
+ {
+ if (!active) {
+ return;
+ }
+
+ m.lock();
+ do_quit = true;
+ w.wakeOne();
+ m.unlock();
+ wait();
+ active = false;
+ }
+
+ bool waitForCondition(int msecs)
+ {
+ unsigned long time = ULONG_MAX;
+ if (msecs != -1) {
+ time = msecs;
+ }
+
+ // move object to the worker thread
+ cond_met = false;
+ orig_thread = QThread::currentThread();
+ q->setParent(0); // don't follow the object
+ QObject *orig_parent = obj->parent();
+ obj->setParent(0); // unparent the target or the move will fail
+ obj->moveToThread(this);
+
+ // tell the worker thread to start, wait for completion
+ m.lock();
+ w.wakeOne();
+ if (!w.wait(&m, time)) {
+ if (loop) {
+ // if we timed out, tell the worker to quit
+ QMetaObject::invokeMethod(loop, "quit");
+ w.wait(&m);
+ }
+ }
+
+ // at this point the worker is done. cleanup and return
+ m.unlock();
+
+ // restore parents
+ obj->setParent(orig_parent);
+ q->setParent(obj);
+
+ return cond_met;
+ }
+
+ void conditionMet()
+ {
+ if (!loop) {
+ return;
+ }
+ loop->quit();
+ cond_met = true;
+ }
protected:
- virtual void run()
- {
- m.lock();
- QEventLoop eventLoop;
-
- while(1)
- {
- // thread now sleeps, waiting for work
- w.wakeOne();
- w.wait(&m);
- if(do_quit)
- {
- m.unlock();
- break;
- }
-
- loop = &eventLoop;
- agent = new SynchronizerAgent;
- connect(agent, SIGNAL(started()), SLOT(agent_started()), Qt::DirectConnection);
-
- // run the event loop
- eventLoop.exec();
-
- delete agent;
- agent = 0;
-
- // eventloop done, flush pending events
- QCoreApplication::instance()->sendPostedEvents();
- QCoreApplication::instance()->sendPostedEvents(0, QEvent::DeferredDelete);
-
- // and move the object back
- obj->moveToThread(orig_thread);
-
- m.lock();
- loop = 0;
- w.wakeOne();
- }
- }
+ virtual void run()
+ {
+ m.lock();
+ QEventLoop eventLoop;
+
+ while (1) {
+ // thread now sleeps, waiting for work
+ w.wakeOne();
+ w.wait(&m);
+ if (do_quit) {
+ m.unlock();
+ break;
+ }
+
+ loop = &eventLoop;
+ agent = new SynchronizerAgent;
+ connect(agent, SIGNAL(started()), SLOT(agent_started()), Qt::DirectConnection);
+
+ // run the event loop
+ eventLoop.exec();
+
+ delete agent;
+ agent = 0;
+
+ // eventloop done, flush pending events
+ QCoreApplication::instance()->sendPostedEvents();
+ QCoreApplication::instance()->sendPostedEvents(0, QEvent::DeferredDelete);
+
+ // and move the object back
+ obj->moveToThread(orig_thread);
+
+ m.lock();
+ loop = 0;
+ w.wakeOne();
+ }
+ }
private slots:
- void agent_started()
- {
- m.unlock();
- }
+ void agent_started()
+ {
+ m.unlock();
+ }
};
Synchronizer::Synchronizer(QObject *parent)
-:QObject(parent)
+ : QObject(parent)
{
- d = new Private(parent, this);
+ d = new Private(parent, this);
}
Synchronizer::~Synchronizer()
{
- delete d;
+ delete d;
}
bool Synchronizer::waitForCondition(int msecs)
{
- d->start();
- return d->waitForCondition(msecs);
+ d->start();
+ return d->waitForCondition(msecs);
}
void Synchronizer::conditionMet()
{
- d->conditionMet();
+ d->conditionMet();
}
}
#include "synchronizer.moc"
diff --git a/src/support/syncthread.cpp b/src/support/syncthread.cpp
index 98a06dda..d3e95602 100644
--- a/src/support/syncthread.cpp
+++ b/src/support/syncthread.cpp
@@ -1,237 +1,246 @@
/*
* Copyright (C) 2006 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "qca_support.h"
#include <QEventLoop>
#include <QMetaMethod>
#include <QMutexLocker>
#include <QWaitCondition>
-namespace QCA {
+namespace QCA
+{
QByteArray methodReturnType(const QMetaObject *obj, const QByteArray &method, const QList<QByteArray> argTypes)
{
- for(int n = 0; n < obj->methodCount(); ++n)
- {
- QMetaMethod m = obj->method(n);
+ for (int n = 0; n < obj->methodCount(); ++n) {
+ QMetaMethod m = obj->method(n);
#if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)
- QByteArray sig = m.methodSignature();
+ QByteArray sig = m.methodSignature();
#else
- QByteArray sig = m.signature();
+ QByteArray sig = m.signature();
#endif
- int offset = sig.indexOf('(');
- if(offset == -1)
- continue;
- QByteArray name = sig.mid(0, offset);
- if(name != method)
- continue;
- if(m.parameterTypes() != argTypes)
- continue;
-
- return m.typeName();
- }
- return QByteArray();
+ int offset = sig.indexOf('(');
+ if (offset == -1) {
+ continue;
+ }
+ QByteArray name = sig.mid(0, offset);
+ if (name != method) {
+ continue;
+ }
+ if (m.parameterTypes() != argTypes) {
+ continue;
+ }
+
+ return m.typeName();
+ }
+ return QByteArray();
}
bool invokeMethodWithVariants(QObject *obj, const QByteArray &method, const QVariantList &args, QVariant *ret, Qt::ConnectionType type)
{
- // QMetaObject::invokeMethod() has a 10 argument maximum
- if(args.count() > 10)
- return false;
-
- QList<QByteArray> argTypes;
- for(int n = 0; n < args.count(); ++n)
- argTypes += args[n].typeName();
-
- // get return type
- int metatype = QMetaType::Void;
- QByteArray retTypeName = methodReturnType(obj->metaObject(), method, argTypes);
+ // QMetaObject::invokeMethod() has a 10 argument maximum
+ if (args.count() > 10) {
+ return false;
+ }
+
+ QList<QByteArray> argTypes;
+ for (int n = 0; n < args.count(); ++n) {
+ argTypes += args[n].typeName();
+ }
+
+ // get return type
+ int metatype = QMetaType::Void;
+ QByteArray retTypeName = methodReturnType(obj->metaObject(), method, argTypes);
#if QT_VERSION >= 0x050000
- if(!retTypeName.isEmpty() && retTypeName != "void")
+ if (!retTypeName.isEmpty() && retTypeName != "void")
#else
- if(!retTypeName.isEmpty())
+ if (!retTypeName.isEmpty())
#endif
- {
- metatype = QMetaType::type(retTypeName.data());
+ {
+ metatype = QMetaType::type(retTypeName.data());
#if QT_VERSION >= 0x050000
- if(metatype == QMetaType::UnknownType) // lookup failed
+ if (metatype == QMetaType::UnknownType) // lookup failed
#else
- if(metatype == QMetaType::Void) // lookup failed
+ if (metatype == QMetaType::Void) // lookup failed
#endif
- return false;
- }
-
- QGenericArgument arg[10];
- for(int n = 0; n < args.count(); ++n)
- arg[n] = QGenericArgument(args[n].typeName(), args[n].constData());
-
- QGenericReturnArgument retarg;
- QVariant retval;
-
- if(metatype != QMetaType::Void)
- {
- retval = QVariant(metatype, (const void *)0);
- retarg = QGenericReturnArgument(retval.typeName(), retval.data());
- }
-
- if(!QMetaObject::invokeMethod(obj, method.data(), type, retarg, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9]))
- return false;
-
- if(retval.isValid() && ret)
- *ret = retval;
- return true;
+ return false;
+ }
+
+ QGenericArgument arg[10];
+ for (int n = 0; n < args.count(); ++n) {
+ arg[n] = QGenericArgument(args[n].typeName(), args[n].constData());
+ }
+
+ QGenericReturnArgument retarg;
+ QVariant retval;
+
+ if (metatype != QMetaType::Void) {
+ retval = QVariant(metatype, (const void *)0);
+ retarg = QGenericReturnArgument(retval.typeName(), retval.data());
+ }
+
+ if (!QMetaObject::invokeMethod(obj, method.data(), type, retarg, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9])) {
+ return false;
+ }
+
+ if (retval.isValid() && ret) {
+ *ret = retval;
+ }
+ return true;
}
//----------------------------------------------------------------------------
// SyncThread
//----------------------------------------------------------------------------
class SyncThreadAgent;
class SyncThread::Private : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SyncThread *q;
- QMutex m;
- QWaitCondition w;
- QEventLoop *loop;
- SyncThreadAgent *agent;
- bool last_success;
- QVariant last_ret;
-
- Private(SyncThread *_q) : QObject(_q), q(_q)
- {
- loop = 0;
- agent = 0;
- }
+ SyncThread *q;
+ QMutex m;
+ QWaitCondition w;
+ QEventLoop *loop;
+ SyncThreadAgent *agent;
+ bool last_success;
+ QVariant last_ret;
+
+ Private(SyncThread *_q) : QObject(_q), q(_q)
+ {
+ loop = 0;
+ agent = 0;
+ }
private slots:
- void agent_started();
- void agent_call_ret(bool success, const QVariant &ret);
+ void agent_started();
+ void agent_call_ret(bool success, const QVariant &ret);
};
class SyncThreadAgent : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- SyncThreadAgent(QObject *parent = 0) : QObject(parent)
- {
- QMetaObject::invokeMethod(this, "started", Qt::QueuedConnection);
- }
+ SyncThreadAgent(QObject *parent = 0) : QObject(parent)
+ {
+ QMetaObject::invokeMethod(this, "started", Qt::QueuedConnection);
+ }
signals:
- void started();
- void call_ret(bool success, const QVariant &ret);
+ void started();
+ void call_ret(bool success, const QVariant &ret);
public slots:
- void call_do(QObject *obj, const QByteArray &method, const QVariantList &args)
- {
- QVariant ret;
- bool ok = invokeMethodWithVariants(obj, method, args, &ret, Qt::DirectConnection);
- emit call_ret(ok, ret);
- }
+ void call_do(QObject *obj, const QByteArray &method, const QVariantList &args)
+ {
+ QVariant ret;
+ bool ok = invokeMethodWithVariants(obj, method, args, &ret, Qt::DirectConnection);
+ emit call_ret(ok, ret);
+ }
};
SyncThread::SyncThread(QObject *parent)
-:QThread(parent)
+ : QThread(parent)
{
- d = new Private(this);
- qRegisterMetaType<QVariant>("QVariant");
- qRegisterMetaType<QVariantList>("QVariantList");
+ d = new Private(this);
+ qRegisterMetaType<QVariant>("QVariant");
+ qRegisterMetaType<QVariantList>("QVariantList");
}
SyncThread::~SyncThread()
{
- stop();
- delete d;
+ stop();
+ delete d;
}
void SyncThread::start()
{
- QMutexLocker locker(&d->m);
- Q_ASSERT(!d->loop);
- QThread::start();
- d->w.wait(&d->m);
+ QMutexLocker locker(&d->m);
+ Q_ASSERT(!d->loop);
+ QThread::start();
+ d->w.wait(&d->m);
}
void SyncThread::stop()
{
- QMutexLocker locker(&d->m);
- if(!d->loop)
- return;
- QMetaObject::invokeMethod(d->loop, "quit");
- d->w.wait(&d->m);
- wait();
+ QMutexLocker locker(&d->m);
+ if (!d->loop) {
+ return;
+ }
+ QMetaObject::invokeMethod(d->loop, "quit");
+ d->w.wait(&d->m);
+ wait();
}
QVariant SyncThread::call(QObject *obj, const QByteArray &method, const QVariantList &args, bool *ok)
{
- QMutexLocker locker(&d->m);
- bool ret;
- Q_UNUSED(ret); // In really ret is used. I use this hack to suppress a compiler warning
- ret = QMetaObject::invokeMethod(d->agent, "call_do",
- Qt::QueuedConnection, Q_ARG(QObject*, obj),
- Q_ARG(QByteArray, method), Q_ARG(QVariantList, args));
- Q_ASSERT(ret);
- d->w.wait(&d->m);
- if(ok)
- *ok = d->last_success;
- QVariant v = d->last_ret;
- d->last_ret = QVariant();
- return v;
+ QMutexLocker locker(&d->m);
+ bool ret;
+ Q_UNUSED(ret); // In really ret is used. I use this hack to suppress a compiler warning
+ ret = QMetaObject::invokeMethod(d->agent, "call_do",
+ Qt::QueuedConnection, Q_ARG(QObject *, obj),
+ Q_ARG(QByteArray, method), Q_ARG(QVariantList, args));
+ Q_ASSERT(ret);
+ d->w.wait(&d->m);
+ if (ok) {
+ *ok = d->last_success;
+ }
+ QVariant v = d->last_ret;
+ d->last_ret = QVariant();
+ return v;
}
void SyncThread::run()
{
- d->m.lock();
- d->loop = new QEventLoop;
- d->agent = new SyncThreadAgent;
- connect(d->agent, SIGNAL(started()), d, SLOT(agent_started()), Qt::DirectConnection);
- connect(d->agent, SIGNAL(call_ret(bool, const QVariant &)), d, SLOT(agent_call_ret(bool, const QVariant &)), Qt::DirectConnection);
- d->loop->exec();
- d->m.lock();
- atEnd();
- delete d->agent;
- delete d->loop;
- d->agent = 0;
- d->loop = 0;
- d->w.wakeOne();
- d->m.unlock();
+ d->m.lock();
+ d->loop = new QEventLoop;
+ d->agent = new SyncThreadAgent;
+ connect(d->agent, SIGNAL(started()), d, SLOT(agent_started()), Qt::DirectConnection);
+ connect(d->agent, SIGNAL(call_ret(bool,QVariant)), d, SLOT(agent_call_ret(bool,QVariant)), Qt::DirectConnection);
+ d->loop->exec();
+ d->m.lock();
+ atEnd();
+ delete d->agent;
+ delete d->loop;
+ d->agent = 0;
+ d->loop = 0;
+ d->w.wakeOne();
+ d->m.unlock();
}
void SyncThread::Private::agent_started()
{
- q->atStart();
- w.wakeOne();
- m.unlock();
+ q->atStart();
+ w.wakeOne();
+ m.unlock();
}
void SyncThread::Private::agent_call_ret(bool success, const QVariant &ret)
{
- QMutexLocker locker(&m);
- last_success = success;
- last_ret = ret;
- w.wakeOne();
+ QMutexLocker locker(&m);
+ last_success = success;
+ last_ret = ret;
+ w.wakeOne();
}
}
#include "syncthread.moc"
diff --git a/tools/mozcerts/main.cpp b/tools/mozcerts/main.cpp
index 6cf6019a..c7470bce 100644
--- a/tools/mozcerts/main.cpp
+++ b/tools/mozcerts/main.cpp
@@ -1,169 +1,168 @@
/*
* Copyright (C) 2005 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
/* mozilla certdata converter. adapted from the debian ruby script */
#include <QtCrypto>
#include <QCoreApplication>
#include <QFile>
#include <QTextStream>
QStringList splitWithQuotes(const QString &in, char c);
int main(int argc, char **argv)
{
- QCA::Initializer qcaInit;
- QCoreApplication app(argc, argv);
-
- if(argc < 3)
- {
- printf("usage: mozcerts [certdata.txt] [outfile.pem]\n");
- return 0;
- }
-
- QFile infile(argv[1]);
- if(!infile.open(QFile::ReadOnly))
- {
- fprintf(stderr, "Error opening input file\n");
- return 1;
- }
-
- QFile outfile(argv[2]);
- if(!outfile.open(QFile::WriteOnly | QFile::Truncate))
- {
- fprintf(stderr, "Error opening output file\n");
- return 1;
- }
-
- int count = 0;
- QString name;
- QTextStream ts(&infile);
- while(!ts.atEnd())
- {
- QString line = ts.readLine();
- if(QRegExp("^#").indexIn(line) != -1)
- continue;
- if(QRegExp("^\\s*$").indexIn(line) != -1)
- continue;
- line = line.trimmed();
-
- if(QRegExp("CKA_LABEL").indexIn(line) != -1)
- {
- QStringList list = splitWithQuotes(line, ' ');
- if(list.count() != 3)
- continue;
-
- name = list[2];
- // make an output filename based on the name
- //outname = name.replace(QRegExp("\\/"), "_")
- // .replace(QRegExp("\\s+"), "_")
- // .replace(QRegExp("[()]"), "=")
- // .replace(QRegExp(","), "_") + ".pem";
- continue;
- }
- else if(QRegExp("CKA_VALUE MULTILINE_OCTAL").indexIn(line) != -1)
- {
- QByteArray buf;
- while(!ts.atEnd())
- {
- line = ts.readLine();
- if(QRegExp("^END").indexIn(line) != -1)
- break;
- line = line.trimmed();
- QRegExp rx("\\\\([0-3][0-7][0-7])");
- int pos = 0;
- while((pos = rx.indexIn(line, pos)) != -1)
- {
- QString str = rx.capturedTexts()[1];
- uchar c = str.toInt(0, 8);
- buf.append(c);
- pos += rx.matchedLength();
- }
- }
-
- printf(">> [%s], %d bytes\n", qPrintable(name), buf.size());
-
- QTextStream ts(&outfile);
- ts << "-----BEGIN CERTIFICATE-----" << '\n';
- QCA::Base64 enc;
- enc.setLineBreaksEnabled(true);
- enc.setLineBreaksColumn(64);
- ts << enc.arrayToString(buf) << '\n';
- ts << "-----END CERTIFICATE-----" << '\n';
-
- ++count;
- }
- }
- printf("Wrote %d certs to [%s]\n", count, argv[2]);
-
- return 0;
+ QCA::Initializer qcaInit;
+ QCoreApplication app(argc, argv);
+
+ if (argc < 3) {
+ printf("usage: mozcerts [certdata.txt] [outfile.pem]\n");
+ return 0;
+ }
+
+ QFile infile(argv[1]);
+ if (!infile.open(QFile::ReadOnly)) {
+ fprintf(stderr, "Error opening input file\n");
+ return 1;
+ }
+
+ QFile outfile(argv[2]);
+ if (!outfile.open(QFile::WriteOnly | QFile::Truncate)) {
+ fprintf(stderr, "Error opening output file\n");
+ return 1;
+ }
+
+ int count = 0;
+ QString name;
+ QTextStream ts(&infile);
+ while (!ts.atEnd()) {
+ QString line = ts.readLine();
+ if (QRegExp("^#").indexIn(line) != -1) {
+ continue;
+ }
+ if (QRegExp("^\\s*$").indexIn(line) != -1) {
+ continue;
+ }
+ line = line.trimmed();
+
+ if (QRegExp("CKA_LABEL").indexIn(line) != -1) {
+ QStringList list = splitWithQuotes(line, ' ');
+ if (list.count() != 3) {
+ continue;
+ }
+
+ name = list[2];
+ // make an output filename based on the name
+ //outname = name.replace(QRegExp("\\/"), "_")
+ // .replace(QRegExp("\\s+"), "_")
+ // .replace(QRegExp("[()]"), "=")
+ // .replace(QRegExp(","), "_") + ".pem";
+ continue;
+ } else if (QRegExp("CKA_VALUE MULTILINE_OCTAL").indexIn(line) != -1) {
+ QByteArray buf;
+ while (!ts.atEnd()) {
+ line = ts.readLine();
+ if (QRegExp("^END").indexIn(line) != -1) {
+ break;
+ }
+ line = line.trimmed();
+ QRegExp rx("\\\\([0-3][0-7][0-7])");
+ int pos = 0;
+ while ((pos = rx.indexIn(line, pos)) != -1) {
+ QString str = rx.capturedTexts()[1];
+ uchar c = str.toInt(0, 8);
+ buf.append(c);
+ pos += rx.matchedLength();
+ }
+ }
+
+ printf(">> [%s], %d bytes\n", qPrintable(name), buf.size());
+
+ QTextStream ts(&outfile);
+ ts << "-----BEGIN CERTIFICATE-----" << '\n';
+ QCA::Base64 enc;
+ enc.setLineBreaksEnabled(true);
+ enc.setLineBreaksColumn(64);
+ ts << enc.arrayToString(buf) << '\n';
+ ts << "-----END CERTIFICATE-----" << '\n';
+
+ ++count;
+ }
+ }
+ printf("Wrote %d certs to [%s]\n", count, argv[2]);
+
+ return 0;
}
int find_notchar(const QString &str, char c, int offset)
{
- for(int n = offset; n < str.length(); ++n)
- {
- if(str[n] != c)
- return n;
- }
- return -1;
+ for (int n = offset; n < str.length(); ++n) {
+ if (str[n] != c) {
+ return n;
+ }
+ }
+ return -1;
}
QStringList splitWithQuotes(const QString &in, char c)
{
- QStringList result;
- int at = 0;
- if(in[at] == c)
- at = find_notchar(in, c, at);
- while(at != -1)
- {
- bool quote = false;
- int end;
- QString str;
- if(in[at] == '\"')
- {
- quote = true;
- ++at;
- end = in.indexOf('\"', at);
- if(end == -1)
- break;
- }
- else
- end = in.indexOf(c, at);
-
- if(end != -1)
- str = in.mid(at, end - at);
- else
- str = in.mid(at);
-
- if(!str.isEmpty())
- result += str;
-
- if(quote)
- end = in.indexOf(c, end);
-
- if(end != -1)
- at = find_notchar(in, c, end);
- else
- at = -1;
- }
- return result;
+ QStringList result;
+ int at = 0;
+ if (in[at] == c) {
+ at = find_notchar(in, c, at);
+ }
+ while (at != -1) {
+ bool quote = false;
+ int end;
+ QString str;
+ if (in[at] == '\"') {
+ quote = true;
+ ++at;
+ end = in.indexOf('\"', at);
+ if (end == -1) {
+ break;
+ }
+ } else {
+ end = in.indexOf(c, at);
+ }
+
+ if (end != -1) {
+ str = in.mid(at, end - at);
+ } else {
+ str = in.mid(at);
+ }
+
+ if (!str.isEmpty()) {
+ result += str;
+ }
+
+ if (quote) {
+ end = in.indexOf(c, end);
+ }
+
+ if (end != -1) {
+ at = find_notchar(in, c, end);
+ } else {
+ at = -1;
+ }
+ }
+ return result;
}
diff --git a/tools/qcatool/main.cpp b/tools/qcatool/main.cpp
index a699e58a..c423086d 100644
--- a/tools/qcatool/main.cpp
+++ b/tools/qcatool/main.cpp
@@ -1,4590 +1,4315 @@
/*
* Copyright (C) 2005-2007 Justin Karneges <justin@affinix.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*
*/
#include <QtCrypto>
#include <QCoreApplication>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QTextStream>
#include <QTimer>
#include <QDir>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
const char *const APPNAME = "qcatool";
const char *const EXENAME = "qcatool";
const char *const VERSION = QCA_VERSION_STR;
static QStringList wrapstring(const QString &str, int width)
{
- QStringList out;
- QString simp = str.simplified();
- QString rest = simp;
- while(1)
- {
- int lastSpace = -1;
- int n;
- for(n = 0; n < rest.length(); ++n)
- {
- if(rest[n].isSpace())
- lastSpace = n;
- if(n == width)
- break;
- }
- if(n == rest.length())
- {
- out += rest;
- break;
- }
-
- QString line;
- if(lastSpace != -1)
- {
- line = rest.mid(0, lastSpace);
- rest = rest.mid(lastSpace + 1);
- }
- else
- {
- line = rest.mid(0, n);
- rest = rest.mid(n);
- }
- out += line;
- }
- return out;
+ QStringList out;
+ QString simp = str.simplified();
+ QString rest = simp;
+ while (1) {
+ int lastSpace = -1;
+ int n;
+ for (n = 0; n < rest.length(); ++n) {
+ if (rest[n].isSpace()) {
+ lastSpace = n;
+ }
+ if (n == width) {
+ break;
+ }
+ }
+ if (n == rest.length()) {
+ out += rest;
+ break;
+ }
+
+ QString line;
+ if (lastSpace != -1) {
+ line = rest.mid(0, lastSpace);
+ rest = rest.mid(lastSpace + 1);
+ } else {
+ line = rest.mid(0, n);
+ rest = rest.mid(n);
+ }
+ out += line;
+ }
+ return out;
}
class StreamLogger : public QCA::AbstractLogDevice
{
public:
- StreamLogger(QTextStream &stream) : QCA::AbstractLogDevice( "Stream logger" ), _stream(stream)
- {
- QCA::logger()->registerLogDevice (this);
- }
-
- ~StreamLogger()
- {
- QCA::logger()->unregisterLogDevice (name ());
- }
-
- void logTextMessage( const QString &message, enum QCA::Logger::Severity severity )
- {
- _stream << now () << " " << severityName (severity) << " " << message << endl;
- }
-
- void logBinaryMessage( const QByteArray &blob, enum QCA::Logger::Severity severity )
- {
- Q_UNUSED(blob);
- _stream << now () << " " << severityName (severity) << " " << "Binary blob not implemented yet" << endl;
- }
+ StreamLogger(QTextStream &stream) : QCA::AbstractLogDevice("Stream logger"), _stream(stream)
+ {
+ QCA::logger()->registerLogDevice(this);
+ }
+
+ ~StreamLogger()
+ {
+ QCA::logger()->unregisterLogDevice(name());
+ }
+
+ void logTextMessage(const QString &message, enum QCA::Logger::Severity severity)
+ {
+ _stream << now() << " " << severityName(severity) << " " << message << endl;
+ }
+
+ void logBinaryMessage(const QByteArray &blob, enum QCA::Logger::Severity severity)
+ {
+ Q_UNUSED(blob);
+ _stream << now() << " " << severityName(severity) << " " << "Binary blob not implemented yet" << endl;
+ }
private:
- inline const char *severityName( enum QCA::Logger::Severity severity )
- {
- if (severity <= QCA::Logger::Debug) {
- return s_severityNames[severity];
- }
- else {
- return s_severityNames[QCA::Logger::Debug+1];
- }
- }
-
- inline QString now() {
- static QString format = "yyyy-MM-dd hh:mm:ss";
- return QDateTime::currentDateTime ().toString (format);
- }
+ inline const char *severityName(enum QCA::Logger::Severity severity)
+ {
+ if (severity <= QCA::Logger::Debug) {
+ return s_severityNames[severity];
+ } else {
+ return s_severityNames[QCA::Logger::Debug + 1];
+ }
+ }
+
+ inline QString now()
+ {
+ static QString format = "yyyy-MM-dd hh:mm:ss";
+ return QDateTime::currentDateTime().toString(format);
+ }
private:
- static const char *s_severityNames[];
- QTextStream &_stream;
+ static const char *s_severityNames[];
+ QTextStream &_stream;
};
const char *StreamLogger::s_severityNames[] = {
- "Q",
- "M",
- "A",
- "C",
- "E",
- "W",
- "N",
- "I",
- "D",
- "U"
+ "Q",
+ "M",
+ "A",
+ "C",
+ "E",
+ "W",
+ "N",
+ "I",
+ "D",
+ "U"
};
static void output_plugin_diagnostic_text()
{
- QString str = QCA::pluginDiagnosticText();
- QCA::clearPluginDiagnosticText();
- if(str[str.length()-1] == '\n')
- str.truncate(str.length()-1);
- QStringList lines = str.split('\n', QString::KeepEmptyParts);
- for(int n = 0; n < lines.count(); ++n)
- fprintf(stderr, "plugin: %s\n", qPrintable(lines[n]));
+ QString str = QCA::pluginDiagnosticText();
+ QCA::clearPluginDiagnosticText();
+ if (str[str.length() - 1] == '\n') {
+ str.truncate(str.length() - 1);
+ }
+ QStringList lines = str.split('\n', QString::KeepEmptyParts);
+ for (int n = 0; n < lines.count(); ++n) {
+ fprintf(stderr, "plugin: %s\n", qPrintable(lines[n]));
+ }
}
static void output_keystore_diagnostic_text()
{
- QString str = QCA::KeyStoreManager::diagnosticText();
- QCA::KeyStoreManager::clearDiagnosticText();
- if(str[str.length()-1] == '\n')
- str.truncate(str.length()-1);
- QStringList lines = str.split('\n', QString::KeepEmptyParts);
- for(int n = 0; n < lines.count(); ++n)
- fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ QString str = QCA::KeyStoreManager::diagnosticText();
+ QCA::KeyStoreManager::clearDiagnosticText();
+ if (str[str.length() - 1] == '\n') {
+ str.truncate(str.length() - 1);
+ }
+ QStringList lines = str.split('\n', QString::KeepEmptyParts);
+ for (int n = 0; n < lines.count(); ++n) {
+ fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ }
}
static void output_message_diagnostic_text(QCA::SecureMessage *msg)
{
- QString str = msg->diagnosticText();
- if(str[str.length()-1] == '\n')
- str.truncate(str.length()-1);
- QStringList lines = str.split('\n', QString::KeepEmptyParts);
- for(int n = 0; n < lines.count(); ++n)
- fprintf(stderr, "message: %s\n", qPrintable(lines[n]));
+ QString str = msg->diagnosticText();
+ if (str[str.length() - 1] == '\n') {
+ str.truncate(str.length() - 1);
+ }
+ QStringList lines = str.split('\n', QString::KeepEmptyParts);
+ for (int n = 0; n < lines.count(); ++n) {
+ fprintf(stderr, "message: %s\n", qPrintable(lines[n]));
+ }
}
class AnimatedKeyGen : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- static QCA::PrivateKey makeKey(QCA::PKey::Type type, int bits, QCA::DLGroupSet set)
- {
- AnimatedKeyGen kg;
- kg.type = type;
- kg.bits = bits;
- kg.set = set;
- QEventLoop eventLoop;
- kg.eventLoop = &eventLoop;
- QTimer::singleShot(0, &kg, SLOT(start()));
- eventLoop.exec();
- QCA::PrivateKey key = kg.key;
- return key;
- }
+ static QCA::PrivateKey makeKey(QCA::PKey::Type type, int bits, QCA::DLGroupSet set)
+ {
+ AnimatedKeyGen kg;
+ kg.type = type;
+ kg.bits = bits;
+ kg.set = set;
+ QEventLoop eventLoop;
+ kg.eventLoop = &eventLoop;
+ QTimer::singleShot(0, &kg, SLOT(start()));
+ eventLoop.exec();
+ QCA::PrivateKey key = kg.key;
+ return key;
+ }
private:
- QCA::PKey::Type type;
- int bits;
- QCA::DLGroupSet set;
- QEventLoop *eventLoop;
- QCA::KeyGenerator gen;
- QCA::DLGroup group;
- QCA::PrivateKey key;
- QTimer t;
- int x;
-
- AnimatedKeyGen()
- {
- gen.setBlockingEnabled(false);
- connect(&gen, SIGNAL(finished()), SLOT(gen_finished()));
- connect(&t, SIGNAL(timeout()), SLOT(t_timeout()));
- }
+ QCA::PKey::Type type;
+ int bits;
+ QCA::DLGroupSet set;
+ QEventLoop *eventLoop;
+ QCA::KeyGenerator gen;
+ QCA::DLGroup group;
+ QCA::PrivateKey key;
+ QTimer t;
+ int x;
+
+ AnimatedKeyGen()
+ {
+ gen.setBlockingEnabled(false);
+ connect(&gen, SIGNAL(finished()), SLOT(gen_finished()));
+ connect(&t, SIGNAL(timeout()), SLOT(t_timeout()));
+ }
private slots:
- void start()
- {
- printf("Generating Key ... ");
- fflush(stdout);
- x = 0;
- t.start(125);
-
- if(type == QCA::PKey::RSA)
- gen.createRSA(bits);
- else
- gen.createDLGroup(set);
- }
-
- void gen_finished()
- {
- if(type == QCA::PKey::DSA || type == QCA::PKey::DH)
- {
- if(group.isNull())
- {
- group = gen.dlGroup();
-
- if(type == QCA::PKey::DSA)
- gen.createDSA(group);
- else
- gen.createDH(group);
- return;
- }
- }
-
- key = gen.key();
-
- printf("\b");
- if(!key.isNull())
- printf("Done\n");
- else
- printf("Error\n");
-
- eventLoop->exit();
- }
-
- void t_timeout()
- {
- if(x == 0)
- printf("\b/");
- else if(x == 1)
- printf("\b-");
- else if(x == 2)
- printf("\b\\");
- else if(x == 3)
- printf("\b|");
- fflush(stdout);
-
- ++x;
- x %= 4;
- }
+ void start()
+ {
+ printf("Generating Key ... ");
+ fflush(stdout);
+ x = 0;
+ t.start(125);
+
+ if (type == QCA::PKey::RSA) {
+ gen.createRSA(bits);
+ } else {
+ gen.createDLGroup(set);
+ }
+ }
+
+ void gen_finished()
+ {
+ if (type == QCA::PKey::DSA || type == QCA::PKey::DH) {
+ if (group.isNull()) {
+ group = gen.dlGroup();
+
+ if (type == QCA::PKey::DSA) {
+ gen.createDSA(group);
+ } else {
+ gen.createDH(group);
+ }
+ return;
+ }
+ }
+
+ key = gen.key();
+
+ printf("\b");
+ if (!key.isNull()) {
+ printf("Done\n");
+ } else {
+ printf("Error\n");
+ }
+
+ eventLoop->exit();
+ }
+
+ void t_timeout()
+ {
+ if (x == 0) {
+ printf("\b/");
+ } else if (x == 1) {
+ printf("\b-");
+ } else if (x == 2) {
+ printf("\b\\");
+ } else if (x == 3) {
+ printf("\b|");
+ }
+ fflush(stdout);
+
+ ++x;
+ x %= 4;
+ }
};
class KeyStoreMonitor : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- static void monitor()
- {
- KeyStoreMonitor monitor;
- QEventLoop eventLoop;
- monitor.eventLoop = &eventLoop;
- QTimer::singleShot(0, &monitor, SLOT(start()));
- eventLoop.exec();
- }
+ static void monitor()
+ {
+ KeyStoreMonitor monitor;
+ QEventLoop eventLoop;
+ monitor.eventLoop = &eventLoop;
+ QTimer::singleShot(0, &monitor, SLOT(start()));
+ eventLoop.exec();
+ }
private:
- QEventLoop *eventLoop;
- QCA::KeyStoreManager *ksm;
- QList<QCA::KeyStore*> keyStores;
- QCA::ConsolePrompt *prompt;
+ QEventLoop *eventLoop;
+ QCA::KeyStoreManager *ksm;
+ QList<QCA::KeyStore *> keyStores;
+ QCA::ConsolePrompt *prompt;
private slots:
- void start()
- {
- // user can quit the monitoring by pressing enter
- printf("Monitoring keystores, press 'q' to quit.\n");
- prompt = new QCA::ConsolePrompt(this);
- connect(prompt, SIGNAL(finished()), SLOT(prompt_finished()));
- prompt->getChar();
-
- // kick off the subsystem
- QCA::KeyStoreManager::start();
-
- // setup keystore manager for monitoring
- ksm = new QCA::KeyStoreManager(this);
- connect(ksm, SIGNAL(keyStoreAvailable(const QString &)), SLOT(ks_available(const QString &)));
- foreach(const QString &keyStoreId, ksm->keyStores())
- ks_available(keyStoreId);
- }
-
- void ks_available(const QString &keyStoreId)
- {
- QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, ksm);
- connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
- connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
- keyStores += ks;
-
- printf(" available: %s\n", qPrintable(ks->name()));
- }
-
- void ks_updated()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
-
- printf(" updated: %s\n", qPrintable(ks->name()));
- }
-
- void ks_unavailable()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
-
- printf(" unavailable: %s\n", qPrintable(ks->name()));
- keyStores.removeAll(ks);
- delete ks;
- }
-
- void prompt_finished()
- {
- QChar c = prompt->resultChar();
- if(c == 'q' || c == 'Q')
- {
- eventLoop->exit();
- return;
- }
- prompt->getChar();
- }
+ void start()
+ {
+ // user can quit the monitoring by pressing enter
+ printf("Monitoring keystores, press 'q' to quit.\n");
+ prompt = new QCA::ConsolePrompt(this);
+ connect(prompt, SIGNAL(finished()), SLOT(prompt_finished()));
+ prompt->getChar();
+
+ // kick off the subsystem
+ QCA::KeyStoreManager::start();
+
+ // setup keystore manager for monitoring
+ ksm = new QCA::KeyStoreManager(this);
+ connect(ksm, SIGNAL(keyStoreAvailable(QString)), SLOT(ks_available(QString)));
+ foreach (const QString &keyStoreId, ksm->keyStores()) {
+ ks_available(keyStoreId);
+ }
+ }
+
+ void ks_available(const QString &keyStoreId)
+ {
+ QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, ksm);
+ connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
+ connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
+ keyStores += ks;
+
+ printf(" available: %s\n", qPrintable(ks->name()));
+ }
+
+ void ks_updated()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+
+ printf(" updated: %s\n", qPrintable(ks->name()));
+ }
+
+ void ks_unavailable()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+
+ printf(" unavailable: %s\n", qPrintable(ks->name()));
+ keyStores.removeAll(ks);
+ delete ks;
+ }
+
+ void prompt_finished()
+ {
+ QChar c = prompt->resultChar();
+ if (c == 'q' || c == 'Q') {
+ eventLoop->exit();
+ return;
+ }
+ prompt->getChar();
+ }
};
class PassphrasePrompt : public QObject
{
- Q_OBJECT
+ Q_OBJECT
public:
- class Item
- {
- public:
- QString promptStr;
- int id;
- QCA::Event event;
- };
-
- QCA::EventHandler handler;
- bool allowPrompt;
- bool warned;
- bool have_pass;
- bool used_pass;
- QCA::SecureArray pass;
- QCA::ConsolePrompt *prompt;
- int prompt_id;
- QCA::Event prompt_event;
- QList<Item> pending;
- bool auto_accept;
-
- QCA::KeyStoreManager ksm;
- QList<QCA::KeyStore*> keyStores;
-
- PassphrasePrompt() : handler(this), ksm(this)
- {
- allowPrompt = true;
- warned = false;
- have_pass = false;
- auto_accept = false;
-
- prompt = 0;
-
- connect(&handler, SIGNAL(eventReady(int, const QCA::Event &)), SLOT(ph_eventReady(int, const QCA::Event &)));
- handler.start();
-
- connect(&ksm, SIGNAL(keyStoreAvailable(const QString &)), SLOT(ks_available(const QString &)));
- foreach(const QString &keyStoreId, ksm.keyStores())
- ks_available(keyStoreId);
- }
-
- ~PassphrasePrompt()
- {
- qDeleteAll(keyStores);
-
- if(prompt)
- {
- handler.reject(prompt_id);
- delete prompt;
- }
-
- while(!pending.isEmpty())
- handler.reject(pending.takeFirst().id);
- }
-
- void setExplicitPassword(const QCA::SecureArray &_pass)
- {
- have_pass = true;
- used_pass = false;
- pass = _pass;
- }
+ class Item
+ {
+ public:
+ QString promptStr;
+ int id;
+ QCA::Event event;
+ };
+
+ QCA::EventHandler handler;
+ bool allowPrompt;
+ bool warned;
+ bool have_pass;
+ bool used_pass;
+ QCA::SecureArray pass;
+ QCA::ConsolePrompt *prompt;
+ int prompt_id;
+ QCA::Event prompt_event;
+ QList<Item> pending;
+ bool auto_accept;
+
+ QCA::KeyStoreManager ksm;
+ QList<QCA::KeyStore *> keyStores;
+
+ PassphrasePrompt() : handler(this), ksm(this)
+ {
+ allowPrompt = true;
+ warned = false;
+ have_pass = false;
+ auto_accept = false;
+
+ prompt = 0;
+
+ connect(&handler, SIGNAL(eventReady(int,QCA::Event)), SLOT(ph_eventReady(int,QCA::Event)));
+ handler.start();
+
+ connect(&ksm, SIGNAL(keyStoreAvailable(QString)), SLOT(ks_available(QString)));
+ foreach (const QString &keyStoreId, ksm.keyStores()) {
+ ks_available(keyStoreId);
+ }
+ }
+
+ ~PassphrasePrompt()
+ {
+ qDeleteAll(keyStores);
+
+ if (prompt) {
+ handler.reject(prompt_id);
+ delete prompt;
+ }
+
+ while (!pending.isEmpty()) {
+ handler.reject(pending.takeFirst().id);
+ }
+ }
+
+ void setExplicitPassword(const QCA::SecureArray &_pass)
+ {
+ have_pass = true;
+ used_pass = false;
+ pass = _pass;
+ }
private slots:
- void ph_eventReady(int id, const QCA::Event &e)
- {
- if(have_pass)
- {
- // only allow using an explicit passphrase once
- if(used_pass)
- {
- handler.reject(id);
- return;
- }
- used_pass = true;
- handler.submitPassword(id, pass);
- return;
- }
-
- if(!allowPrompt)
- {
- if(!have_pass && !warned)
- {
- warned = true;
- fprintf(stderr, "Error: no passphrase specified (use '--pass=' for none).\n");
- }
-
- handler.reject(id);
- return;
- }
-
- if(e.type() == QCA::Event::Password)
- {
- QString type = "password";
- if(e.passwordStyle() == QCA::Event::StylePassphrase)
- type = "passphrase";
- else if(e.passwordStyle() == QCA::Event::StylePIN)
- type = "PIN";
-
- QString str;
- if(e.source() == QCA::Event::KeyStore)
- {
- QString name;
- QCA::KeyStoreEntry entry = e.keyStoreEntry();
- if(!entry.isNull())
- {
- name = entry.name();
- }
- else
- {
- if(e.keyStoreInfo().type() == QCA::KeyStore::SmartCard)
- name = QString("the '") + e.keyStoreInfo().name() + "' token";
- else
- name = e.keyStoreInfo().name();
- }
- str = QString("Enter %1 for %2").arg(type).arg(name);
- }
- else if(!e.fileName().isEmpty())
- str = QString("Enter %1 for %2").arg(type).arg(e.fileName());
- else
- str = QString("Enter %1").arg(type);
-
- if(!prompt)
- {
- prompt = new QCA::ConsolePrompt(this);
- connect(prompt, SIGNAL(finished()), SLOT(prompt_finished()));
- prompt_id = id;
- prompt_event = e;
- prompt->getHidden(str);
- }
- else
- {
- Item i;
- i.promptStr = str;
- i.id = id;
- i.event = e;
- pending += i;
- }
- }
- else if(e.type() == QCA::Event::Token)
- {
- // even though we're being prompted for a missing token,
- // we should still check if the token is present, due to
- // a possible race between insert and token request.
- bool found = false;
-
- // token-only
- if(e.keyStoreEntry().isNull())
- {
- foreach(QCA::KeyStore *ks, keyStores)
- {
- if(ks->id() == e.keyStoreInfo().id())
- {
- found = true;
- break;
- }
- }
- }
- // token-entry
- else
- {
- QCA::KeyStoreEntry kse = e.keyStoreEntry();
-
- QCA::KeyStore *ks = 0;
- foreach(QCA::KeyStore *i, keyStores)
- {
- if(i->id() == e.keyStoreInfo().id())
- {
- ks = i;
- break;
- }
- }
- if(ks)
- {
- QList<QCA::KeyStoreEntry> list = ks->entryList();
- foreach(const QCA::KeyStoreEntry &e, list)
- {
- if(e.id() == kse.id() && kse.isAvailable())
- {
- found = true;
- break;
- }
- }
- }
- }
- if(found)
- {
- // auto-accept
- handler.tokenOkay(id);
- return;
- }
-
- QCA::KeyStoreEntry entry = e.keyStoreEntry();
- QString name;
- if(!entry.isNull())
- {
- name = QString("Please make ") + entry.name() + " (of " + entry.storeName() + ") available";
- }
- else
- {
- name = QString("Please insert the '") + e.keyStoreInfo().name() + "' token";
- }
-
- QString str = QString("%1 and press Enter (or 'q' to cancel) ...").arg(name);
-
- if(!prompt)
- {
- fprintf(stderr, "%s\n", qPrintable(str));
- prompt = new QCA::ConsolePrompt(this);
- connect(prompt, SIGNAL(finished()), SLOT(prompt_finished()));
- prompt_id = id;
- prompt_event = e;
- prompt->getChar();
- }
- else
- {
- Item i;
- i.promptStr = str;
- i.id = id;
- i.event = e;
- pending += i;
- }
- }
- else
- handler.reject(id);
- }
-
- void prompt_finished()
- {
- if(prompt_event.type() == QCA::Event::Password)
- {
- handler.submitPassword(prompt_id, prompt->result());
- }
- else
- {
- if(auto_accept)
- {
- auto_accept = false;
- handler.tokenOkay(prompt_id);
- }
- else
- {
- QChar c = prompt->resultChar();
- if(c == '\r' || c == '\n')
- handler.tokenOkay(prompt_id);
- else if(c == 'q' || c == 'Q')
- handler.reject(prompt_id);
- else
- {
- // retry
- prompt->getChar();
- return;
- }
- }
- }
-
- if(!pending.isEmpty())
- {
- Item i = pending.takeFirst();
- prompt_id = i.id;
- prompt_event = i.event;
- if(i.event.type() == QCA::Event::Password)
- {
- prompt->getHidden(i.promptStr);
- }
- else // Token
- {
- fprintf(stderr, "%s\n", qPrintable(i.promptStr));
- prompt->getChar();
- }
- }
- else
- {
- delete prompt;
- prompt = 0;
- }
- }
-
- void ks_available(const QString &keyStoreId)
- {
- QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, &ksm);
- connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
- connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
- keyStores += ks;
- ks->startAsynchronousMode();
-
- // are we currently in a token-only prompt?
- if(prompt && prompt_event.type() == QCA::Event::Token && prompt_event.keyStoreEntry().isNull())
- {
- // was the token we're looking for just inserted?
- if(prompt_event.keyStoreInfo().id() == keyStoreId)
- {
- fprintf(stderr, "Token inserted! Continuing...\n");
-
- // auto-accept
- auto_accept = true;
- prompt_finished();
- }
- }
- }
-
- void ks_unavailable()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
- keyStores.removeAll(ks);
- delete ks;
- }
-
- void ks_updated()
- {
- QCA::KeyStore *ks = (QCA::KeyStore *)sender();
-
- // are we currently in a token-entry prompt?
- if(prompt && prompt_event.type() == QCA::Event::Token && !prompt_event.keyStoreEntry().isNull())
- {
- QCA::KeyStoreEntry kse = prompt_event.keyStoreEntry();
-
- // was the token of the entry we're looking for updated?
- if(prompt_event.keyStoreInfo().id() == ks->id())
- {
- // is the entry available?
- bool avail = false;
- QList<QCA::KeyStoreEntry> list = ks->entryList();
- foreach(const QCA::KeyStoreEntry &e, list)
- {
- if(e.id() == kse.id())
- {
- avail = kse.isAvailable();
- break;
- }
- }
- if(avail)
- {
- fprintf(stderr, "Entry available! Continuing...\n");
-
- // auto-accept
- auto_accept = true;
- prompt_finished();
- }
- }
- }
- }
+ void ph_eventReady(int id, const QCA::Event &e)
+ {
+ if (have_pass) {
+ // only allow using an explicit passphrase once
+ if (used_pass) {
+ handler.reject(id);
+ return;
+ }
+ used_pass = true;
+ handler.submitPassword(id, pass);
+ return;
+ }
+
+ if (!allowPrompt) {
+ if (!have_pass && !warned) {
+ warned = true;
+ fprintf(stderr, "Error: no passphrase specified (use '--pass=' for none).\n");
+ }
+
+ handler.reject(id);
+ return;
+ }
+
+ if (e.type() == QCA::Event::Password) {
+ QString type = "password";
+ if (e.passwordStyle() == QCA::Event::StylePassphrase) {
+ type = "passphrase";
+ } else if (e.passwordStyle() == QCA::Event::StylePIN) {
+ type = "PIN";
+ }
+
+ QString str;
+ if (e.source() == QCA::Event::KeyStore) {
+ QString name;
+ QCA::KeyStoreEntry entry = e.keyStoreEntry();
+ if (!entry.isNull()) {
+ name = entry.name();
+ } else {
+ if (e.keyStoreInfo().type() == QCA::KeyStore::SmartCard) {
+ name = QString("the '") + e.keyStoreInfo().name() + "' token";
+ } else {
+ name = e.keyStoreInfo().name();
+ }
+ }
+ str = QString("Enter %1 for %2").arg(type).arg(name);
+ } else if (!e.fileName().isEmpty()) {
+ str = QString("Enter %1 for %2").arg(type).arg(e.fileName());
+ } else {
+ str = QString("Enter %1").arg(type);
+ }
+
+ if (!prompt) {
+ prompt = new QCA::ConsolePrompt(this);
+ connect(prompt, SIGNAL(finished()), SLOT(prompt_finished()));
+ prompt_id = id;
+ prompt_event = e;
+ prompt->getHidden(str);
+ } else {
+ Item i;
+ i.promptStr = str;
+ i.id = id;
+ i.event = e;
+ pending += i;
+ }
+ } else if (e.type() == QCA::Event::Token) {
+ // even though we're being prompted for a missing token,
+ // we should still check if the token is present, due to
+ // a possible race between insert and token request.
+ bool found = false;
+
+ // token-only
+ if (e.keyStoreEntry().isNull()) {
+ foreach (QCA::KeyStore *ks, keyStores) {
+ if (ks->id() == e.keyStoreInfo().id()) {
+ found = true;
+ break;
+ }
+ }
+ }
+ // token-entry
+ else {
+ QCA::KeyStoreEntry kse = e.keyStoreEntry();
+
+ QCA::KeyStore *ks = 0;
+ foreach (QCA::KeyStore *i, keyStores) {
+ if (i->id() == e.keyStoreInfo().id()) {
+ ks = i;
+ break;
+ }
+ }
+ if (ks) {
+ QList<QCA::KeyStoreEntry> list = ks->entryList();
+ foreach (const QCA::KeyStoreEntry &e, list) {
+ if (e.id() == kse.id() && kse.isAvailable()) {
+ found = true;
+ break;
+ }
+ }
+ }
+ }
+ if (found) {
+ // auto-accept
+ handler.tokenOkay(id);
+ return;
+ }
+
+ QCA::KeyStoreEntry entry = e.keyStoreEntry();
+ QString name;
+ if (!entry.isNull()) {
+ name = QString("Please make ") + entry.name() + " (of " + entry.storeName() + ") available";
+ } else {
+ name = QString("Please insert the '") + e.keyStoreInfo().name() + "' token";
+ }
+
+ QString str = QString("%1 and press Enter (or 'q' to cancel) ...").arg(name);
+
+ if (!prompt) {
+ fprintf(stderr, "%s\n", qPrintable(str));
+ prompt = new QCA::ConsolePrompt(this);
+ connect(prompt, SIGNAL(finished()), SLOT(prompt_finished()));
+ prompt_id = id;
+ prompt_event = e;
+ prompt->getChar();
+ } else {
+ Item i;
+ i.promptStr = str;
+ i.id = id;
+ i.event = e;
+ pending += i;
+ }
+ } else {
+ handler.reject(id);
+ }
+ }
+
+ void prompt_finished()
+ {
+ if (prompt_event.type() == QCA::Event::Password) {
+ handler.submitPassword(prompt_id, prompt->result());
+ } else {
+ if (auto_accept) {
+ auto_accept = false;
+ handler.tokenOkay(prompt_id);
+ } else {
+ QChar c = prompt->resultChar();
+ if (c == '\r' || c == '\n') {
+ handler.tokenOkay(prompt_id);
+ } else if (c == 'q' || c == 'Q') {
+ handler.reject(prompt_id);
+ } else {
+ // retry
+ prompt->getChar();
+ return;
+ }
+ }
+ }
+
+ if (!pending.isEmpty()) {
+ Item i = pending.takeFirst();
+ prompt_id = i.id;
+ prompt_event = i.event;
+ if (i.event.type() == QCA::Event::Password) {
+ prompt->getHidden(i.promptStr);
+ } else { // Token
+ fprintf(stderr, "%s\n", qPrintable(i.promptStr));
+ prompt->getChar();
+ }
+ } else {
+ delete prompt;
+ prompt = 0;
+ }
+ }
+
+ void ks_available(const QString &keyStoreId)
+ {
+ QCA::KeyStore *ks = new QCA::KeyStore(keyStoreId, &ksm);
+ connect(ks, SIGNAL(updated()), SLOT(ks_updated()));
+ connect(ks, SIGNAL(unavailable()), SLOT(ks_unavailable()));
+ keyStores += ks;
+ ks->startAsynchronousMode();
+
+ // are we currently in a token-only prompt?
+ if (prompt && prompt_event.type() == QCA::Event::Token && prompt_event.keyStoreEntry().isNull()) {
+ // was the token we're looking for just inserted?
+ if (prompt_event.keyStoreInfo().id() == keyStoreId) {
+ fprintf(stderr, "Token inserted! Continuing...\n");
+
+ // auto-accept
+ auto_accept = true;
+ prompt_finished();
+ }
+ }
+ }
+
+ void ks_unavailable()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+ keyStores.removeAll(ks);
+ delete ks;
+ }
+
+ void ks_updated()
+ {
+ QCA::KeyStore *ks = (QCA::KeyStore *)sender();
+
+ // are we currently in a token-entry prompt?
+ if (prompt && prompt_event.type() == QCA::Event::Token && !prompt_event.keyStoreEntry().isNull()) {
+ QCA::KeyStoreEntry kse = prompt_event.keyStoreEntry();
+
+ // was the token of the entry we're looking for updated?
+ if (prompt_event.keyStoreInfo().id() == ks->id()) {
+ // is the entry available?
+ bool avail = false;
+ QList<QCA::KeyStoreEntry> list = ks->entryList();
+ foreach (const QCA::KeyStoreEntry &e, list) {
+ if (e.id() == kse.id()) {
+ avail = kse.isAvailable();
+ break;
+ }
+ }
+ if (avail) {
+ fprintf(stderr, "Entry available! Continuing...\n");
+
+ // auto-accept
+ auto_accept = true;
+ prompt_finished();
+ }
+ }
+ }
+ }
};
class PassphrasePromptThread : public QCA::SyncThread
{
public:
- PassphrasePrompt *pp;
+ PassphrasePrompt *pp;
- PassphrasePromptThread()
- {
- start();
- }
+ PassphrasePromptThread()
+ {
+ start();
+ }
- ~PassphrasePromptThread()
- {
- stop();
- }
+ ~PassphrasePromptThread()
+ {
+ stop();
+ }
protected:
- virtual void atStart()
- {
- pp = new PassphrasePrompt;
- }
-
- virtual void atEnd()
- {
- delete pp;
- }
+ virtual void atStart()
+ {
+ pp = new PassphrasePrompt;
+ }
+
+ virtual void atEnd()
+ {
+ delete pp;
+ }
};
static bool promptForNewPassphrase(QCA::SecureArray *result)
{
- QCA::ConsolePrompt prompt;
- prompt.getHidden("Enter new passphrase");
- prompt.waitForFinished();
- QCA::SecureArray out = prompt.result();
-
- prompt.getHidden("Confirm new passphrase");
- prompt.waitForFinished();
-
- if(prompt.result() != out)
- {
- fprintf(stderr, "Error: confirmation does not match original entry.\n");
- return false;
- }
- *result = out;
- return true;
+ QCA::ConsolePrompt prompt;
+ prompt.getHidden("Enter new passphrase");
+ prompt.waitForFinished();
+ QCA::SecureArray out = prompt.result();
+
+ prompt.getHidden("Confirm new passphrase");
+ prompt.waitForFinished();
+
+ if (prompt.result() != out) {
+ fprintf(stderr, "Error: confirmation does not match original entry.\n");
+ return false;
+ }
+ *result = out;
+ return true;
}
static void ksm_start_and_wait()
{
- // activate the KeyStoreManager and block until ready
- QCA::KeyStoreManager::start();
- {
- QCA::KeyStoreManager ksm;
- ksm.waitForBusyFinished();
- }
+ // activate the KeyStoreManager and block until ready
+ QCA::KeyStoreManager::start();
+ {
+ QCA::KeyStoreManager ksm;
+ ksm.waitForBusyFinished();
+ }
}
static QString line_encode(const QString &in)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- out += "\\\\";
- else if(in[n] == '\n')
- out += "\\n";
- else
- out += in[n];
- }
- return out;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ out += "\\\\";
+ } else if (in[n] == '\n') {
+ out += "\\n";
+ } else {
+ out += in[n];
+ }
+ }
+ return out;
}
static QString line_decode(const QString &in)
{
- QString out;
- for(int n = 0; n < in.length(); ++n)
- {
- if(in[n] == '\\')
- {
- if(n + 1 < in.length())
- {
- if(in[n + 1] == '\\')
- out += '\\';
- else if(in[n + 1] == 'n')
- out += '\n';
- ++n;
- }
- }
- else
- out += in[n];
- }
- return out;
+ QString out;
+ for (int n = 0; n < in.length(); ++n) {
+ if (in[n] == '\\') {
+ if (n + 1 < in.length()) {
+ if (in[n + 1] == '\\') {
+ out += '\\';
+ } else if (in[n + 1] == 'n') {
+ out += '\n';
+ }
+ ++n;
+ }
+ } else {
+ out += in[n];
+ }
+ }
+ return out;
}
static QString make_ksentry_string(const QString &id)
{
- QString out;
- out += "QCATOOL_KEYSTOREENTRY_1\n";
- out += line_encode(id) + '\n';
- return out;
+ QString out;
+ out += "QCATOOL_KEYSTOREENTRY_1\n";
+ out += line_encode(id) + '\n';
+ return out;
}
/*static bool write_ksentry_file(const QString &id, const QString &fileName)
{
- QFile f(fileName);
- if(!f.open(QFile::WriteOnly | QFile::Truncate))
- return false;
- f.write(make_ksentry_string(id).toUtf8());
- return true;
+ QFile f(fileName);
+ if(!f.open(QFile::WriteOnly | QFile::Truncate))
+ return false;
+ f.write(make_ksentry_string(id).toUtf8());
+ return true;
}*/
static QString read_ksentry_file(const QString &fileName)
{
- QString out;
-
- QFile f(fileName);
- if(!f.open(QFile::ReadOnly))
- return out;
- QTextStream ts(&f);
- int linenum = 0;
- while(!ts.atEnd())
- {
- QString line = ts.readLine();
- if(linenum == 0)
- {
- if(line != "QCATOOL_KEYSTOREENTRY_1")
- return out;
- }
- else
- {
- out = line_decode(line);
- break;
- }
- ++linenum;
- }
- return out;
+ QString out;
+
+ QFile f(fileName);
+ if (!f.open(QFile::ReadOnly)) {
+ return out;
+ }
+ QTextStream ts(&f);
+ int linenum = 0;
+ while (!ts.atEnd()) {
+ QString line = ts.readLine();
+ if (linenum == 0) {
+ if (line != "QCATOOL_KEYSTOREENTRY_1") {
+ return out;
+ }
+ } else {
+ out = line_decode(line);
+ break;
+ }
+ ++linenum;
+ }
+ return out;
}
static bool is_pem_file(const QString &fileName)
{
- QFile f(fileName);
- if(!f.open(QFile::ReadOnly))
- return false;
- QTextStream ts(&f);
- if(!ts.atEnd())
- {
- QString line = ts.readLine();
- if(line.startsWith("-----BEGIN"))
- return true;
- }
- return false;
+ QFile f(fileName);
+ if (!f.open(QFile::ReadOnly)) {
+ return false;
+ }
+ QTextStream ts(&f);
+ if (!ts.atEnd()) {
+ QString line = ts.readLine();
+ if (line.startsWith("-----BEGIN")) {
+ return true;
+ }
+ }
+ return false;
}
static QByteArray read_der_file(const QString &fileName)
{
- QFile f(fileName);
- if(!f.open(QFile::ReadOnly))
- return QByteArray();
- return f.readAll();
+ QFile f(fileName);
+ if (!f.open(QFile::ReadOnly)) {
+ return QByteArray();
+ }
+ return f.readAll();
}
class InfoType
{
public:
- QCA::CertificateInfoType type;
- QString varname;
- QString shortname;
- QString name;
- QString desc;
-
- InfoType()
- {
- }
-
- InfoType(QCA::CertificateInfoType _type, const QString &_varname, const QString &_shortname, const QString &_name, const QString &_desc)
- :type(_type), varname(_varname), shortname(_shortname), name(_name), desc(_desc)
- {
- }
+ QCA::CertificateInfoType type;
+ QString varname;
+ QString shortname;
+ QString name;
+ QString desc;
+
+ InfoType()
+ {
+ }
+
+ InfoType(QCA::CertificateInfoType _type, const QString &_varname, const QString &_shortname, const QString &_name, const QString &_desc)
+ : type(_type), varname(_varname), shortname(_shortname), name(_name), desc(_desc)
+ {
+ }
};
static QList<InfoType> makeInfoTypeList(bool legacyEmail = false)
{
- QList<InfoType> out;
- out += InfoType(QCA::CommonName, "CommonName", "CN", "Common Name (CN)", "Full name, domain, anything");
- out += InfoType(QCA::Email, "Email", "", "Email Address", "");
- if(legacyEmail)
- out += InfoType(QCA::EmailLegacy, "EmailLegacy", "", "PKCS#9 Email Address", "");
- out += InfoType(QCA::Organization, "Organization", "O", "Organization (O)", "Company, group, etc");
- out += InfoType(QCA::OrganizationalUnit, "OrganizationalUnit", "OU", "Organizational Unit (OU)", "Division/branch of organization");
- out += InfoType(QCA::Locality, "Locality", "", "Locality (L)", "City, shire, part of a state");
- out += InfoType(QCA::State, "State", "", "State (ST)", "State within the country");
- out += InfoType(QCA::Country, "Country", "C", "Country Code (C)", "2-letter code");
- out += InfoType(QCA::IncorporationLocality, "IncorporationLocality", "", "Incorporation Locality", "For EV certificates");
- out += InfoType(QCA::IncorporationState, "IncorporationState", "", "Incorporation State", "For EV certificates");
- out += InfoType(QCA::IncorporationCountry, "IncorporationCountry", "", "Incorporation Country", "For EV certificates");
- out += InfoType(QCA::URI, "URI", "", "URI", "");
- out += InfoType(QCA::DNS, "DNS", "", "Domain Name", "Domain (dnsName)");
- out += InfoType(QCA::IPAddress, "IPAddress", "", "IP Adddress", "");
- out += InfoType(QCA::XMPP, "XMPP", "", "XMPP Address (JID)", "From RFC 3920 (id-on-xmppAddr)");
- return out;
+ QList<InfoType> out;
+ out += InfoType(QCA::CommonName, "CommonName", "CN", "Common Name (CN)", "Full name, domain, anything");
+ out += InfoType(QCA::Email, "Email", "", "Email Address", "");
+ if (legacyEmail) {
+ out += InfoType(QCA::EmailLegacy, "EmailLegacy", "", "PKCS#9 Email Address", "");
+ }
+ out += InfoType(QCA::Organization, "Organization", "O", "Organization (O)", "Company, group, etc");
+ out += InfoType(QCA::OrganizationalUnit, "OrganizationalUnit", "OU", "Organizational Unit (OU)", "Division/branch of organization");
+ out += InfoType(QCA::Locality, "Locality", "", "Locality (L)", "City, shire, part of a state");
+ out += InfoType(QCA::State, "State", "", "State (ST)", "State within the country");
+ out += InfoType(QCA::Country, "Country", "C", "Country Code (C)", "2-letter code");
+ out += InfoType(QCA::IncorporationLocality, "IncorporationLocality", "", "Incorporation Locality", "For EV certificates");
+ out += InfoType(QCA::IncorporationState, "IncorporationState", "", "Incorporation State", "For EV certificates");
+ out += InfoType(QCA::IncorporationCountry, "IncorporationCountry", "", "Incorporation Country", "For EV certificates");
+ out += InfoType(QCA::URI, "URI", "", "URI", "");
+ out += InfoType(QCA::DNS, "DNS", "", "Domain Name", "Domain (dnsName)");
+ out += InfoType(QCA::IPAddress, "IPAddress", "", "IP Adddress", "");
+ out += InfoType(QCA::XMPP, "XMPP", "", "XMPP Address (JID)", "From RFC 3920 (id-on-xmppAddr)");
+ return out;
}
class MyConstraintType
{
public:
- QCA::ConstraintType type;
- QString varname;
- QString name;
- QString desc;
-
- MyConstraintType()
- {
- }
-
- MyConstraintType(const QCA::ConstraintType &_type, const QString &_varname, const QString &_name, const QString &_desc)
- :type(_type), varname(_varname), name(_name), desc(_desc)
- {
- }
+ QCA::ConstraintType type;
+ QString varname;
+ QString name;
+ QString desc;
+
+ MyConstraintType()
+ {
+ }
+
+ MyConstraintType(const QCA::ConstraintType &_type, const QString &_varname, const QString &_name, const QString &_desc)
+ : type(_type), varname(_varname), name(_name), desc(_desc)
+ {
+ }
};
static QList<MyConstraintType> makeConstraintTypeList()
{
- QList<MyConstraintType> out;
- out += MyConstraintType(QCA::DigitalSignature, "DigitalSignature", "Digital Signature", "Can be used for signing");
- out += MyConstraintType(QCA::NonRepudiation, "NonRepudiation", "Non-Repudiation", "Usage is legally binding");
- out += MyConstraintType(QCA::KeyEncipherment, "KeyEncipherment", "Key Encipherment", "Can encrypt other keys");
- out += MyConstraintType(QCA::DataEncipherment, "DataEncipherment", "Data Encipherment", "Can encrypt arbitrary data");
- out += MyConstraintType(QCA::KeyAgreement, "KeyAgreement", "Key Agreement", "Can perform key agreement (DH)");
- out += MyConstraintType(QCA::KeyCertificateSign, "KeyCertificateSign", "Certificate Sign", "Can sign other certificates");
- out += MyConstraintType(QCA::CRLSign, "CRLSign", "CRL Sign", "Can sign CRLs");
- out += MyConstraintType(QCA::EncipherOnly, "EncipherOnly", "Encipher Only", "Can be used for encrypting");
- out += MyConstraintType(QCA::DecipherOnly, "DecipherOnly", "Decipher Only", "Can be used for decrypting");
- out += MyConstraintType(QCA::ServerAuth, "ServerAuth", "Server Authentication", "TLS Server");
- out += MyConstraintType(QCA::ClientAuth, "ClientAuth", "Client Authentication", "TLS Client");
- out += MyConstraintType(QCA::CodeSigning, "CodeSigning", "Code Signing", "");
- out += MyConstraintType(QCA::EmailProtection, "EmailProtection", "Email Protection", "S/MIME");
- out += MyConstraintType(QCA::IPSecEndSystem, "IPSecEndSystem", "IPSec End-System", "");
- out += MyConstraintType(QCA::IPSecTunnel, "IPSecTunnel", "IPSec Tunnel", "");
- out += MyConstraintType(QCA::IPSecUser, "IPSecUser", "IPSec User", "");
- out += MyConstraintType(QCA::TimeStamping, "TimeStamping", "Time Stamping", "");
- out += MyConstraintType(QCA::OCSPSigning, "OCSPSigning", "OCSP Signing", "");
- return out;
+ QList<MyConstraintType> out;
+ out += MyConstraintType(QCA::DigitalSignature, "DigitalSignature", "Digital Signature", "Can be used for signing");
+ out += MyConstraintType(QCA::NonRepudiation, "NonRepudiation", "Non-Repudiation", "Usage is legally binding");
+ out += MyConstraintType(QCA::KeyEncipherment, "KeyEncipherment", "Key Encipherment", "Can encrypt other keys");
+ out += MyConstraintType(QCA::DataEncipherment, "DataEncipherment", "Data Encipherment", "Can encrypt arbitrary data");
+ out += MyConstraintType(QCA::KeyAgreement, "KeyAgreement", "Key Agreement", "Can perform key agreement (DH)");
+ out += MyConstraintType(QCA::KeyCertificateSign, "KeyCertificateSign", "Certificate Sign", "Can sign other certificates");
+ out += MyConstraintType(QCA::CRLSign, "CRLSign", "CRL Sign", "Can sign CRLs");
+ out += MyConstraintType(QCA::EncipherOnly, "EncipherOnly", "Encipher Only", "Can be used for encrypting");
+ out += MyConstraintType(QCA::DecipherOnly, "DecipherOnly", "Decipher Only", "Can be used for decrypting");
+ out += MyConstraintType(QCA::ServerAuth, "ServerAuth", "Server Authentication", "TLS Server");
+ out += MyConstraintType(QCA::ClientAuth, "ClientAuth", "Client Authentication", "TLS Client");
+ out += MyConstraintType(QCA::CodeSigning, "CodeSigning", "Code Signing", "");
+ out += MyConstraintType(QCA::EmailProtection, "EmailProtection", "Email Protection", "S/MIME");
+ out += MyConstraintType(QCA::IPSecEndSystem, "IPSecEndSystem", "IPSec End-System", "");
+ out += MyConstraintType(QCA::IPSecTunnel, "IPSecTunnel", "IPSec Tunnel", "");
+ out += MyConstraintType(QCA::IPSecUser, "IPSecUser", "IPSec User", "");
+ out += MyConstraintType(QCA::TimeStamping, "TimeStamping", "Time Stamping", "");
+ out += MyConstraintType(QCA::OCSPSigning, "OCSPSigning", "OCSP Signing", "");
+ return out;
}
const char *crlEntryReasonToString(QCA::CRLEntry::Reason r)
{
- switch(r)
- {
- case QCA::CRLEntry::Unspecified: return "Unspecified";
- case QCA::CRLEntry::KeyCompromise: return "KeyCompromise";
- case QCA::CRLEntry::CACompromise: return "CACompromise";
- case QCA::CRLEntry::AffiliationChanged: return "AffiliationChanged";
- case QCA::CRLEntry::Superseded: return "Superseded";
- case QCA::CRLEntry::CessationOfOperation: return "CessationOfOperation";
- case QCA::CRLEntry::CertificateHold: return "CertificateHold";
- case QCA::CRLEntry::RemoveFromCRL: return "RemoveFromCRL";
- case QCA::CRLEntry::PrivilegeWithdrawn: return "PrivilegeWithdrawn";
- case QCA::CRLEntry::AACompromise: return "AACompromise";
- default: return "Unknown";
- }
+ switch (r) {
+ case QCA::CRLEntry::Unspecified: return "Unspecified";
+ case QCA::CRLEntry::KeyCompromise: return "KeyCompromise";
+ case QCA::CRLEntry::CACompromise: return "CACompromise";
+ case QCA::CRLEntry::AffiliationChanged: return "AffiliationChanged";
+ case QCA::CRLEntry::Superseded: return "Superseded";
+ case QCA::CRLEntry::CessationOfOperation: return "CessationOfOperation";
+ case QCA::CRLEntry::CertificateHold: return "CertificateHold";
+ case QCA::CRLEntry::RemoveFromCRL: return "RemoveFromCRL";
+ case QCA::CRLEntry::PrivilegeWithdrawn: return "PrivilegeWithdrawn";
+ case QCA::CRLEntry::AACompromise: return "AACompromise";
+ default: return "Unknown";
+ }
}
static bool validOid(const QString &in)
{
- for(int n = 0; n < in.length(); ++n)
- {
- if(!in[n].isDigit() && in[n] != '.')
- return false;
- }
- return true;
+ for (int n = 0; n < in.length(); ++n) {
+ if (!in[n].isDigit() && in[n] != '.') {
+ return false;
+ }
+ }
+ return true;
}
class ValidityLength
{
public:
- int years, months, days;
+ int years, months, days;
};
static int vl_getnext(const QString &in, int offset = 0)
{
- if(offset >= in.length())
- return in.length();
-
- int n = offset;
- bool lookForNonDigit;
-
- if(in[n].isDigit())
- lookForNonDigit = true;
- else
- lookForNonDigit = false;
-
- for(++n; n < in.length(); ++n)
- {
- if(in[n].isDigit() != lookForNonDigit)
- break;
- }
- return n;
+ if (offset >= in.length()) {
+ return in.length();
+ }
+
+ int n = offset;
+ bool lookForNonDigit;
+
+ if (in[n].isDigit()) {
+ lookForNonDigit = true;
+ } else {
+ lookForNonDigit = false;
+ }
+
+ for (++n; n < in.length(); ++n) {
+ if (in[n].isDigit() != lookForNonDigit) {
+ break;
+ }
+ }
+ return n;
}
static QStringList vl_getparts(const QString &in)
{
- QStringList out;
- int offset = 0;
- while(1)
- {
- int n = vl_getnext(in, offset);
- if(n == offset)
- break;
- out += in.mid(offset, n - offset);
- offset = n;
- }
- return out;
+ QStringList out;
+ int offset = 0;
+ while (1) {
+ int n = vl_getnext(in, offset);
+ if (n == offset) {
+ break;
+ }
+ out += in.mid(offset, n - offset);
+ offset = n;
+ }
+ return out;
}
static bool parseValidityLength(const QString &in, ValidityLength *vl)
{
- vl->years = -1;
- vl->months = -1;
- vl->days = -1;
-
- QStringList parts = vl_getparts(in);
- while(1)
- {
- // first part should be a number
- if(parts.count() < 1)
- break;
- QString str = parts.takeFirst();
- bool ok;
- int x = str.toInt(&ok);
- if(!ok)
- return false;
-
- // next part should be 1 letter plus any amount of space
- if(parts.count() < 1)
- return false;
- str = parts.takeFirst();
- if(!str[0].isLetter())
- return false;
- str = str.trimmed(); // remove space
-
- if(str == "y")
- {
- if(vl->years != -1)
- return false;
- vl->years = x;
- }
- if(str == "m")
- {
- if(vl->months != -1)
- return false;
- vl->months = x;
- }
- if(str == "d")
- {
- if(vl->days != -1)
- return false;
- vl->days = x;
- }
- }
-
- if(vl->years == -1)
- vl->years = 0;
- if(vl->months == -1)
- vl->months = 0;
- if(vl->days == -1)
- vl->days = 0;
-
- return true;
+ vl->years = -1;
+ vl->months = -1;
+ vl->days = -1;
+
+ QStringList parts = vl_getparts(in);
+ while (1) {
+ // first part should be a number
+ if (parts.count() < 1) {
+ break;
+ }
+ QString str = parts.takeFirst();
+ bool ok;
+ int x = str.toInt(&ok);
+ if (!ok) {
+ return false;
+ }
+
+ // next part should be 1 letter plus any amount of space
+ if (parts.count() < 1) {
+ return false;
+ }
+ str = parts.takeFirst();
+ if (!str[0].isLetter()) {
+ return false;
+ }
+ str = str.trimmed(); // remove space
+
+ if (str == "y") {
+ if (vl->years != -1) {
+ return false;
+ }
+ vl->years = x;
+ }
+ if (str == "m") {
+ if (vl->months != -1) {
+ return false;
+ }
+ vl->months = x;
+ }
+ if (str == "d") {
+ if (vl->days != -1) {
+ return false;
+ }
+ vl->days = x;
+ }
+ }
+
+ if (vl->years == -1) {
+ vl->years = 0;
+ }
+ if (vl->months == -1) {
+ vl->months = 0;
+ }
+ if (vl->days == -1) {
+ vl->days = 0;
+ }
+
+ return true;
}
static QString prompt_for(const QString &prompt)
{
- printf("%s: ", prompt.toLatin1().data());
- fflush(stdout);
- QByteArray result(256, 0);
- if(fgets((char *)result.data(), result.size(), stdin))
- return QString::fromLocal8Bit(result).trimmed();
- else
- return QString();
+ printf("%s: ", prompt.toLatin1().data());
+ fflush(stdout);
+ QByteArray result(256, 0);
+ if (fgets((char *)result.data(), result.size(), stdin)) {
+ return QString::fromLocal8Bit(result).trimmed();
+ } else {
+ return QString();
+ }
}
static QCA::CertificateOptions promptForCertAttributes(bool advanced, bool req)
{
- QCA::CertificateOptions opts;
-
- if(advanced)
- {
- if(!req)
- {
- while(1)
- {
- QString str = prompt_for("Create an end user ('user') certificate or a CA ('ca') certificate? [user]");
- if(str.isEmpty())
- str = "user";
- if(str != "user" && str != "ca")
- {
- printf("'%s' is not a valid entry.\n", qPrintable(str));
- continue;
- }
-
- if(str == "ca")
- opts.setAsCA();
- break;
- }
- printf("\n");
-
- while(1)
- {
- QString str = prompt_for("Serial Number");
- QCA::BigInteger num;
- if(str.isEmpty() || !num.fromString(str))
- {
- printf("'%s' is not a valid entry.\n", qPrintable(str));
- continue;
- }
-
- opts.setSerialNumber(num);
- break;
- }
- printf("\n");
- }
-
- {
- QCA::CertificateInfoOrdered info;
- printf("Choose the information attributes to add to the certificate. They will be\n"
- "added in the order they are entered.\n\n");
- printf("Available information attributes:\n");
- QList<InfoType> list = makeInfoTypeList();
- for(int n = 0; n < list.count(); ++n)
- {
- const InfoType &i = list[n];
- char c = 'a' + n;
- printf(" %c) %-32s %s\n", c, qPrintable(i.name), qPrintable(i.desc));
- }
- printf("\n");
- while(1)
- {
- int index;
- while(1)
- {
- QString str = prompt_for("Select an attribute to add, or enter to move on");
- if(str.isEmpty())
- {
- index = -1;
- break;
- }
- if(str.length() == 1)
- {
- index = str[0].toLatin1() - 'a';
- if(index >= 0 && index < list.count())
- break;
- }
- printf("'%s' is not a valid entry.\n", qPrintable(str));
- }
- if(index == -1)
- break;
-
- QString val = prompt_for(list[index].name);
- info += QCA::CertificateInfoPair(list[index].type, val);
- printf("Added attribute.\n\n");
- }
- opts.setInfoOrdered(info);
- }
-
- {
- QCA::Constraints constraints;
- printf("\n");
- printf("Choose the constraint attributes to add to the certificate.\n\n");
- printf("Available attributes:\n");
- QList<MyConstraintType> list = makeConstraintTypeList();
- for(int n = 0; n < list.count(); ++n)
- {
- const MyConstraintType &i = list[n];
- char c = 'a' + n;
- printf(" %c) %-32s %s\n", c, qPrintable(i.name), qPrintable(i.desc));
- }
- printf("\n");
- printf("If no constraints are added, then the certificate may be used for any purpose.\n\n");
- while(1)
- {
- int index;
- while(1)
- {
- QString str = prompt_for("Select an attribute to add, or enter to move on");
- if(str.isEmpty())
- {
- index = -1;
- break;
- }
- if(str.length() == 1)
- {
- index = str[0].toLatin1() - 'a';
- if(index >= 0 && index < list.count())
- break;
- }
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- }
- if(index == -1)
- break;
-
- if(constraints.contains(list[index].type))
- {
- printf("You have already added '%s'.\n\n", qPrintable(list[index].name));
- continue;
- }
-
- constraints += list[index].type;
- printf("Added attribute.\n\n");
- }
- opts.setConstraints(constraints);
- }
-
- {
- QStringList policies;
- printf("\n");
- printf("Are there any policy OID attributes that you wish to add? Use the dotted\n"
- "string format.\n\n");
- while(1)
- {
- QString str = prompt_for("Enter a policy OID to add, or enter to move on");
- if(str.isEmpty())
- break;
- if(!validOid(str))
- {
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- continue;
- }
- if(policies.contains(str))
- {
- printf("You have already added '%s'.\n\n", qPrintable(str));
- continue;
- }
-
- policies += str;
- printf("Added attribute.\n\n");
- }
- opts.setPolicies(policies);
- }
-
- printf("\n");
- }
- else
- {
- QCA::CertificateInfo info;
- info.insert(QCA::CommonName, prompt_for("Common Name"));
- info.insert(QCA::Country, prompt_for("Country Code (2 letters)"));
- info.insert(QCA::Organization, prompt_for("Organization"));
- info.insert(QCA::Email, prompt_for("Email"));
- opts.setInfo(info);
-
- printf("\n");
- }
-
- if(!req)
- {
- while(1)
- {
- QString str = prompt_for("How long should the certificate be valid? (e.g. '1y2m3d')");
- ValidityLength vl;
- if(!parseValidityLength(str, &vl))
- {
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- continue;
- }
-
- if(vl.years == 0 && vl.months == 0 && vl.days == 0)
- {
- printf("The certificate must be valid for at least one day.\n\n");
- continue;
- }
-
- QDateTime start = QDateTime::currentDateTime().toUTC();
- QDateTime end = start;
- if(vl.years > 0)
- end = end.addYears(vl.years);
- if(vl.months > 0)
- end = end.addMonths(vl.months);
- if(vl.days > 0)
- end = end.addDays(vl.days);
- opts.setValidityPeriod(start, end);
-
- QStringList parts;
- if(vl.years > 0)
- parts += QString("%1 year(s)").arg(vl.years);
- if(vl.months > 0)
- parts += QString("%1 month(s)").arg(vl.months);
- if(vl.days > 0)
- parts += QString("%1 day(s)").arg(vl.days);
- QString out;
- if(parts.count() == 1)
- out = parts[0];
- else if(parts.count() == 2)
- out = parts[0] + " and " + parts[1];
- else if(parts.count() == 3)
- out = parts[0] + ", " + parts[1] + ", and " + parts[2];
- printf("Certificate will be valid for %s.\n", qPrintable(out));
- break;
- }
- printf("\n");
- }
-
- return opts;
+ QCA::CertificateOptions opts;
+
+ if (advanced) {
+ if (!req) {
+ while (1) {
+ QString str = prompt_for("Create an end user ('user') certificate or a CA ('ca') certificate? [user]");
+ if (str.isEmpty()) {
+ str = "user";
+ }
+ if (str != "user" && str != "ca") {
+ printf("'%s' is not a valid entry.\n", qPrintable(str));
+ continue;
+ }
+
+ if (str == "ca") {
+ opts.setAsCA();
+ }
+ break;
+ }
+ printf("\n");
+
+ while (1) {
+ QString str = prompt_for("Serial Number");
+ QCA::BigInteger num;
+ if (str.isEmpty() || !num.fromString(str)) {
+ printf("'%s' is not a valid entry.\n", qPrintable(str));
+ continue;
+ }
+
+ opts.setSerialNumber(num);
+ break;
+ }
+ printf("\n");
+ }
+
+ {
+ QCA::CertificateInfoOrdered info;
+ printf("Choose the information attributes to add to the certificate. They will be\n"
+ "added in the order they are entered.\n\n");
+ printf("Available information attributes:\n");
+ QList<InfoType> list = makeInfoTypeList();
+ for (int n = 0; n < list.count(); ++n) {
+ const InfoType &i = list[n];
+ char c = 'a' + n;
+ printf(" %c) %-32s %s\n", c, qPrintable(i.name), qPrintable(i.desc));
+ }
+ printf("\n");
+ while (1) {
+ int index;
+ while (1) {
+ QString str = prompt_for("Select an attribute to add, or enter to move on");
+ if (str.isEmpty()) {
+ index = -1;
+ break;
+ }
+ if (str.length() == 1) {
+ index = str[0].toLatin1() - 'a';
+ if (index >= 0 && index < list.count()) {
+ break;
+ }
+ }
+ printf("'%s' is not a valid entry.\n", qPrintable(str));
+ }
+ if (index == -1) {
+ break;
+ }
+
+ QString val = prompt_for(list[index].name);
+ info += QCA::CertificateInfoPair(list[index].type, val);
+ printf("Added attribute.\n\n");
+ }
+ opts.setInfoOrdered(info);
+ }
+
+ {
+ QCA::Constraints constraints;
+ printf("\n");
+ printf("Choose the constraint attributes to add to the certificate.\n\n");
+ printf("Available attributes:\n");
+ QList<MyConstraintType> list = makeConstraintTypeList();
+ for (int n = 0; n < list.count(); ++n) {
+ const MyConstraintType &i = list[n];
+ char c = 'a' + n;
+ printf(" %c) %-32s %s\n", c, qPrintable(i.name), qPrintable(i.desc));
+ }
+ printf("\n");
+ printf("If no constraints are added, then the certificate may be used for any purpose.\n\n");
+ while (1) {
+ int index;
+ while (1) {
+ QString str = prompt_for("Select an attribute to add, or enter to move on");
+ if (str.isEmpty()) {
+ index = -1;
+ break;
+ }
+ if (str.length() == 1) {
+ index = str[0].toLatin1() - 'a';
+ if (index >= 0 && index < list.count()) {
+ break;
+ }
+ }
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ }
+ if (index == -1) {
+ break;
+ }
+
+ if (constraints.contains(list[index].type)) {
+ printf("You have already added '%s'.\n\n", qPrintable(list[index].name));
+ continue;
+ }
+
+ constraints += list[index].type;
+ printf("Added attribute.\n\n");
+ }
+ opts.setConstraints(constraints);
+ }
+
+ {
+ QStringList policies;
+ printf("\n");
+ printf("Are there any policy OID attributes that you wish to add? Use the dotted\n"
+ "string format.\n\n");
+ while (1) {
+ QString str = prompt_for("Enter a policy OID to add, or enter to move on");
+ if (str.isEmpty()) {
+ break;
+ }
+ if (!validOid(str)) {
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ continue;
+ }
+ if (policies.contains(str)) {
+ printf("You have already added '%s'.\n\n", qPrintable(str));
+ continue;
+ }
+
+ policies += str;
+ printf("Added attribute.\n\n");
+ }
+ opts.setPolicies(policies);
+ }
+
+ printf("\n");
+ } else {
+ QCA::CertificateInfo info;
+ info.insert(QCA::CommonName, prompt_for("Common Name"));
+ info.insert(QCA::Country, prompt_for("Country Code (2 letters)"));
+ info.insert(QCA::Organization, prompt_for("Organization"));
+ info.insert(QCA::Email, prompt_for("Email"));
+ opts.setInfo(info);
+
+ printf("\n");
+ }
+
+ if (!req) {
+ while (1) {
+ QString str = prompt_for("How long should the certificate be valid? (e.g. '1y2m3d')");
+ ValidityLength vl;
+ if (!parseValidityLength(str, &vl)) {
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ continue;
+ }
+
+ if (vl.years == 0 && vl.months == 0 && vl.days == 0) {
+ printf("The certificate must be valid for at least one day.\n\n");
+ continue;
+ }
+
+ QDateTime start = QDateTime::currentDateTime().toUTC();
+ QDateTime end = start;
+ if (vl.years > 0) {
+ end = end.addYears(vl.years);
+ }
+ if (vl.months > 0) {
+ end = end.addMonths(vl.months);
+ }
+ if (vl.days > 0) {
+ end = end.addDays(vl.days);
+ }
+ opts.setValidityPeriod(start, end);
+
+ QStringList parts;
+ if (vl.years > 0) {
+ parts += QString("%1 year(s)").arg(vl.years);
+ }
+ if (vl.months > 0) {
+ parts += QString("%1 month(s)").arg(vl.months);
+ }
+ if (vl.days > 0) {
+ parts += QString("%1 day(s)").arg(vl.days);
+ }
+ QString out;
+ if (parts.count() == 1) {
+ out = parts[0];
+ } else if (parts.count() == 2) {
+ out = parts[0] + " and " + parts[1];
+ } else if (parts.count() == 3) {
+ out = parts[0] + ", " + parts[1] + ", and " + parts[2];
+ }
+ printf("Certificate will be valid for %s.\n", qPrintable(out));
+ break;
+ }
+ printf("\n");
+ }
+
+ return opts;
}
// qsettings seems to give us a string type for both bool and int (and
// possibly others, but those are the only two we care about here).
// in order to figure out what is actually a bool or an int, we need
// to examine the string. so for the functions below, we convert
// the variant to a string, and then inspect it to see if it looks
// like a bool or an int.
static bool string_is_bool(const QString &in)
{
- QString lc = in.toLower();
- if(lc == "true" || lc == "false")
- return true;
- return false;
+ QString lc = in.toLower();
+ if (lc == "true" || lc == "false") {
+ return true;
+ }
+ return false;
}
static bool string_is_int(const QString &in)
{
- bool ok;
- in.toInt(&ok);
- return ok;
+ bool ok;
+ in.toInt(&ok);
+ return ok;
}
static bool variant_is_bool(const QVariant &in)
{
#if QT_VERSION >= 0x050000
- if(in.canConvert<QString>() && string_is_bool(in.toString()))
+ if (in.canConvert<QString>() && string_is_bool(in.toString()))
#else
- if(qVariantCanConvert<QString>(in) && string_is_bool(in.toString()))
+ if (qVariantCanConvert<QString>(in) && string_is_bool(in.toString()))
#endif
- return true;
- return false;
+ return true;
+ return false;
}
static bool variant_is_int(const QVariant &in)
{
#if QT_VERSION >= 0x050000
- if(in.canConvert<QString>() && string_is_int(in.toString()))
+ if (in.canConvert<QString>() && string_is_int(in.toString()))
#else
- if(qVariantCanConvert<QString>(in) && string_is_int(in.toString()))
+ if (qVariantCanConvert<QString>(in) && string_is_int(in.toString()))
#endif
- return true;
- return false;
+ return true;
+ return false;
}
static QString prompt_for_string(const QString &prompt, const QString &def = QString())
{
- printf("%s", prompt.toLatin1().data());
- fflush(stdout);
- QByteArray result(256, 0);
- if(!fgets((char *)result.data(), result.size(), stdin))
- return QString();
- if(result[result.length()-1] == '\n')
- result.truncate(result.length()-1);
- // empty input -> use default
- if(result.isEmpty())
- return def;
- // trimmed input could result in an empty value, but in that case
- // it is treated as if the user wishes to submit an empty value.
- return QString::fromLocal8Bit(result).trimmed();
+ printf("%s", prompt.toLatin1().data());
+ fflush(stdout);
+ QByteArray result(256, 0);
+ if (!fgets((char *)result.data(), result.size(), stdin)) {
+ return QString();
+ }
+ if (result[result.length() - 1] == '\n') {
+ result.truncate(result.length() - 1);
+ }
+ // empty input -> use default
+ if (result.isEmpty()) {
+ return def;
+ }
+ // trimmed input could result in an empty value, but in that case
+ // it is treated as if the user wishes to submit an empty value.
+ return QString::fromLocal8Bit(result).trimmed();
}
static int prompt_for_int(const QString &prompt, int def = 0)
{
- while(1)
- {
- QString str = prompt_for_string(prompt);
- if(str.isEmpty())
- return def;
- bool ok;
- int x = str.toInt(&ok);
- if(ok)
- return x;
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- }
+ while (1) {
+ QString str = prompt_for_string(prompt);
+ if (str.isEmpty()) {
+ return def;
+ }
+ bool ok;
+ int x = str.toInt(&ok);
+ if (ok) {
+ return x;
+ }
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ }
}
static bool partial_compare_nocase(const QString &in, const QString &target, int min = 1)
{
- if(in.length() >= min && in.length() <= target.length() && target.mid(0, in.length()).toLower() == in.toLower())
- return true;
- return false;
+ if (in.length() >= min && in.length() <= target.length() && target.mid(0, in.length()).toLower() == in.toLower()) {
+ return true;
+ }
+ return false;
}
static bool prompt_for_bool(const QString &prompt, bool def = false)
{
- while(1)
- {
- QString str = prompt_for_string(prompt);
- if(str.isEmpty())
- return def;
- if(partial_compare_nocase(str, "true"))
- return true;
- else if(partial_compare_nocase(str, "false"))
- return false;
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- }
+ while (1) {
+ QString str = prompt_for_string(prompt);
+ if (str.isEmpty()) {
+ return def;
+ }
+ if (partial_compare_nocase(str, "true")) {
+ return true;
+ } else if (partial_compare_nocase(str, "false")) {
+ return false;
+ }
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ }
}
static bool prompt_for_yesno(const QString &prompt, bool def = false)
{
- while(1)
- {
- QString str = prompt_for_string(prompt);
- if(str.isEmpty())
- return def;
- if(partial_compare_nocase(str, "yes"))
- return true;
- else if(partial_compare_nocase(str, "no"))
- return false;
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- }
+ while (1) {
+ QString str = prompt_for_string(prompt);
+ if (str.isEmpty()) {
+ return def;
+ }
+ if (partial_compare_nocase(str, "yes")) {
+ return true;
+ } else if (partial_compare_nocase(str, "no")) {
+ return false;
+ }
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ }
}
static QString prompt_for_slotevent_method(const QString &prompt, const QString &def = QString())
{
- while(1)
- {
- QString str = prompt_for_string(prompt);
- if(str.isEmpty())
- return def;
- if(partial_compare_nocase(str, "auto"))
- return "auto";
- else if(partial_compare_nocase(str, "trigger"))
- return "trigger";
- else if(partial_compare_nocase(str, "poll"))
- return "poll";
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- }
+ while (1) {
+ QString str = prompt_for_string(prompt);
+ if (str.isEmpty()) {
+ return def;
+ }
+ if (partial_compare_nocase(str, "auto")) {
+ return "auto";
+ } else if (partial_compare_nocase(str, "trigger")) {
+ return "trigger";
+ } else if (partial_compare_nocase(str, "poll")) {
+ return "poll";
+ }
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ }
}
static QVariantMap provider_config_edit_generic(const QVariantMap &in)
{
- QVariantMap config = in;
- QMutableMapIterator<QString,QVariant> it(config);
- while(it.hasNext())
- {
- it.next();
- QString var = it.key();
- if(var == "formtype")
- continue;
- QVariant val = it.value();
-
- // fields must be bool, int, or string
- QVariant newval;
- QString prompt = QString("%1: [%2] ").arg(var).arg(val.toString());
- if(variant_is_bool(val))
- newval = prompt_for_bool(QString("bool ") + prompt, val.toBool());
- else if(variant_is_int(val))
- newval = prompt_for_int(QString("int ") + prompt, val.toInt());
+ QVariantMap config = in;
+ QMutableMapIterator<QString, QVariant> it(config);
+ while (it.hasNext()) {
+ it.next();
+ QString var = it.key();
+ if (var == "formtype") {
+ continue;
+ }
+ QVariant val = it.value();
+
+ // fields must be bool, int, or string
+ QVariant newval;
+ QString prompt = QString("%1: [%2] ").arg(var).arg(val.toString());
+ if (variant_is_bool(val)) {
+ newval = prompt_for_bool(QString("bool ") + prompt, val.toBool());
+ } else if (variant_is_int(val)) {
+ newval = prompt_for_int(QString("int ") + prompt, val.toInt());
+ }
#if QT_VERSION >= 0x050000
- else if(val.canConvert<QString>())
+ else if (val.canConvert<QString>())
#else
- else if(qVariantCanConvert<QString>(val))
+ else if (qVariantCanConvert<QString>(val))
#endif
- newval = prompt_for_string(QString("string ") + prompt, val.toString());
- else
- continue; // skip bogus fields
+ newval = prompt_for_string(QString("string ") + prompt, val.toString());
+ else {
+ continue; // skip bogus fields
+ }
- it.setValue(newval);
- }
+ it.setValue(newval);
+ }
- return config;
+ return config;
}
class Pkcs11ProviderConfig
{
public:
- bool allow_protected_authentication;
- bool cert_private;
- bool enabled;
- QString library;
- QString name;
- int private_mask;
- QString slotevent_method;
- int slotevent_timeout;
-
- Pkcs11ProviderConfig() :
- allow_protected_authentication(true),
- cert_private(false),
- enabled(false),
- private_mask(0),
- slotevent_method("auto"),
- slotevent_timeout(0)
- {
- }
-
- QVariantMap toVariantMap() const
- {
- QVariantMap out;
- out["allow_protected_authentication"] = allow_protected_authentication;
- out["cert_private"] = cert_private;
- out["enabled"] = enabled;
- out["library"] = library;
- out["name"] = name;
- out["private_mask"] = private_mask;
- out["slotevent_method"] = slotevent_method;
- out["slotevent_timeout"] = slotevent_timeout;
- return out;
- }
-
- bool fromVariantMap(const QVariantMap &in)
- {
- allow_protected_authentication = in["allow_protected_authentication"].toBool();
- cert_private = in["cert_private"].toBool();
- enabled = in["enabled"].toBool();
- library = in["library"].toString();
- name = in["name"].toString();
- private_mask = in["private_mask"].toInt();
- slotevent_method = in["slotevent_method"].toString();
- slotevent_timeout = in["slotevent_timeout"].toInt();
- return true;
- }
+ bool allow_protected_authentication;
+ bool cert_private;
+ bool enabled;
+ QString library;
+ QString name;
+ int private_mask;
+ QString slotevent_method;
+ int slotevent_timeout;
+
+ Pkcs11ProviderConfig() :
+ allow_protected_authentication(true),
+ cert_private(false),
+ enabled(false),
+ private_mask(0),
+ slotevent_method("auto"),
+ slotevent_timeout(0)
+ {
+ }
+
+ QVariantMap toVariantMap() const
+ {
+ QVariantMap out;
+ out["allow_protected_authentication"] = allow_protected_authentication;
+ out["cert_private"] = cert_private;
+ out["enabled"] = enabled;
+ out["library"] = library;
+ out["name"] = name;
+ out["private_mask"] = private_mask;
+ out["slotevent_method"] = slotevent_method;
+ out["slotevent_timeout"] = slotevent_timeout;
+ return out;
+ }
+
+ bool fromVariantMap(const QVariantMap &in)
+ {
+ allow_protected_authentication = in["allow_protected_authentication"].toBool();
+ cert_private = in["cert_private"].toBool();
+ enabled = in["enabled"].toBool();
+ library = in["library"].toString();
+ name = in["name"].toString();
+ private_mask = in["private_mask"].toInt();
+ slotevent_method = in["slotevent_method"].toString();
+ slotevent_timeout = in["slotevent_timeout"].toInt();
+ return true;
+ }
};
class Pkcs11Config
{
public:
- bool allow_load_rootca;
- bool allow_protected_authentication;
- int log_level;
- int pin_cache;
- QList<Pkcs11ProviderConfig> providers;
-
- QVariantMap orig_config;
-
- Pkcs11Config() :
- allow_load_rootca(false),
- allow_protected_authentication(true),
- log_level(0),
- pin_cache(-1)
- {
- }
-
- QVariantMap toVariantMap() const
- {
- QVariantMap out = orig_config;
-
- // form type
- out["formtype"] = "http://affinix.com/qca/forms/qca-pkcs11#1.0";
-
- // base settings
- out["allow_load_rootca"] = allow_load_rootca;
- out["allow_protected_authentication"] = allow_protected_authentication;
- out["log_level"] = log_level;
- out["pin_cache"] = pin_cache;
-
- // provider settings (always write at least 10 providers)
- for(int n = 0; n < 10 || n < providers.count(); ++n)
- {
- QString prefix = QString().sprintf("provider_%02d_", n);
-
- Pkcs11ProviderConfig provider;
- if(n < providers.count())
- provider = providers[n];
-
- QVariantMap subconfig = provider.toVariantMap();
- QMapIterator<QString,QVariant> it(subconfig);
- while(it.hasNext())
- {
- it.next();
- out.insert(prefix + it.key(), it.value());
- }
- }
-
- return out;
- }
-
- bool fromVariantMap(const QVariantMap &in)
- {
- if(in["formtype"] != "http://affinix.com/qca/forms/qca-pkcs11#1.0")
- return false;
-
- allow_load_rootca = in["allow_load_rootca"].toBool();
- allow_protected_authentication = in["allow_protected_authentication"].toBool();
- log_level = in["log_level"].toInt();
- pin_cache = in["pin_cache"].toInt();
-
- for(int n = 0;; ++n)
- {
- QString prefix = QString().sprintf("provider_%02d_", n);
-
- // collect all key/values with this prefix into a
- // a separate container, leaving out the prefix
- // from the keys.
- QVariantMap subconfig;
- QMapIterator<QString,QVariant> it(in);
- while(it.hasNext())
- {
- it.next();
- if(it.key().startsWith(prefix))
- subconfig.insert(it.key().mid(prefix.length()), it.value());
- }
-
- // if there are no config items with this prefix, we're done
- if(subconfig.isEmpty())
- break;
-
- Pkcs11ProviderConfig provider;
- if(!provider.fromVariantMap(subconfig))
- return false;
-
- // skip unnamed entries
- if(provider.name.isEmpty())
- continue;
-
- // skip duplicate entries
- bool have_name_already = false;
- foreach(const Pkcs11ProviderConfig &i, providers)
- {
- if(i.name == provider.name)
- {
- have_name_already = true;
- break;
- }
- }
- if(have_name_already)
- continue;
-
- providers += provider;
- }
-
- orig_config = in;
- return true;
- }
+ bool allow_load_rootca;
+ bool allow_protected_authentication;
+ int log_level;
+ int pin_cache;
+ QList<Pkcs11ProviderConfig> providers;
+
+ QVariantMap orig_config;
+
+ Pkcs11Config() :
+ allow_load_rootca(false),
+ allow_protected_authentication(true),
+ log_level(0),
+ pin_cache(-1)
+ {
+ }
+
+ QVariantMap toVariantMap() const
+ {
+ QVariantMap out = orig_config;
+
+ // form type
+ out["formtype"] = "http://affinix.com/qca/forms/qca-pkcs11#1.0";
+
+ // base settings
+ out["allow_load_rootca"] = allow_load_rootca;
+ out["allow_protected_authentication"] = allow_protected_authentication;
+ out["log_level"] = log_level;
+ out["pin_cache"] = pin_cache;
+
+ // provider settings (always write at least 10 providers)
+ for (int n = 0; n < 10 || n < providers.count(); ++n) {
+ QString prefix = QString().sprintf("provider_%02d_", n);
+
+ Pkcs11ProviderConfig provider;
+ if (n < providers.count()) {
+ provider = providers[n];
+ }
+
+ QVariantMap subconfig = provider.toVariantMap();
+ QMapIterator<QString, QVariant> it(subconfig);
+ while (it.hasNext()) {
+ it.next();
+ out.insert(prefix + it.key(), it.value());
+ }
+ }
+
+ return out;
+ }
+
+ bool fromVariantMap(const QVariantMap &in)
+ {
+ if (in["formtype"] != "http://affinix.com/qca/forms/qca-pkcs11#1.0") {
+ return false;
+ }
+
+ allow_load_rootca = in["allow_load_rootca"].toBool();
+ allow_protected_authentication = in["allow_protected_authentication"].toBool();
+ log_level = in["log_level"].toInt();
+ pin_cache = in["pin_cache"].toInt();
+
+ for (int n = 0;; ++n) {
+ QString prefix = QString().sprintf("provider_%02d_", n);
+
+ // collect all key/values with this prefix into a
+ // a separate container, leaving out the prefix
+ // from the keys.
+ QVariantMap subconfig;
+ QMapIterator<QString, QVariant> it(in);
+ while (it.hasNext()) {
+ it.next();
+ if (it.key().startsWith(prefix)) {
+ subconfig.insert(it.key().mid(prefix.length()), it.value());
+ }
+ }
+
+ // if there are no config items with this prefix, we're done
+ if (subconfig.isEmpty()) {
+ break;
+ }
+
+ Pkcs11ProviderConfig provider;
+ if (!provider.fromVariantMap(subconfig)) {
+ return false;
+ }
+
+ // skip unnamed entries
+ if (provider.name.isEmpty()) {
+ continue;
+ }
+
+ // skip duplicate entries
+ bool have_name_already = false;
+ foreach (const Pkcs11ProviderConfig &i, providers) {
+ if (i.name == provider.name) {
+ have_name_already = true;
+ break;
+ }
+ }
+ if (have_name_already) {
+ continue;
+ }
+
+ providers += provider;
+ }
+
+ orig_config = in;
+ return true;
+ }
};
static QVariantMap provider_config_edit_pkcs11(const QVariantMap &in)
{
- Pkcs11Config config;
- if(!config.fromVariantMap(in))
- {
- fprintf(stderr, "Error: unable to parse PKCS#11 provider configuration.\n");
- return QVariantMap();
- }
-
- while(1)
- {
- printf("\n");
- printf("Global settings:\n");
- printf(" Allow loading of root CAs: %s\n", config.allow_load_rootca ? "Yes" : "No");
- printf(" Allow protected authentication: %s\n", config.allow_protected_authentication ? "Yes" : "No");
- QString str;
- if(config.pin_cache == -1)
- str = "No limit";
- else
- str = QString("%1 seconds").arg(config.pin_cache);
- printf(" Maximum PIN cache time: %s\n", qPrintable(str));
- printf(" Log level: %d\n", config.log_level);
- printf("\n");
- printf("PKCS#11 modules:\n");
- if(!config.providers.isEmpty())
- {
- foreach(const Pkcs11ProviderConfig &provider, config.providers)
- printf(" %s\n", qPrintable(provider.name));
- }
- else
- printf(" (None)\n");
- printf("\n");
- printf("Actions:\n");
- printf(" a) Edit global settings\n");
- printf(" b) Add PKCS#11 module\n");
- printf(" c) Edit PKCS#11 module\n");
- printf(" d) Remove PKCS#11 module\n");
- printf("\n");
-
- int index;
- while(1)
- {
- QString str = prompt_for("Select an action, or enter to quit");
- if(str.isEmpty())
- {
- index = -1;
- break;
- }
- if(str.length() == 1)
- {
- index = str[0].toLatin1() - 'a';
- if(index >= 0 && index < 4)
- break;
- }
- printf("'%s' is not a valid entry.\n\n", qPrintable(str));
- }
- if(index == -1)
- break;
-
- if(index == 0)
- {
- printf("\n");
-
- QString prompt;
- prompt = QString("Allow loading of root CAs: [%1] ").arg(config.allow_load_rootca ? "Yes" : "No");
- config.allow_load_rootca = prompt_for_yesno(prompt, config.allow_load_rootca);
- prompt = QString("Allow protected authentication: [%1] ").arg(config.allow_protected_authentication ? "Yes" : "No");
- config.allow_protected_authentication = prompt_for_yesno(prompt, config.allow_protected_authentication);
- prompt = QString("Maximum PIN cache time in seconds (-1 for no limit): [%1] ").arg(config.pin_cache);
- config.pin_cache = prompt_for_int(prompt, config.pin_cache);
- prompt = QString("Log level: [%1] ").arg(config.log_level);
- config.log_level = prompt_for_int(prompt, config.log_level);
- }
- else // 1, 2, 3
- {
- int at = -1;
-
- // for edit/remove, need to select provider
- if(index == 2 || index == 3)
- {
- printf("\nWhich PKCS#11 module?\n");
- for(int n = 0; n < config.providers.count(); ++n)
- {
- const Pkcs11ProviderConfig &provider = config.providers[n];
- char c = 'a' + n;
- printf(" %c) %s\n", c, qPrintable(provider.name));
- }
- printf("\n");
-
- int index;
- while(1)
- {
- QString str = prompt_for("Select a module, or enter to go back");
- if(str.isEmpty())
- {
- index = -1;
- break;
- }
- if(str.length() == 1)
- {
- index = str[0].toLatin1() - 'a';
- if(index >= 0 && index < config.providers.count())
- break;
- }
- printf("'%s' is not a valid entry.\n", qPrintable(str));
- }
-
- // exit?
- if(index == -1)
- continue;
-
- at = index;
- }
-
- // edit the entry
- if(index == 1 || index == 2)
- {
- Pkcs11ProviderConfig provider;
- if(index == 2) // edit
- provider = config.providers[at];
- provider.enabled = true;
- printf("\n");
-
- QString prompt;
-
- // prompt for unique name
- while(1)
- {
- if(index == 1)
- prompt = QString("Unique friendly name: ");
- else
- prompt = QString("Unique friendly name: [%1] ").arg(provider.name);
- provider.name = prompt_for_string(prompt, provider.name);
-
- if(provider.name.isEmpty())
- {
- printf("The friendly name cannot be blank.\n\n");
- continue;
- }
-
- bool have_name_already = false;
- for(int n = 0; n < config.providers.count(); ++n)
- {
- const Pkcs11ProviderConfig &i = config.providers[n];
-
- // skip checking against the entry we are editing
- if(at != -1 && n == at)
- continue;
-
- if(i.name == provider.name)
- {
- have_name_already = true;
- break;
- }
- }
- if(have_name_already)
- {
- printf("This name is already used by another module.\n\n");
- continue;
- }
-
- break;
- }
-
- // prompt for library file
- QString last;
- while(1)
- {
- if(index == 1)
- prompt = QString("Library filename: ");
- else
- prompt = QString("Library filename: [%1] ").arg(provider.library);
- provider.library = prompt_for_string(prompt, provider.library);
-
- if(provider.library.isEmpty())
- {
- printf("The library filename cannot be blank.\n\n");
- continue;
- }
-
- if(last != provider.library && !QFile::exists(provider.library))
- {
- last = provider.library;
- printf("'%s' does not exist.\nPress enter again if you really want this.\n\n", qPrintable(provider.library));
- continue;
- }
-
- break;
- }
-
- prompt = QString("Allow protected authentication: [%1] ").arg(provider.allow_protected_authentication ? "Yes" : "No");
- provider.allow_protected_authentication = prompt_for_yesno(prompt, provider.allow_protected_authentication);
- prompt = QString("Provider stores certificates as private objects: [%1] ").arg(provider.cert_private ? "Yes" : "No");
- provider.cert_private = prompt_for_yesno(prompt, provider.cert_private);
- printf("\n");
- printf("Provider private key mask:\n");
- printf(" 0 Determine automatically.\n");
- printf(" 1 Use sign.\n");
- printf(" 2 Use sign recover.\n");
- printf(" 4 Use decrypt.\n");
- printf(" 8 Use unwrap.\n");
- prompt = QString("Mask value: [%1] ").arg(provider.private_mask);
- provider.private_mask = prompt_for_int(prompt, provider.private_mask);
- printf("\n");
- printf("Slot event method:\n");
- printf(" auto Determine automatically.\n");
- printf(" trigger Use trigger.\n");
- printf(" poll Use poll.\n");
- prompt = QString("Method value: [%1] ").arg(provider.slotevent_method);
- provider.slotevent_method = prompt_for_slotevent_method(prompt, provider.slotevent_method);
- if(provider.slotevent_method == "poll")
- {
- prompt = QString("Poll timeout (0 for no preference): [%1] ").arg(provider.slotevent_timeout);
- provider.slotevent_timeout = prompt_for_int(prompt, provider.slotevent_timeout);
- }
- else
- provider.slotevent_timeout = 0;
-
- if(index == 1)
- config.providers += provider;
- else // 2
- config.providers[at] = provider;
- }
- // remove the entry
- else // 3
- {
- config.providers.removeAt(at);
- }
- }
- }
-
- return config.toVariantMap();
+ Pkcs11Config config;
+ if (!config.fromVariantMap(in)) {
+ fprintf(stderr, "Error: unable to parse PKCS#11 provider configuration.\n");
+ return QVariantMap();
+ }
+
+ while (1) {
+ printf("\n");
+ printf("Global settings:\n");
+ printf(" Allow loading of root CAs: %s\n", config.allow_load_rootca ? "Yes" : "No");
+ printf(" Allow protected authentication: %s\n", config.allow_protected_authentication ? "Yes" : "No");
+ QString str;
+ if (config.pin_cache == -1) {
+ str = "No limit";
+ } else {
+ str = QString("%1 seconds").arg(config.pin_cache);
+ }
+ printf(" Maximum PIN cache time: %s\n", qPrintable(str));
+ printf(" Log level: %d\n", config.log_level);
+ printf("\n");
+ printf("PKCS#11 modules:\n");
+ if (!config.providers.isEmpty()) {
+ foreach (const Pkcs11ProviderConfig &provider, config.providers) {
+ printf(" %s\n", qPrintable(provider.name));
+ }
+ } else {
+ printf(" (None)\n");
+ }
+ printf("\n");
+ printf("Actions:\n");
+ printf(" a) Edit global settings\n");
+ printf(" b) Add PKCS#11 module\n");
+ printf(" c) Edit PKCS#11 module\n");
+ printf(" d) Remove PKCS#11 module\n");
+ printf("\n");
+
+ int index;
+ while (1) {
+ QString str = prompt_for("Select an action, or enter to quit");
+ if (str.isEmpty()) {
+ index = -1;
+ break;
+ }
+ if (str.length() == 1) {
+ index = str[0].toLatin1() - 'a';
+ if (index >= 0 && index < 4) {
+ break;
+ }
+ }
+ printf("'%s' is not a valid entry.\n\n", qPrintable(str));
+ }
+ if (index == -1) {
+ break;
+ }
+
+ if (index == 0) {
+ printf("\n");
+
+ QString prompt;
+ prompt = QString("Allow loading of root CAs: [%1] ").arg(config.allow_load_rootca ? "Yes" : "No");
+ config.allow_load_rootca = prompt_for_yesno(prompt, config.allow_load_rootca);
+ prompt = QString("Allow protected authentication: [%1] ").arg(config.allow_protected_authentication ? "Yes" : "No");
+ config.allow_protected_authentication = prompt_for_yesno(prompt, config.allow_protected_authentication);
+ prompt = QString("Maximum PIN cache time in seconds (-1 for no limit): [%1] ").arg(config.pin_cache);
+ config.pin_cache = prompt_for_int(prompt, config.pin_cache);
+ prompt = QString("Log level: [%1] ").arg(config.log_level);
+ config.log_level = prompt_for_int(prompt, config.log_level);
+ } else { // 1, 2, 3
+ int at = -1;
+
+ // for edit/remove, need to select provider
+ if (index == 2 || index == 3) {
+ printf("\nWhich PKCS#11 module?\n");
+ for (int n = 0; n < config.providers.count(); ++n) {
+ const Pkcs11ProviderConfig &provider = config.providers[n];
+ char c = 'a' + n;
+ printf(" %c) %s\n", c, qPrintable(provider.name));
+ }
+ printf("\n");
+
+ int index;
+ while (1) {
+ QString str = prompt_for("Select a module, or enter to go back");
+ if (str.isEmpty()) {
+ index = -1;
+ break;
+ }
+ if (str.length() == 1) {
+ index = str[0].toLatin1() - 'a';
+ if (index >= 0 && index < config.providers.count()) {
+ break;
+ }
+ }
+ printf("'%s' is not a valid entry.\n", qPrintable(str));
+ }
+
+ // exit?
+ if (index == -1) {
+ continue;
+ }
+
+ at = index;
+ }
+
+ // edit the entry
+ if (index == 1 || index == 2) {
+ Pkcs11ProviderConfig provider;
+ if (index == 2) { // edit
+ provider = config.providers[at];
+ }
+ provider.enabled = true;
+ printf("\n");
+
+ QString prompt;
+
+ // prompt for unique name
+ while (1) {
+ if (index == 1) {
+ prompt = QString("Unique friendly name: ");
+ } else {
+ prompt = QString("Unique friendly name: [%1] ").arg(provider.name);
+ }
+ provider.name = prompt_for_string(prompt, provider.name);
+
+ if (provider.name.isEmpty()) {
+ printf("The friendly name cannot be blank.\n\n");
+ continue;
+ }
+
+ bool have_name_already = false;
+ for (int n = 0; n < config.providers.count(); ++n) {
+ const Pkcs11ProviderConfig &i = config.providers[n];
+
+ // skip checking against the entry we are editing
+ if (at != -1 && n == at) {
+ continue;
+ }
+
+ if (i.name == provider.name) {
+ have_name_already = true;
+ break;
+ }
+ }
+ if (have_name_already) {
+ printf("This name is already used by another module.\n\n");
+ continue;
+ }
+
+ break;
+ }
+
+ // prompt for library file
+ QString last;
+ while (1) {
+ if (index == 1) {
+ prompt = QString("Library filename: ");
+ } else {
+ prompt = QString("Library filename: [%1] ").arg(provider.library);
+ }
+ provider.library = prompt_for_string(prompt, provider.library);
+
+ if (provider.library.isEmpty()) {
+ printf("The library filename cannot be blank.\n\n");
+ continue;
+ }
+
+ if (last != provider.library && !QFile::exists(provider.library)) {
+ last = provider.library;
+ printf("'%s' does not exist.\nPress enter again if you really want this.\n\n", qPrintable(provider.library));
+ continue;
+ }
+
+ break;
+ }
+
+ prompt = QString("Allow protected authentication: [%1] ").arg(provider.allow_protected_authentication ? "Yes" : "No");
+ provider.allow_protected_authentication = prompt_for_yesno(prompt, provider.allow_protected_authentication);
+ prompt = QString("Provider stores certificates as private objects: [%1] ").arg(provider.cert_private ? "Yes" : "No");
+ provider.cert_private = prompt_for_yesno(prompt, provider.cert_private);
+ printf("\n");
+ printf("Provider private key mask:\n");
+ printf(" 0 Determine automatically.\n");
+ printf(" 1 Use sign.\n");
+ printf(" 2 Use sign recover.\n");
+ printf(" 4 Use decrypt.\n");
+ printf(" 8 Use unwrap.\n");
+ prompt = QString("Mask value: [%1] ").arg(provider.private_mask);
+ provider.private_mask = prompt_for_int(prompt, provider.private_mask);
+ printf("\n");
+ printf("Slot event method:\n");
+ printf(" auto Determine automatically.\n");
+ printf(" trigger Use trigger.\n");
+ printf(" poll Use poll.\n");
+ prompt = QString("Method value: [%1] ").arg(provider.slotevent_method);
+ provider.slotevent_method = prompt_for_slotevent_method(prompt, provider.slotevent_method);
+ if (provider.slotevent_method == "poll") {
+ prompt = QString("Poll timeout (0 for no preference): [%1] ").arg(provider.slotevent_timeout);
+ provider.slotevent_timeout = prompt_for_int(prompt, provider.slotevent_timeout);
+ } else {
+ provider.slotevent_timeout = 0;
+ }
+
+ if (index == 1) {
+ config.providers += provider;
+ } else { // 2
+ config.providers[at] = provider;
+ }
+ }
+ // remove the entry
+ else { // 3
+ config.providers.removeAt(at);
+ }
+ }
+ }
+
+ return config.toVariantMap();
}
static QVariantMap provider_config_edit(const QVariantMap &in)
{
- // see if we have a configurator for a known form type
- if(in["formtype"] == "http://affinix.com/qca/forms/qca-pkcs11#1.0")
- return provider_config_edit_pkcs11(in);
+ // see if we have a configurator for a known form type
+ if (in["formtype"] == "http://affinix.com/qca/forms/qca-pkcs11#1.0") {
+ return provider_config_edit_pkcs11(in);
+ }
- // otherwise, use the generic configurator
- return provider_config_edit_generic(in);
+ // otherwise, use the generic configurator
+ return provider_config_edit_generic(in);
}
static QString get_fingerprint(const QCA::Certificate &cert, const QString &hashType)
{
- QString hex = QCA::Hash(hashType).hashToString(cert.toDER());
- QString out;
- for(int n = 0; n < hex.count(); ++n)
- {
- if(n != 0 && n % 2 == 0)
- out += ':';
- out += hex[n];
- }
- return out;
+ QString hex = QCA::Hash(hashType).hashToString(cert.toDER());
+ QString out;
+ for (int n = 0; n < hex.count(); ++n) {
+ if (n != 0 && n % 2 == 0) {
+ out += ':';
+ }
+ out += hex[n];
+ }
+ return out;
}
static QString kstype_to_string(QCA::KeyStore::Type _type)
{
- QString type;
- switch(_type)
- {
- case QCA::KeyStore::System: type = "Sys "; break;
- case QCA::KeyStore::User: type = "User"; break;
- case QCA::KeyStore::Application: type = "App "; break;
- case QCA::KeyStore::SmartCard: type = "Card"; break;
- case QCA::KeyStore::PGPKeyring: type = "PGP "; break;
- default: type = "XXXX"; break;
- }
- return type;
+ QString type;
+ switch (_type) {
+ case QCA::KeyStore::System: type = "Sys "; break;
+ case QCA::KeyStore::User: type = "User"; break;
+ case QCA::KeyStore::Application: type = "App "; break;
+ case QCA::KeyStore::SmartCard: type = "Card"; break;
+ case QCA::KeyStore::PGPKeyring: type = "PGP "; break;
+ default: type = "XXXX"; break;
+ }
+ return type;
}
static QString ksentrytype_to_string(QCA::KeyStoreEntry::Type _type)
{
- QString type;
- switch(_type)
- {
- case QCA::KeyStoreEntry::TypeKeyBundle: type = "Key "; break;
- case QCA::KeyStoreEntry::TypeCertificate: type = "Cert"; break;
- case QCA::KeyStoreEntry::TypeCRL: type = "CRL "; break;
- case QCA::KeyStoreEntry::TypePGPSecretKey: type = "PSec"; break;
- case QCA::KeyStoreEntry::TypePGPPublicKey: type = "PPub"; break;
- default: type = "XXXX"; break;
- }
- return type;
+ QString type;
+ switch (_type) {
+ case QCA::KeyStoreEntry::TypeKeyBundle: type = "Key "; break;
+ case QCA::KeyStoreEntry::TypeCertificate: type = "Cert"; break;
+ case QCA::KeyStoreEntry::TypeCRL: type = "CRL "; break;
+ case QCA::KeyStoreEntry::TypePGPSecretKey: type = "PSec"; break;
+ case QCA::KeyStoreEntry::TypePGPPublicKey: type = "PPub"; break;
+ default: type = "XXXX"; break;
+ }
+ return type;
}
static void try_print_info(const QString &name, const QStringList &values)
{
- if(!values.isEmpty())
- {
- QString value = values.join(", ");
- printf(" %s: %s\n", qPrintable(name), value.toUtf8().data());
- }
+ if (!values.isEmpty()) {
+ QString value = values.join(", ");
+ printf(" %s: %s\n", qPrintable(name), value.toUtf8().data());
+ }
}
static void print_info(const QString &title, const QCA::CertificateInfo &info)
{
- QList<InfoType> list = makeInfoTypeList();
- printf("%s\n", title.toLatin1().data());
- foreach(const InfoType &t, list)
- try_print_info(t.name, info.values(t.type));
+ QList<InfoType> list = makeInfoTypeList();
+ printf("%s\n", title.toLatin1().data());
+ foreach (const InfoType &t, list) {
+ try_print_info(t.name, info.values(t.type));
+ }
}
static void print_info_ordered(const QString &title, const QCA::CertificateInfoOrdered &info)
{
- QList<InfoType> list = makeInfoTypeList(true);
- printf("%s\n", title.toLatin1().data());
- foreach(const QCA::CertificateInfoPair &pair, info)
- {
- QCA::CertificateInfoType type = pair.type();
- QString name;
- int at = -1;
- for(int n = 0; n < list.count(); ++n)
- {
- if(list[n].type == type)
- {
- at = n;
- break;
- }
- }
-
- // known type?
- if(at != -1)
- {
- name = list[at].name;
- }
- else
- {
- if(pair.type().section() == QCA::CertificateInfoType::DN)
- name = QString("DN:") + pair.type().id();
- else
- name = QString("AN:") + pair.type().id();
- }
-
- printf(" %s: %s\n", qPrintable(name), pair.value().toUtf8().data());
- }
+ QList<InfoType> list = makeInfoTypeList(true);
+ printf("%s\n", title.toLatin1().data());
+ foreach (const QCA::CertificateInfoPair &pair, info) {
+ QCA::CertificateInfoType type = pair.type();
+ QString name;
+ int at = -1;
+ for (int n = 0; n < list.count(); ++n) {
+ if (list[n].type == type) {
+ at = n;
+ break;
+ }
+ }
+
+ // known type?
+ if (at != -1) {
+ name = list[at].name;
+ } else {
+ if (pair.type().section() == QCA::CertificateInfoType::DN) {
+ name = QString("DN:") + pair.type().id();
+ } else {
+ name = QString("AN:") + pair.type().id();
+ }
+ }
+
+ printf(" %s: %s\n", qPrintable(name), pair.value().toUtf8().data());
+ }
}
static QString constraint_to_string(const QCA::ConstraintType &t)
{
- QList<MyConstraintType> list = makeConstraintTypeList();
- for(int n = 0; n < list.count(); ++n)
- {
- if(list[n].type == t)
- return list[n].name;
- }
- return t.id();
+ QList<MyConstraintType> list = makeConstraintTypeList();
+ for (int n = 0; n < list.count(); ++n) {
+ if (list[n].type == t) {
+ return list[n].name;
+ }
+ }
+ return t.id();
}
static QString sigalgo_to_string(QCA::SignatureAlgorithm algo)
{
- QString str;
- switch(algo)
- {
- case QCA::EMSA1_SHA1: str = "EMSA1(SHA1)"; break;
- case QCA::EMSA3_SHA1: str = "EMSA3(SHA1)"; break;
- case QCA::EMSA3_MD5: str = "EMSA3(MD5)"; break;
- case QCA::EMSA3_MD2: str = "EMSA3(MD2)"; break;
- case QCA::EMSA3_RIPEMD160: str = "EMSA3(RIPEMD160)"; break;
- case QCA::EMSA3_Raw: str = "EMSA3(raw)"; break;
- default: str = "Unknown"; break;
- }
- return str;
+ QString str;
+ switch (algo) {
+ case QCA::EMSA1_SHA1: str = "EMSA1(SHA1)"; break;
+ case QCA::EMSA3_SHA1: str = "EMSA3(SHA1)"; break;
+ case QCA::EMSA3_MD5: str = "EMSA3(MD5)"; break;
+ case QCA::EMSA3_MD2: str = "EMSA3(MD2)"; break;
+ case QCA::EMSA3_RIPEMD160: str = "EMSA3(RIPEMD160)"; break;
+ case QCA::EMSA3_Raw: str = "EMSA3(raw)"; break;
+ default: str = "Unknown"; break;
+ }
+ return str;
}
static void print_cert(const QCA::Certificate &cert, bool ordered = false)
{
- printf("Serial Number: %s\n", qPrintable(cert.serialNumber().toString()));
-
- if(ordered)
- {
- print_info_ordered("Subject", cert.subjectInfoOrdered());
- print_info_ordered("Issuer", cert.issuerInfoOrdered());
- }
- else
- {
- print_info("Subject", cert.subjectInfo());
- print_info("Issuer", cert.issuerInfo());
- }
-
- printf("Validity\n");
- printf(" Not before: %s\n", qPrintable(cert.notValidBefore().toString()));
- printf(" Not after: %s\n", qPrintable(cert.notValidAfter().toString()));
-
- printf("Constraints\n");
- QCA::Constraints constraints = cert.constraints();
- int n;
- if(!constraints.isEmpty())
- {
- for(n = 0; n < constraints.count(); ++n)
- printf(" %s\n", qPrintable(constraint_to_string(constraints[n])));
- }
- else
- printf(" No constraints\n");
-
- printf("Policies\n");
- QStringList policies = cert.policies();
- if(!policies.isEmpty())
- {
- for(n = 0; n < policies.count(); ++n)
- printf(" %s\n", qPrintable(policies[n]));
- }
- else
- printf(" No policies\n");
-
- QByteArray id;
- printf("Issuer Key ID: ");
- id = cert.issuerKeyId();
- if(!id.isEmpty())
- printf("%s\n", qPrintable(QCA::arrayToHex(id)));
- else
- printf("None\n");
-
- printf("Subject Key ID: ");
- id = cert.subjectKeyId();
- if(!id.isEmpty())
- printf("%s\n", qPrintable(QCA::arrayToHex(id)));
- else
- printf("None\n");
-
- printf("CA: %s\n", cert.isCA() ? "Yes": "No");
- printf("Signature Algorithm: %s\n", qPrintable(sigalgo_to_string(cert.signatureAlgorithm())));
-
- QCA::PublicKey key = cert.subjectPublicKey();
- printf("Public Key:\n%s", key.toPEM().toLatin1().data());
-
- printf("SHA1 Fingerprint: %s\n", qPrintable(get_fingerprint(cert, "sha1")));
- printf("MD5 Fingerprint: %s\n", qPrintable(get_fingerprint(cert, "md5")));
+ printf("Serial Number: %s\n", qPrintable(cert.serialNumber().toString()));
+
+ if (ordered) {
+ print_info_ordered("Subject", cert.subjectInfoOrdered());
+ print_info_ordered("Issuer", cert.issuerInfoOrdered());
+ } else {
+ print_info("Subject", cert.subjectInfo());
+ print_info("Issuer", cert.issuerInfo());
+ }
+
+ printf("Validity\n");
+ printf(" Not before: %s\n", qPrintable(cert.notValidBefore().toString()));
+ printf(" Not after: %s\n", qPrintable(cert.notValidAfter().toString()));
+
+ printf("Constraints\n");
+ QCA::Constraints constraints = cert.constraints();
+ int n;
+ if (!constraints.isEmpty()) {
+ for (n = 0; n < constraints.count(); ++n) {
+ printf(" %s\n", qPrintable(constraint_to_string(constraints[n])));
+ }
+ } else {
+ printf(" No constraints\n");
+ }
+
+ printf("Policies\n");
+ QStringList policies = cert.policies();
+ if (!policies.isEmpty()) {
+ for (n = 0; n < policies.count(); ++n) {
+ printf(" %s\n", qPrintable(policies[n]));
+ }
+ } else {
+ printf(" No policies\n");
+ }
+
+ QByteArray id;
+ printf("Issuer Key ID: ");
+ id = cert.issuerKeyId();
+ if (!id.isEmpty()) {
+ printf("%s\n", qPrintable(QCA::arrayToHex(id)));
+ } else {
+ printf("None\n");
+ }
+
+ printf("Subject Key ID: ");
+ id = cert.subjectKeyId();
+ if (!id.isEmpty()) {
+ printf("%s\n", qPrintable(QCA::arrayToHex(id)));
+ } else {
+ printf("None\n");
+ }
+
+ printf("CA: %s\n", cert.isCA() ? "Yes" : "No");
+ printf("Signature Algorithm: %s\n", qPrintable(sigalgo_to_string(cert.signatureAlgorithm())));
+
+ QCA::PublicKey key = cert.subjectPublicKey();
+ printf("Public Key:\n%s", key.toPEM().toLatin1().data());
+
+ printf("SHA1 Fingerprint: %s\n", qPrintable(get_fingerprint(cert, "sha1")));
+ printf("MD5 Fingerprint: %s\n", qPrintable(get_fingerprint(cert, "md5")));
}
static void print_certreq(const QCA::CertificateRequest &cert, bool ordered = false)
{
- if(ordered)
- print_info_ordered("Subject", cert.subjectInfoOrdered());
- else
- print_info("Subject", cert.subjectInfo());
-
- printf("Constraints\n");
- QCA::Constraints constraints = cert.constraints();
- int n;
- if(!constraints.isEmpty())
- {
- for(n = 0; n < constraints.count(); ++n)
- printf(" %s\n", qPrintable(constraint_to_string(constraints[n])));
- }
- else
- printf(" No constraints\n");
-
- printf("Policies\n");
- QStringList policies = cert.policies();
- if(!policies.isEmpty())
- {
- for(n = 0; n < policies.count(); ++n)
- printf(" %s\n", qPrintable(policies[n]));
- }
- else
- printf(" No policies\n");
-
- printf("CA: %s\n", cert.isCA() ? "Yes": "No");
- printf("Signature Algorithm: %s\n", qPrintable(sigalgo_to_string(cert.signatureAlgorithm())));
-
- QCA::PublicKey key = cert.subjectPublicKey();
- printf("Public Key:\n%s", key.toPEM().toLatin1().data());
+ if (ordered) {
+ print_info_ordered("Subject", cert.subjectInfoOrdered());
+ } else {
+ print_info("Subject", cert.subjectInfo());
+ }
+
+ printf("Constraints\n");
+ QCA::Constraints constraints = cert.constraints();
+ int n;
+ if (!constraints.isEmpty()) {
+ for (n = 0; n < constraints.count(); ++n) {
+ printf(" %s\n", qPrintable(constraint_to_string(constraints[n])));
+ }
+ } else {
+ printf(" No constraints\n");
+ }
+
+ printf("Policies\n");
+ QStringList policies = cert.policies();
+ if (!policies.isEmpty()) {
+ for (n = 0; n < policies.count(); ++n) {
+ printf(" %s\n", qPrintable(policies[n]));
+ }
+ } else {
+ printf(" No policies\n");
+ }
+
+ printf("CA: %s\n", cert.isCA() ? "Yes" : "No");
+ printf("Signature Algorithm: %s\n", qPrintable(sigalgo_to_string(cert.signatureAlgorithm())));
+
+ QCA::PublicKey key = cert.subjectPublicKey();
+ printf("Public Key:\n%s", key.toPEM().toLatin1().data());
}
static void print_crl(const QCA::CRL &crl, bool ordered = false)
{
- if(ordered)
- print_info_ordered("Issuer", crl.issuerInfoOrdered());
- else
- print_info("Issuer", crl.issuerInfo());
-
- int num = crl.number();
- if(num != -1)
- printf("Number: %d\n", num);
-
- printf("Validity\n");
- printf(" This update: %s\n", qPrintable(crl.thisUpdate().toString()));
- printf(" Next update: %s\n", qPrintable(crl.nextUpdate().toString()));
-
- QByteArray id;
- printf("Issuer Key ID: ");
- id = crl.issuerKeyId();
- if(!id.isEmpty())
- printf("%s\n", qPrintable(QCA::arrayToHex(id)));
- else
- printf("None\n");
-
- printf("Signature Algorithm: %s\n", qPrintable(sigalgo_to_string(crl.signatureAlgorithm())));
-
- QList<QCA::CRLEntry> revokedList = crl.revoked();
- foreach(const QCA::CRLEntry &entry, revokedList)
- {
- printf(" %s: %s, %s\n",
- qPrintable(entry.serialNumber().toString()),
- crlEntryReasonToString(entry.reason()),
- qPrintable(entry.time().toString()));
- }
+ if (ordered) {
+ print_info_ordered("Issuer", crl.issuerInfoOrdered());
+ } else {
+ print_info("Issuer", crl.issuerInfo());
+ }
+
+ int num = crl.number();
+ if (num != -1) {
+ printf("Number: %d\n", num);
+ }
+
+ printf("Validity\n");
+ printf(" This update: %s\n", qPrintable(crl.thisUpdate().toString()));
+ printf(" Next update: %s\n", qPrintable(crl.nextUpdate().toString()));
+
+ QByteArray id;
+ printf("Issuer Key ID: ");
+ id = crl.issuerKeyId();
+ if (!id.isEmpty()) {
+ printf("%s\n", qPrintable(QCA::arrayToHex(id)));
+ } else {
+ printf("None\n");
+ }
+
+ printf("Signature Algorithm: %s\n", qPrintable(sigalgo_to_string(crl.signatureAlgorithm())));
+
+ QList<QCA::CRLEntry> revokedList = crl.revoked();
+ foreach (const QCA::CRLEntry &entry, revokedList) {
+ printf(" %s: %s, %s\n",
+ qPrintable(entry.serialNumber().toString()),
+ crlEntryReasonToString(entry.reason()),
+ qPrintable(entry.time().toString()));
+ }
}
static QString format_pgp_fingerprint(const QString &in)
{
- QString out;
- bool first = true;
- for(int n = 0; n + 3 < in.length(); n += 4)
- {
- if(!first)
- out += ' ';
- else
- first = false;
- out += in.mid(n, 4).toUpper();
- }
- return out;
+ QString out;
+ bool first = true;
+ for (int n = 0; n + 3 < in.length(); n += 4) {
+ if (!first) {
+ out += ' ';
+ } else {
+ first = false;
+ }
+ out += in.mid(n, 4).toUpper();
+ }
+ return out;
}
static void print_pgp(const QCA::PGPKey &key)
{
- printf("Key ID: %s\n", qPrintable(key.keyId()));
- printf("User IDs:\n");
- foreach(const QString &s, key.userIds())
- printf(" %s\n", qPrintable(s));
- printf("Validity\n");
- printf(" Not before: %s\n", qPrintable(key.creationDate().toString()));
- if(!key.expirationDate().isNull())
- printf(" Not after: %s\n", qPrintable(key.expirationDate().toString()));
- else
- printf(" Not after: (no expiration)\n");
- printf("In Keyring: %s\n", key.inKeyring() ? "Yes": "No");
- printf("Secret Key: %s\n", key.isSecret() ? "Yes": "No");
- printf("Trusted: %s\n", key.isTrusted() ? "Yes": "No");
- printf("Fingerprint: %s\n", qPrintable(format_pgp_fingerprint(key.fingerprint())));
+ printf("Key ID: %s\n", qPrintable(key.keyId()));
+ printf("User IDs:\n");
+ foreach (const QString &s, key.userIds()) {
+ printf(" %s\n", qPrintable(s));
+ }
+ printf("Validity\n");
+ printf(" Not before: %s\n", qPrintable(key.creationDate().toString()));
+ if (!key.expirationDate().isNull()) {
+ printf(" Not after: %s\n", qPrintable(key.expirationDate().toString()));
+ } else {
+ printf(" Not after: (no expiration)\n");
+ }
+ printf("In Keyring: %s\n", key.inKeyring() ? "Yes" : "No");
+ printf("Secret Key: %s\n", key.isSecret() ? "Yes" : "No");
+ printf("Trusted: %s\n", key.isTrusted() ? "Yes" : "No");
+ printf("Fingerprint: %s\n", qPrintable(format_pgp_fingerprint(key.fingerprint())));
}
static QString validityToString(QCA::Validity v)
{
- QString s;
- switch(v)
- {
- case QCA::ValidityGood:
- s = "Validated";
- break;
- case QCA::ErrorRejected:
- s = "Root CA is marked to reject the specified purpose";
- break;
- case QCA::ErrorUntrusted:
- s = "Certificate not trusted for the required purpose";
- break;
- case QCA::ErrorSignatureFailed:
- s = "Invalid signature";
- break;
- case QCA::ErrorInvalidCA:
- s = "Invalid CA certificate";
- break;
- case QCA::ErrorInvalidPurpose:
- s = "Invalid certificate purpose";
- break;
- case QCA::ErrorSelfSigned:
- s = "Certificate is self-signed";
- break;
- case QCA::ErrorRevoked:
- s = "Certificate has been revoked";
- break;
- case QCA::ErrorPathLengthExceeded:
- s = "Maximum certificate chain length exceeded";
- break;
- case QCA::ErrorExpired:
- s = "Certificate has expired";
- break;
- case QCA::ErrorExpiredCA:
- s = "CA has expired";
- break;
- case QCA::ErrorValidityUnknown:
- default:
- s = "General certificate validation error";
- break;
- }
- return s;
+ QString s;
+ switch (v) {
+ case QCA::ValidityGood:
+ s = "Validated";
+ break;
+ case QCA::ErrorRejected:
+ s = "Root CA is marked to reject the specified purpose";
+ break;
+ case QCA::ErrorUntrusted:
+ s = "Certificate not trusted for the required purpose";
+ break;
+ case QCA::ErrorSignatureFailed:
+ s = "Invalid signature";
+ break;
+ case QCA::ErrorInvalidCA:
+ s = "Invalid CA certificate";
+ break;
+ case QCA::ErrorInvalidPurpose:
+ s = "Invalid certificate purpose";
+ break;
+ case QCA::ErrorSelfSigned:
+ s = "Certificate is self-signed";
+ break;
+ case QCA::ErrorRevoked:
+ s = "Certificate has been revoked";
+ break;
+ case QCA::ErrorPathLengthExceeded:
+ s = "Maximum certificate chain length exceeded";
+ break;
+ case QCA::ErrorExpired:
+ s = "Certificate has expired";
+ break;
+ case QCA::ErrorExpiredCA:
+ s = "CA has expired";
+ break;
+ case QCA::ErrorValidityUnknown:
+ default:
+ s = "General certificate validation error";
+ break;
+ }
+ return s;
}
static QString smIdentityResultToString(QCA::SecureMessageSignature::IdentityResult r)
{
- QString str;
- switch(r)
- {
- case QCA::SecureMessageSignature::Valid: str = "Valid"; break;
- case QCA::SecureMessageSignature::InvalidSignature: str = "InvalidSignature"; break;
- case QCA::SecureMessageSignature::InvalidKey: str = "InvalidKey"; break;
- case QCA::SecureMessageSignature::NoKey: str = "NoKey"; break;
- default: str = "Unknown";
- }
- return str;
+ QString str;
+ switch (r) {
+ case QCA::SecureMessageSignature::Valid: str = "Valid"; break;
+ case QCA::SecureMessageSignature::InvalidSignature: str = "InvalidSignature"; break;
+ case QCA::SecureMessageSignature::InvalidKey: str = "InvalidKey"; break;
+ case QCA::SecureMessageSignature::NoKey: str = "NoKey"; break;
+ default: str = "Unknown";
+ }
+ return str;
}
static QString smErrorToString(QCA::SecureMessage::Error e)
{
- QMap<QCA::SecureMessage::Error,QString> map;
- map[QCA::SecureMessage::ErrorPassphrase] = "ErrorPassphrase";
- map[QCA::SecureMessage::ErrorFormat] = "ErrorFormat";
- map[QCA::SecureMessage::ErrorSignerExpired] = "ErrorSignerExpired";
- map[QCA::SecureMessage::ErrorSignerInvalid] = "ErrorSignerInvalid";
- map[QCA::SecureMessage::ErrorEncryptExpired] = "ErrorEncryptExpired";
- map[QCA::SecureMessage::ErrorEncryptUntrusted] = "ErrorEncryptUntrusted";
- map[QCA::SecureMessage::ErrorEncryptInvalid] = "ErrorEncryptInvalid";
- map[QCA::SecureMessage::ErrorNeedCard] = "ErrorNeedCard";
- map[QCA::SecureMessage::ErrorCertKeyMismatch] = "ErrorCertKeyMismatch";
- map[QCA::SecureMessage::ErrorUnknown] = "ErrorUnknown";
- return map[e];
+ QMap<QCA::SecureMessage::Error, QString> map;
+ map[QCA::SecureMessage::ErrorPassphrase] = "ErrorPassphrase";
+ map[QCA::SecureMessage::ErrorFormat] = "ErrorFormat";
+ map[QCA::SecureMessage::ErrorSignerExpired] = "ErrorSignerExpired";
+ map[QCA::SecureMessage::ErrorSignerInvalid] = "ErrorSignerInvalid";
+ map[QCA::SecureMessage::ErrorEncryptExpired] = "ErrorEncryptExpired";
+ map[QCA::SecureMessage::ErrorEncryptUntrusted] = "ErrorEncryptUntrusted";
+ map[QCA::SecureMessage::ErrorEncryptInvalid] = "ErrorEncryptInvalid";
+ map[QCA::SecureMessage::ErrorNeedCard] = "ErrorNeedCard";
+ map[QCA::SecureMessage::ErrorCertKeyMismatch] = "ErrorCertKeyMismatch";
+ map[QCA::SecureMessage::ErrorUnknown] = "ErrorUnknown";
+ return map[e];
}
static void smDisplaySignatures(const QList<QCA::SecureMessageSignature> &signers)
{
- foreach(const QCA::SecureMessageSignature &signer, signers)
- {
- QCA::SecureMessageSignature::IdentityResult r = signer.identityResult();
- fprintf(stderr, "IdentityResult: %s\n", qPrintable(smIdentityResultToString(r)));
-
- QCA::SecureMessageKey key = signer.key();
- if(!key.isNull())
- {
- if(key.type() == QCA::SecureMessageKey::PGP)
- {
- QCA::PGPKey pub = key.pgpPublicKey();
- fprintf(stderr, "From: %s (%s)\n", qPrintable(pub.primaryUserId()), qPrintable(pub.keyId()));
- }
- else
- {
- QCA::Certificate cert = key.x509CertificateChain().primary();
- QString emailStr;
- QCA::CertificateInfo info = cert.subjectInfo();
- if(info.contains(QCA::Email))
- emailStr = QString(" (%1)").arg(info.value(QCA::Email));
- fprintf(stderr, "From: %s%s\n", qPrintable(cert.commonName()), qPrintable(emailStr));
- }
- }
- }
+ foreach (const QCA::SecureMessageSignature &signer, signers) {
+ QCA::SecureMessageSignature::IdentityResult r = signer.identityResult();
+ fprintf(stderr, "IdentityResult: %s\n", qPrintable(smIdentityResultToString(r)));
+
+ QCA::SecureMessageKey key = signer.key();
+ if (!key.isNull()) {
+ if (key.type() == QCA::SecureMessageKey::PGP) {
+ QCA::PGPKey pub = key.pgpPublicKey();
+ fprintf(stderr, "From: %s (%s)\n", qPrintable(pub.primaryUserId()), qPrintable(pub.keyId()));
+ } else {
+ QCA::Certificate cert = key.x509CertificateChain().primary();
+ QString emailStr;
+ QCA::CertificateInfo info = cert.subjectInfo();
+ if (info.contains(QCA::Email)) {
+ emailStr = QString(" (%1)").arg(info.value(QCA::Email));
+ }
+ fprintf(stderr, "From: %s%s\n", qPrintable(cert.commonName()), qPrintable(emailStr));
+ }
+ }
+ }
}
const char *mime_signpart =
- "Content-Type: text/plain; charset=UTF-8\r\n"
- "Content-Transfer-Encoding: 8bit\r\n"
- "\r\n"
- "%1";
+ "Content-Type: text/plain; charset=UTF-8\r\n"
+ "Content-Transfer-Encoding: 8bit\r\n"
+ "\r\n"
+ "%1";
const char *mime_signed =
- "Content-Type: multipart/signed;\r\n"
- " micalg=%1;\r\n"
- " boundary=QCATOOL-0001;\r\n"
- " protocol=\"application/pkcs7-signature\"\r\n"
- "\r\n"
- "\r\n"
- "--QCATOOL-0001\r\n"
- "%2\r\n"
- "--QCATOOL-0001\r\n"
- "Content-Transfer-Encoding: base64\r\n"
- "Content-Type: application/pkcs7-signature;\r\n"
- " name=smime.p7s\r\n"
- "Content-Disposition: attachment;\r\n"
- " filename=smime.p7s\r\n"
- "\r\n"
- "%3\r\n"
- "\r\n"
- "--QCATOOL-0001--\r\n";
+ "Content-Type: multipart/signed;\r\n"
+ " micalg=%1;\r\n"
+ " boundary=QCATOOL-0001;\r\n"
+ " protocol=\"application/pkcs7-signature\"\r\n"
+ "\r\n"
+ "\r\n"
+ "--QCATOOL-0001\r\n"
+ "%2\r\n"
+ "--QCATOOL-0001\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "Content-Type: application/pkcs7-signature;\r\n"
+ " name=smime.p7s\r\n"
+ "Content-Disposition: attachment;\r\n"
+ " filename=smime.p7s\r\n"
+ "\r\n"
+ "%3\r\n"
+ "\r\n"
+ "--QCATOOL-0001--\r\n";
const char *mime_enveloped =
- "Mime-Version: 1.0\r\n"
- "Content-Transfer-Encoding: base64\r\n"
- "Content-Type: application/pkcs7-mime;\r\n"
- " name=smime.p7m;\r\n"
- " smime-type=enveloped-data\r\n"
- "Content-Disposition: attachment;\r\n"
- " filename=smime.p7m\r\n"
- "\r\n"
- "%1\r\n";
+ "Mime-Version: 1.0\r\n"
+ "Content-Transfer-Encoding: base64\r\n"
+ "Content-Type: application/pkcs7-mime;\r\n"
+ " name=smime.p7m;\r\n"
+ " smime-type=enveloped-data\r\n"
+ "Content-Disposition: attachment;\r\n"
+ " filename=smime.p7m\r\n"
+ "\r\n"
+ "%1\r\n";
static QString add_cr(const QString &in)
{
- QString out = in;
- int at = 0;
- while(1)
- {
- at = out.indexOf('\n', at);
- if(at == -1)
- break;
- if(at - 1 >= 0 && out[at - 1] != '\r')
- {
- out.insert(at, '\r');
- ++at;
- }
- ++at;
- }
- return out;
+ QString out = in;
+ int at = 0;
+ while (1) {
+ at = out.indexOf('\n', at);
+ if (at == -1) {
+ break;
+ }
+ if (at - 1 >= 0 && out[at - 1] != '\r') {
+ out.insert(at, '\r');
+ ++at;
+ }
+ ++at;
+ }
+ return out;
}
static QString rem_cr(const QString &in)
{
- QString out = in;
- out.replace("\r\n", "\n");
- return out;
+ QString out = in;
+ out.replace("\r\n", "\n");
+ return out;
}
static int indexOf_newline(const QString &in, int offset = 0)
{
- for(int n = offset; n < in.length(); ++n)
- {
- if(n + 1 < in.length() && in[n] == '\r' && in[n + 1] == '\n')
- return n;
- if(in[n] == '\n')
- return n;
- }
- return -1;
+ for (int n = offset; n < in.length(); ++n) {
+ if (n + 1 < in.length() && in[n] == '\r' && in[n + 1] == '\n') {
+ return n;
+ }
+ if (in[n] == '\n') {
+ return n;
+ }
+ }
+ return -1;
}
static int indexOf_doublenewline(const QString &in, int offset = 0)
{
- int at = -1;
- while(1)
- {
- int n = indexOf_newline(in, offset);
- if(n == -1)
- return -1;
-
- if(at != -1)
- {
- if(n == offset)
- break;
- }
-
- at = n;
- if(in[n] == '\n')
- offset = n + 1;
- else
- offset = n + 2;
- }
- return at;
+ int at = -1;
+ while (1) {
+ int n = indexOf_newline(in, offset);
+ if (n == -1) {
+ return -1;
+ }
+
+ if (at != -1) {
+ if (n == offset) {
+ break;
+ }
+ }
+
+ at = n;
+ if (in[n] == '\n') {
+ offset = n + 1;
+ } else {
+ offset = n + 2;
+ }
+ }
+ return at;
}
// this is so gross
static int newline_len(const QString &in, int offset = 0)
{
- if(in[offset] == '\r')
- return 2;
- else
- return 1;
+ if (in[offset] == '\r') {
+ return 2;
+ } else {
+ return 1;
+ }
}
// all of this mime stuff is a total hack
static QString open_mime_envelope(const QString &in)
{
- int n = indexOf_doublenewline(in);
- if(n == -1)
- return QString();
- return in.mid(n + (newline_len(in, n) * 2)); // good lord
+ int n = indexOf_doublenewline(in);
+ if (n == -1) {
+ return QString();
+ }
+ return in.mid(n + (newline_len(in, n) * 2)); // good lord
}
static bool open_mime_data_sig(const QString &in, QString *data, QString *sig)
{
- int n = in.indexOf("boundary=");
- if(n == -1)
- return false;
- n += 9;
- int i = indexOf_newline(in, n);
- if(i == -1)
- return false;
- QString boundary;
- QString bregion = in.mid(n, i - n);
- n = bregion.indexOf(';');
- if(n != -1)
- boundary = bregion.mid(0, n);
- else
- boundary = bregion;
-
- if(boundary[0] == '\"')
- boundary.remove(0, 1);
- if(boundary[boundary.length() - 1] == '\"')
- boundary.remove(boundary.length() - 1, 1);
- //printf("boundary: [%s]\n", qPrintable(boundary));
- QString boundary_end = QString("--") + boundary;
- boundary = QString("--") + boundary;
-
- QString work = open_mime_envelope(in);
- //printf("work: [%s]\n", qPrintable(work));
-
- n = work.indexOf(boundary);
- if(n == -1)
- return false;
- n += boundary.length();
- i = indexOf_newline(work, n);
- if(i == -1)
- return false;
- n += newline_len(work, i);
- int data_start = n;
-
- n = work.indexOf(boundary, data_start);
- if(n == -1)
- return false;
- int data_end = n;
-
- n = data_end + boundary.length();
- i = indexOf_newline(work, n);
- if(i == -1)
- return false;
- n += newline_len(work, i);
- int next = n;
-
- QString tmp_data = work.mid(data_start, data_end - data_start);
- n = work.indexOf(boundary_end, next);
- if(n == -1)
- return false;
- QString tmp_sig = work.mid(next, n - next);
-
- // nuke some newlines
- if(tmp_data.right(2) == "\r\n")
- tmp_data.truncate(tmp_data.length() - 2);
- else if(tmp_data.right(1) == "\n")
- tmp_data.truncate(tmp_data.length() - 1);
- if(tmp_sig.right(2) == "\r\n")
- tmp_sig.truncate(tmp_sig.length() - 2);
- else if(tmp_sig.right(1) == "\n")
- tmp_sig.truncate(tmp_sig.length() - 1);
-
- tmp_sig = open_mime_envelope(tmp_sig);
-
- *data = tmp_data;
- *sig = tmp_sig;
- return true;
+ int n = in.indexOf("boundary=");
+ if (n == -1) {
+ return false;
+ }
+ n += 9;
+ int i = indexOf_newline(in, n);
+ if (i == -1) {
+ return false;
+ }
+ QString boundary;
+ QString bregion = in.mid(n, i - n);
+ n = bregion.indexOf(';');
+ if (n != -1) {
+ boundary = bregion.mid(0, n);
+ } else {
+ boundary = bregion;
+ }
+
+ if (boundary[0] == '\"') {
+ boundary.remove(0, 1);
+ }
+ if (boundary[boundary.length() - 1] == '\"') {
+ boundary.remove(boundary.length() - 1, 1);
+ }
+ //printf("boundary: [%s]\n", qPrintable(boundary));
+ QString boundary_end = QString("--") + boundary;
+ boundary = QString("--") + boundary;
+
+ QString work = open_mime_envelope(in);
+ //printf("work: [%s]\n", qPrintable(work));
+
+ n = work.indexOf(boundary);
+ if (n == -1) {
+ return false;
+ }
+ n += boundary.length();
+ i = indexOf_newline(work, n);
+ if (i == -1) {
+ return false;
+ }
+ n += newline_len(work, i);
+ int data_start = n;
+
+ n = work.indexOf(boundary, data_start);
+ if (n == -1) {
+ return false;
+ }
+ int data_end = n;
+
+ n = data_end + boundary.length();
+ i = indexOf_newline(work, n);
+ if (i == -1) {
+ return false;
+ }
+ n += newline_len(work, i);
+ int next = n;
+
+ QString tmp_data = work.mid(data_start, data_end - data_start);
+ n = work.indexOf(boundary_end, next);
+ if (n == -1) {
+ return false;
+ }
+ QString tmp_sig = work.mid(next, n - next);
+
+ // nuke some newlines
+ if (tmp_data.right(2) == "\r\n") {
+ tmp_data.truncate(tmp_data.length() - 2);
+ } else if (tmp_data.right(1) == "\n") {
+ tmp_data.truncate(tmp_data.length() - 1);
+ }
+ if (tmp_sig.right(2) == "\r\n") {
+ tmp_sig.truncate(tmp_sig.length() - 2);
+ } else if (tmp_sig.right(1) == "\n") {
+ tmp_sig.truncate(tmp_sig.length() - 1);
+ }
+
+ tmp_sig = open_mime_envelope(tmp_sig);
+
+ *data = tmp_data;
+ *sig = tmp_sig;
+ return true;
}
static QString idHash(const QString &id)
{
- // hash the id and take the rightmost 4 hex characters
- return QCA::Hash("md5").hashToString(id.toUtf8()).right(4);
+ // hash the id and take the rightmost 4 hex characters
+ return QCA::Hash("md5").hashToString(id.toUtf8()).right(4);
}
// first = ids, second = names
static QPair<QStringList, QStringList> getKeyStoreStrings(const QStringList &list, QCA::KeyStoreManager *ksm)
{
- QPair<QStringList, QStringList> out;
- for(int n = 0; n < list.count(); ++n)
- {
- QCA::KeyStore ks(list[n], ksm);
- out.first.append(idHash(ks.id()));
- out.second.append(ks.name());
- }
- return out;
+ QPair<QStringList, QStringList> out;
+ for (int n = 0; n < list.count(); ++n) {
+ QCA::KeyStore ks(list[n], ksm);
+ out.first.append(idHash(ks.id()));
+ out.second.append(ks.name());
+ }
+ return out;
}
static QPair<QStringList, QStringList> getKeyStoreEntryStrings(const QList<QCA::KeyStoreEntry> &list)
{
- QPair<QStringList, QStringList> out;
- for(int n = 0; n < list.count(); ++n)
- {
- out.first.append(idHash(list[n].id()));
- out.second.append(list[n].name());
- }
- return out;
+ QPair<QStringList, QStringList> out;
+ for (int n = 0; n < list.count(); ++n) {
+ out.first.append(idHash(list[n].id()));
+ out.second.append(list[n].name());
+ }
+ return out;
}
static QList<int> getPartialMatches(const QStringList &list, const QString &str)
{
- QList<int> out;
- for(int n = 0; n < list.count(); ++n)
- {
- if(list[n].contains(str, Qt::CaseInsensitive))
- out += n;
- }
- return out;
+ QList<int> out;
+ for (int n = 0; n < list.count(); ++n) {
+ if (list[n].contains(str, Qt::CaseInsensitive)) {
+ out += n;
+ }
+ }
+ return out;
}
static int findByString(const QPair<QStringList, QStringList> &in, const QString &str)
{
- // exact id match
- int n = in.first.indexOf(str);
- if(n != -1)
- return n;
-
- // partial id match
- QList<int> ret = getPartialMatches(in.first, str);
- if(!ret.isEmpty())
- return ret.first();
-
- // partial name match
- ret = getPartialMatches(in.second, str);
- if(!ret.isEmpty())
- return ret.first();
-
- return -1;
+ // exact id match
+ int n = in.first.indexOf(str);
+ if (n != -1) {
+ return n;
+ }
+
+ // partial id match
+ QList<int> ret = getPartialMatches(in.first, str);
+ if (!ret.isEmpty()) {
+ return ret.first();
+ }
+
+ // partial name match
+ ret = getPartialMatches(in.second, str);
+ if (!ret.isEmpty()) {
+ return ret.first();
+ }
+
+ return -1;
}
static QString getKeyStore(const QString &name)
{
- QCA::KeyStoreManager ksm;
- QStringList storeList = ksm.keyStores();
- int n = findByString(getKeyStoreStrings(storeList, &ksm), name);
- if(n != -1)
- return storeList[n];
- return QString();
+ QCA::KeyStoreManager ksm;
+ QStringList storeList = ksm.keyStores();
+ int n = findByString(getKeyStoreStrings(storeList, &ksm), name);
+ if (n != -1) {
+ return storeList[n];
+ }
+ return QString();
}
static QCA::KeyStoreEntry getKeyStoreEntry(QCA::KeyStore *store, const QString &name)
{
- QList<QCA::KeyStoreEntry> list = store->entryList();
- int n = findByString(getKeyStoreEntryStrings(list), name);
- if(n != -1)
- return list[n];
- return QCA::KeyStoreEntry();
+ QList<QCA::KeyStoreEntry> list = store->entryList();
+ int n = findByString(getKeyStoreEntryStrings(list), name);
+ if (n != -1) {
+ return list[n];
+ }
+ return QCA::KeyStoreEntry();
}
// here are a bunch of get_Foo functions for the various types
// E - generic entry
// K - private key
// C - cert
// X - keybundle
// P - pgp public key
// S - pgp secret key
// in all cases but K, the store:obj notation can be used. if there
// is no colon present, then we treat the input as a filename. we
// try the file as an exported passive entry id, and if the type
// is C or X, we'll fall back to regular files if necessary.
static QCA::KeyStoreEntry get_E(const QString &name, bool nopassiveerror = false)
{
- QCA::KeyStoreEntry entry;
-
- QCA::KeyStoreManager::start();
-
- int n = name.indexOf(':');
- if(n != -1)
- {
- ksm_start_and_wait();
-
- // store:obj lookup
- QString storeName = name.mid(0, n);
- QString objectName = name.mid(n + 1);
-
- QCA::KeyStoreManager ksm;
- QCA::KeyStore store(getKeyStore(storeName), &ksm);
- if(!store.isValid())
- {
- fprintf(stderr, "Error: no such store [%s].\n", qPrintable(storeName));
- return entry;
- }
-
- entry = getKeyStoreEntry(&store, objectName);
- if(entry.isNull())
- {
- fprintf(stderr, "Error: no such object [%s].\n", qPrintable(objectName));
- return entry;
- }
- }
- else
- {
- // exported id
- QString serialized = read_ksentry_file(name);
- entry = QCA::KeyStoreEntry(serialized);
- if(entry.isNull())
- {
- if(!nopassiveerror)
- fprintf(stderr, "Error: invalid/unknown entry [%s].\n", qPrintable(name));
- return entry;
- }
- }
-
- return entry;
+ QCA::KeyStoreEntry entry;
+
+ QCA::KeyStoreManager::start();
+
+ int n = name.indexOf(':');
+ if (n != -1) {
+ ksm_start_and_wait();
+
+ // store:obj lookup
+ QString storeName = name.mid(0, n);
+ QString objectName = name.mid(n + 1);
+
+ QCA::KeyStoreManager ksm;
+ QCA::KeyStore store(getKeyStore(storeName), &ksm);
+ if (!store.isValid()) {
+ fprintf(stderr, "Error: no such store [%s].\n", qPrintable(storeName));
+ return entry;
+ }
+
+ entry = getKeyStoreEntry(&store, objectName);
+ if (entry.isNull()) {
+ fprintf(stderr, "Error: no such object [%s].\n", qPrintable(objectName));
+ return entry;
+ }
+ } else {
+ // exported id
+ QString serialized = read_ksentry_file(name);
+ entry = QCA::KeyStoreEntry(serialized);
+ if (entry.isNull()) {
+ if (!nopassiveerror) {
+ fprintf(stderr, "Error: invalid/unknown entry [%s].\n", qPrintable(name));
+ }
+ return entry;
+ }
+ }
+
+ return entry;
}
static QCA::PrivateKey get_K(const QString &name)
{
- QCA::PrivateKey key;
-
- int n = name.indexOf(':');
- if(n != -1)
- {
- fprintf(stderr, "Error: cannot use store:obj notation for raw private keys.\n");
- return key;
- }
-
- if(is_pem_file(name))
- key = QCA::PrivateKey::fromPEMFile(name);
- else
- key = QCA::PrivateKey::fromDER(read_der_file(name));
- if(key.isNull())
- {
- fprintf(stderr, "Error: unable to read/process private key file.\n");
- return key;
- }
-
- return key;
+ QCA::PrivateKey key;
+
+ int n = name.indexOf(':');
+ if (n != -1) {
+ fprintf(stderr, "Error: cannot use store:obj notation for raw private keys.\n");
+ return key;
+ }
+
+ if (is_pem_file(name)) {
+ key = QCA::PrivateKey::fromPEMFile(name);
+ } else {
+ key = QCA::PrivateKey::fromDER(read_der_file(name));
+ }
+ if (key.isNull()) {
+ fprintf(stderr, "Error: unable to read/process private key file.\n");
+ return key;
+ }
+
+ return key;
}
static QCA::Certificate get_C(const QString &name)
{
- QCA::KeyStoreEntry entry = get_E(name, true);
- if(!entry.isNull())
- {
- if(entry.type() != QCA::KeyStoreEntry::TypeCertificate)
- {
- fprintf(stderr, "Error: entry is not a certificate.\n");
- return QCA::Certificate();
- }
- return entry.certificate();
- }
-
- if(!QCA::isSupported("cert"))
- {
- fprintf(stderr, "Error: need 'cert' feature.\n");
- return QCA::Certificate();
- }
-
- // try file
- QCA::Certificate cert;
- if(is_pem_file(name))
- cert = QCA::Certificate::fromPEMFile(name);
- else
- cert = QCA::Certificate::fromDER(read_der_file(name));
- if(cert.isNull())
- {
- fprintf(stderr, "Error: unable to read/process certificate file.\n");
- return cert;
- }
-
- return cert;
+ QCA::KeyStoreEntry entry = get_E(name, true);
+ if (!entry.isNull()) {
+ if (entry.type() != QCA::KeyStoreEntry::TypeCertificate) {
+ fprintf(stderr, "Error: entry is not a certificate.\n");
+ return QCA::Certificate();
+ }
+ return entry.certificate();
+ }
+
+ if (!QCA::isSupported("cert")) {
+ fprintf(stderr, "Error: need 'cert' feature.\n");
+ return QCA::Certificate();
+ }
+
+ // try file
+ QCA::Certificate cert;
+ if (is_pem_file(name)) {
+ cert = QCA::Certificate::fromPEMFile(name);
+ } else {
+ cert = QCA::Certificate::fromDER(read_der_file(name));
+ }
+ if (cert.isNull()) {
+ fprintf(stderr, "Error: unable to read/process certificate file.\n");
+ return cert;
+ }
+
+ return cert;
}
static QCA::KeyBundle get_X(const QString &name)
{
- QCA::KeyStoreEntry entry = get_E(name, true);
- if(!entry.isNull())
- {
- if(entry.type() != QCA::KeyStoreEntry::TypeKeyBundle)
- {
- fprintf(stderr, "Error: entry is not a keybundle.\n");
- return QCA::KeyBundle();
- }
- return entry.keyBundle();
- }
-
- if(!QCA::isSupported("pkcs12"))
- {
- fprintf(stderr, "Error: need 'pkcs12' feature.\n");
- return QCA::KeyBundle();
- }
-
- // try file
- QCA::KeyBundle key = QCA::KeyBundle::fromFile(name);
- if(key.isNull())
- {
- fprintf(stderr, "Error: unable to read/process keybundle file.\n");
- return key;
- }
-
- return key;
+ QCA::KeyStoreEntry entry = get_E(name, true);
+ if (!entry.isNull()) {
+ if (entry.type() != QCA::KeyStoreEntry::TypeKeyBundle) {
+ fprintf(stderr, "Error: entry is not a keybundle.\n");
+ return QCA::KeyBundle();
+ }
+ return entry.keyBundle();
+ }
+
+ if (!QCA::isSupported("pkcs12")) {
+ fprintf(stderr, "Error: need 'pkcs12' feature.\n");
+ return QCA::KeyBundle();
+ }
+
+ // try file
+ QCA::KeyBundle key = QCA::KeyBundle::fromFile(name);
+ if (key.isNull()) {
+ fprintf(stderr, "Error: unable to read/process keybundle file.\n");
+ return key;
+ }
+
+ return key;
}
static QCA::PGPKey get_P(const QString &name)
{
- QCA::KeyStoreEntry entry = get_E(name, true);
- if(!entry.isNull())
- {
- if(entry.type() != QCA::KeyStoreEntry::TypePGPPublicKey && entry.type() != QCA::KeyStoreEntry::TypePGPSecretKey)
- {
- fprintf(stderr, "Error: entry is not a pgp public key.\n");
- return QCA::PGPKey();
- }
- return entry.pgpPublicKey();
- }
-
- // try file
- QCA::PGPKey key = QCA::PGPKey::fromFile(name);
- if(key.isNull())
- {
- fprintf(stderr, "Error: unable to read/process pgp key file.\n");
- return key;
- }
-
- return key;
+ QCA::KeyStoreEntry entry = get_E(name, true);
+ if (!entry.isNull()) {
+ if (entry.type() != QCA::KeyStoreEntry::TypePGPPublicKey && entry.type() != QCA::KeyStoreEntry::TypePGPSecretKey) {
+ fprintf(stderr, "Error: entry is not a pgp public key.\n");
+ return QCA::PGPKey();
+ }
+ return entry.pgpPublicKey();
+ }
+
+ // try file
+ QCA::PGPKey key = QCA::PGPKey::fromFile(name);
+ if (key.isNull()) {
+ fprintf(stderr, "Error: unable to read/process pgp key file.\n");
+ return key;
+ }
+
+ return key;
}
static QPair<QCA::PGPKey, QCA::PGPKey> get_S(const QString &name, bool noerror = false)
{
- QPair<QCA::PGPKey, QCA::PGPKey> key;
- QCA::KeyStoreEntry entry = get_E(name, true);
- if(!entry.isNull())
- {
- if(entry.type() != QCA::KeyStoreEntry::TypePGPSecretKey)
- {
- if(!noerror)
- fprintf(stderr, "Error: entry is not a pgp secret key.\n");
- return key;
- }
-
- key.first = entry.pgpSecretKey();
- key.second = entry.pgpPublicKey();
- return key;
- }
- return key;
+ QPair<QCA::PGPKey, QCA::PGPKey> key;
+ QCA::KeyStoreEntry entry = get_E(name, true);
+ if (!entry.isNull()) {
+ if (entry.type() != QCA::KeyStoreEntry::TypePGPSecretKey) {
+ if (!noerror) {
+ fprintf(stderr, "Error: entry is not a pgp secret key.\n");
+ }
+ return key;
+ }
+
+ key.first = entry.pgpSecretKey();
+ key.second = entry.pgpPublicKey();
+ return key;
+ }
+ return key;
}
static void usage()
{
- printf("%s: simple qca utility\n", APPNAME);
- printf("usage: %s (options) [command]\n", EXENAME);
- printf(" options: --pass=x, --newpass=x, --nonroots=x, --roots=x, --nosys,\n");
- printf(" --noprompt, --ordered, --debug, --log-file=x, --log-level=n,\n");
- printf(" --nobundle\n");
- printf("\n");
- printf(" help|--help|-h This help text\n");
- printf(" version|--version|-v Print version information\n");
- printf(" plugins List available plugins\n");
- printf(" config [command]\n");
- printf(" save [provider] Save default provider config\n");
- printf(" edit [provider] Edit provider config\n");
- printf(" key [command]\n");
- printf(" make rsa|dsa [bits] Create a key pair\n");
- printf(" changepass [K] Add/change/remove passphrase of a key\n");
- printf(" cert [command]\n");
- printf(" makereq [K] Create certificate request (CSR)\n");
- printf(" makeself [K] Create self-signed certificate\n");
- printf(" makereqadv [K] Advanced version of 'makereq'\n");
- printf(" makeselfadv [K] Advanced version of 'makeself'\n");
- printf(" validate [C] Validate certificate\n");
- printf(" keybundle [command]\n");
- printf(" make [K] [C] Create a keybundle\n");
- printf(" extract [X] Extract certificate(s) and key\n");
- printf(" changepass [X] Change passphrase of a keybundle\n");
- printf(" keystore [command]\n");
- printf(" list-stores List all available keystores\n");
- printf(" list [storeName] List content of a keystore\n");
- printf(" monitor Monitor for keystore availability\n");
- printf(" export [E] Export a keystore entry's content\n");
- printf(" exportref [E] Export a keystore entry reference\n");
- printf(" addkb [storeName] [cert.p12] Add a keybundle into a keystore\n");
- printf(" addpgp [storeName] [key.asc] Add a PGP key into a keystore\n");
- printf(" remove [E] Remove an object from a keystore\n");
- printf(" show [command]\n");
- printf(" cert [C] Examine a certificate\n");
- printf(" req [req.pem] Examine a certificate request (CSR)\n");
- printf(" crl [crl.pem] Examine a certificate revocation list\n");
- printf(" kb [X] Examine a keybundle\n");
- printf(" pgp [P|S] Examine a PGP key\n");
- printf(" message [command]\n");
- printf(" sign pgp|pgpdetach|smime [X|S] Sign a message\n");
- printf(" encrypt pgp|smime [C|P] Encrypt a message\n");
- printf(" signencrypt [S] [P] PGP sign & encrypt a message\n");
- printf(" verify pgp|smime Verify a message\n");
- printf(" decrypt pgp|smime ((X) ...) Decrypt a message (S/MIME needs X)\n");
- printf(" exportcerts Export certs from S/MIME message\n");
- printf("\n");
- printf("Object types: K = private key, C = certificate, X = key bundle,\n");
- printf(" P = PGP public key, S = PGP secret key, E = generic entry\n");
- printf("\n");
- printf("An object must be either a filename or a keystore reference (\"store:obj\").\n");
- printf("\n");
- printf("Log level is from 0 (quiet) to 8 (debug)\n");
- printf("\n");
+ printf("%s: simple qca utility\n", APPNAME);
+ printf("usage: %s (options) [command]\n", EXENAME);
+ printf(" options: --pass=x, --newpass=x, --nonroots=x, --roots=x, --nosys,\n");
+ printf(" --noprompt, --ordered, --debug, --log-file=x, --log-level=n,\n");
+ printf(" --nobundle\n");
+ printf("\n");
+ printf(" help|--help|-h This help text\n");
+ printf(" version|--version|-v Print version information\n");
+ printf(" plugins List available plugins\n");
+ printf(" config [command]\n");
+ printf(" save [provider] Save default provider config\n");
+ printf(" edit [provider] Edit provider config\n");
+ printf(" key [command]\n");
+ printf(" make rsa|dsa [bits] Create a key pair\n");
+ printf(" changepass [K] Add/change/remove passphrase of a key\n");
+ printf(" cert [command]\n");
+ printf(" makereq [K] Create certificate request (CSR)\n");
+ printf(" makeself [K] Create self-signed certificate\n");
+ printf(" makereqadv [K] Advanced version of 'makereq'\n");
+ printf(" makeselfadv [K] Advanced version of 'makeself'\n");
+ printf(" validate [C] Validate certificate\n");
+ printf(" keybundle [command]\n");
+ printf(" make [K] [C] Create a keybundle\n");
+ printf(" extract [X] Extract certificate(s) and key\n");
+ printf(" changepass [X] Change passphrase of a keybundle\n");
+ printf(" keystore [command]\n");
+ printf(" list-stores List all available keystores\n");
+ printf(" list [storeName] List content of a keystore\n");
+ printf(" monitor Monitor for keystore availability\n");
+ printf(" export [E] Export a keystore entry's content\n");
+ printf(" exportref [E] Export a keystore entry reference\n");
+ printf(" addkb [storeName] [cert.p12] Add a keybundle into a keystore\n");
+ printf(" addpgp [storeName] [key.asc] Add a PGP key into a keystore\n");
+ printf(" remove [E] Remove an object from a keystore\n");
+ printf(" show [command]\n");
+ printf(" cert [C] Examine a certificate\n");
+ printf(" req [req.pem] Examine a certificate request (CSR)\n");
+ printf(" crl [crl.pem] Examine a certificate revocation list\n");
+ printf(" kb [X] Examine a keybundle\n");
+ printf(" pgp [P|S] Examine a PGP key\n");
+ printf(" message [command]\n");
+ printf(" sign pgp|pgpdetach|smime [X|S] Sign a message\n");
+ printf(" encrypt pgp|smime [C|P] Encrypt a message\n");
+ printf(" signencrypt [S] [P] PGP sign & encrypt a message\n");
+ printf(" verify pgp|smime Verify a message\n");
+ printf(" decrypt pgp|smime ((X) ...) Decrypt a message (S/MIME needs X)\n");
+ printf(" exportcerts Export certs from S/MIME message\n");
+ printf("\n");
+ printf("Object types: K = private key, C = certificate, X = key bundle,\n");
+ printf(" P = PGP public key, S = PGP secret key, E = generic entry\n");
+ printf("\n");
+ printf("An object must be either a filename or a keystore reference (\"store:obj\").\n");
+ printf("\n");
+ printf("Log level is from 0 (quiet) to 8 (debug)\n");
+ printf("\n");
}
int main(int argc, char **argv)
{
- QCA::Initializer qcaInit;
- QCoreApplication app(argc, argv);
- QFile logFile;
- QTextStream logStream (stderr);
- StreamLogger streamLogger (logStream);
-
- QStringList args;
- for(int n = 1; n < argc; ++n)
- args.append(QString::fromLocal8Bit(argv[n]));
-
- if(args.count() < 1)
- {
- usage();
- return 1;
- }
-
- bool have_pass = false;
- bool have_newpass = false;
- QCA::SecureArray pass, newpass;
- bool allowprompt = true;
- bool ordered = false;
- bool debug = false;
- bool nosys = false;
- bool nobundle = false;
- QString rootsFile, nonRootsFile;
-
- for(int n = 0; n < args.count(); ++n)
- {
- QString s = args[n];
- if(!s.startsWith("--"))
- continue;
- QString var;
- QString val;
- int x = s.indexOf('=');
- if(x != -1)
- {
- var = s.mid(2, x - 2);
- val = s.mid(x + 1);
- }
- else
- {
- var = s.mid(2);
- }
-
- bool known = true;
-
- if(var == "pass")
- {
- have_pass = true;
- pass = val.toUtf8();
- }
- else if(var == "newpass")
- {
- have_newpass = true;
- newpass = val.toUtf8();
- }
- else if(var == "log-file")
- {
- logFile.setFileName (val);
- logFile.open (QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);
- logStream.setDevice (&logFile);
- }
- else if(var == "log-level")
- {
- QCA::logger ()->setLevel ((QCA::Logger::Severity)val.toInt ());
- }
- else if(var == "noprompt")
- allowprompt = false;
- else if(var == "ordered")
- ordered = true;
- else if(var == "debug")
- debug = true;
- else if(var == "roots")
- rootsFile = val;
- else if(var == "nonroots")
- nonRootsFile = val;
- else if(var == "nosys")
- nosys = true;
- else if(var == "nobundle")
- nobundle = true;
- else
- known = false;
-
- if(known)
- {
- args.removeAt(n);
- --n; // adjust position
- }
- }
-
- // help
- if(args.isEmpty() || args[0] == "help" || args[0] == "--help" || args[0] == "-h")
- {
- usage();
- return 0;
- }
-
- // version
- if(args[0] == "version" || args[0] == "--version" || args[0] == "-v")
- {
- int ver = qcaVersion();
- int maj = (ver >> 16) & 0xff;
- int min = (ver >> 8) & 0xff;
- int bug = ver & 0xff;
- printf("%s version %s by Justin Karneges\n", APPNAME, VERSION);
- printf("Using QCA version %d.%d.%d\n", maj, min, bug);
- return 0;
- }
-
- // show plugins
- if(args[0] == "plugins")
- {
- QStringList paths = QCA::pluginPaths();
- if(!paths.isEmpty())
- {
- for(int n = 0; n < paths.count(); ++n)
- {
- printf(" %s\n", qPrintable(QDir::toNativeSeparators(paths[n])));
- }
- }
- else
- printf(" (none)\n");
-
- QCA::ProviderList list = QCA::providers();
-
- if(debug)
- output_plugin_diagnostic_text();
-
- printf("Available Providers:\n");
- if(!list.isEmpty())
- {
- for(int n = 0; n < list.count(); ++n)
- {
- printf(" %s\n", qPrintable(list[n]->name()));
- QString credit = list[n]->credit();
- if(!credit.isEmpty())
- {
- QStringList lines = wrapstring(credit, 74);
- foreach(const QString &s, lines)
- printf(" %s\n", qPrintable(s));
- }
- if (debug)
- {
- QStringList capabilities = list[n]->features();
- foreach(const QString &capability, capabilities)
- {
- printf(" *%s", qPrintable(capability));
- if(!QCA::isSupported(qPrintable(capability), list[n]->name()))
- {
- printf("(NOT supported) - bug");
- }
- printf("\n");
- }
- }
- }
- }
- else
- printf(" (none)\n");
-
- QCA::unloadAllPlugins();
-
- if(debug)
- output_plugin_diagnostic_text();
-
- return 0;
- }
-
- // config stuff
- if(args[0] == "config")
- {
- if(args.count() < 2)
- {
- usage();
- return 1;
- }
-
- if(args[1] == "save")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QString name = args[2];
- QCA::Provider *p = QCA::findProvider(name);
- if(!p)
- {
- fprintf(stderr, "Error: no such provider '%s'.\n", qPrintable(name));
- return 1;
- }
-
- QVariantMap map1 = p->defaultConfig();
- if(map1.isEmpty())
- {
- fprintf(stderr, "Error: provider does not support configuration.\n");
- return 1;
- }
-
- // set and save
- QCA::setProviderConfig(name, map1);
- QCA::saveProviderConfig(name);
- printf("Done.\n");
- return 0;
- }
- else if(args[1] == "edit")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QString name = args[2];
- if(!QCA::findProvider(name))
- {
- fprintf(stderr, "Error: no such provider '%s'.\n", qPrintable(name));
- return 1;
- }
-
- QVariantMap map1 = QCA::getProviderConfig(name);
- if(map1.isEmpty())
- {
- fprintf(stderr, "Error: provider does not support configuration.\n");
- return 1;
- }
-
- printf("Editing configuration for %s ...\n", qPrintable(name));
- printf("Note: to clear a string entry, type whitespace and press enter.\n");
-
- map1 = provider_config_edit(map1);
- if(map1.isEmpty())
- return 1;
-
- // set and save
- QCA::setProviderConfig(name, map1);
- QCA::saveProviderConfig(name);
- printf("Done.\n");
- return 0;
- }
- else
- {
- usage();
- return 1;
- }
- }
-
- // enable console passphrase prompt
- PassphrasePromptThread passphrasePrompt;
- if(!allowprompt)
- passphrasePrompt.pp->allowPrompt = false;
- if(have_pass)
- passphrasePrompt.pp->setExplicitPassword(pass);
-
- if(args[0] == "key")
- {
- if(args.count() < 2)
- {
- usage();
- return 1;
- }
-
- if(args[1] == "make")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- bool genrsa;
- int bits;
-
- if(args[2] == "rsa")
- {
- if(!QCA::isSupported("rsa"))
- {
- fprintf(stderr, "Error: need 'rsa' feature.\n");
- return 1;
- }
-
- genrsa = true;
- bits = args[3].toInt();
- if(bits < 512)
- {
- fprintf(stderr, "Error: RSA bits must be at least 512.\n");
- return 1;
- }
- }
- else if(args[2] == "dsa")
- {
- if(!QCA::isSupported("dsa"))
- {
- fprintf(stderr, "Error: need 'dsa' feature.\n");
- return 1;
- }
-
- if(!QCA::isSupported("dlgroup"))
- {
- fprintf(stderr, "Error: need 'dlgroup' feature.\n");
- return 1;
- }
-
- genrsa = false;
- bits = args[3].toInt();
- if(bits != 512 && bits != 768 && bits != 1024)
- {
- fprintf(stderr, "Error: DSA bits must be 512, 768, or 1024.\n");
- return 1;
- }
- }
- else
- {
- usage();
- return 1;
- }
-
- if(!allowprompt && !have_newpass)
- {
- fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
- return 1;
- }
-
- QCA::PrivateKey priv;
- QString pubFileName, privFileName;
-
- if(genrsa)
- {
- // note: third arg is bogus, doesn't apply to RSA
- priv = AnimatedKeyGen::makeKey(QCA::PKey::RSA, bits, QCA::DSA_512);
- pubFileName = "rsapub.pem";
- privFileName = "rsapriv.pem";
- }
- else // dsa
- {
- QCA::DLGroupSet set;
- if(bits == 512)
- set = QCA::DSA_512;
- else if(bits == 768)
- set = QCA::DSA_768;
- else // 1024
- set = QCA::DSA_1024;
-
- // note: second arg is bogus, doesn't apply to DSA
- priv = AnimatedKeyGen::makeKey(QCA::PKey::DSA, 0, set);
- pubFileName = "dsapub.pem";
- privFileName = "dsapriv.pem";
- }
-
- if(priv.isNull())
- {
- fprintf(stderr, "Error: unable to generate key.\n");
- return 1;
- }
-
- QCA::PublicKey pub = priv.toPublicKey();
-
- // prompt for new passphrase if necessary
- if(!have_newpass)
- {
- while(!promptForNewPassphrase(&newpass))
- {
- }
- have_newpass = true;
- }
-
- if(pub.toPEMFile(pubFileName))
- printf("Public key saved to %s\n", qPrintable(pubFileName));
- else
- {
- fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(pubFileName));
- return 1;
- }
-
- bool ok;
- if(!newpass.isEmpty())
- ok = priv.toPEMFile(privFileName, newpass);
- else
- ok = priv.toPEMFile(privFileName);
- if(ok)
- printf("Private key saved to %s\n", qPrintable(privFileName));
- else
- {
- fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(privFileName));
- return 1;
- }
- }
- else if(args[1] == "changepass")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::PrivateKey priv = get_K(args[2]);
- if(priv.isNull())
- return 1;
-
- if(!allowprompt && !have_newpass)
- {
- fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
- return 1;
- }
-
- // prompt for new passphrase if necessary
- if(!have_newpass)
- {
- while(!promptForNewPassphrase(&newpass))
- {
- }
- have_newpass = true;
- }
-
- QString out;
- if(!newpass.isEmpty())
- out = priv.toPEM(newpass);
- else
- out = priv.toPEM();
- if(!out.isEmpty())
- printf("%s", qPrintable(out));
- else
- {
- fprintf(stderr, "Error: can't encode key.\n");
- return 1;
- }
- }
- else
- {
- usage();
- return 1;
- }
- }
- else if(args[0] == "cert")
- {
- if(args.count() < 2)
- {
- usage();
- return 1;
- }
-
- if(args[1] == "makereq" || args[1] == "makereqadv")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("csr"))
- {
- fprintf(stderr, "Error: need 'csr' feature.\n");
- return 1;
- }
-
- QCA::PrivateKey priv = get_K(args[2]);
- if(priv.isNull())
- return 1;
-
- printf("\n");
-
- bool advanced = (args[1] == "makereqadv") ? true: false;
-
- QCA::CertificateOptions opts = promptForCertAttributes(advanced, true);
- QCA::CertificateRequest req(opts, priv);
-
- QString reqname = "certreq.pem";
- if(req.toPEMFile(reqname))
- printf("Certificate request saved to %s\n", qPrintable(reqname));
- else
- {
- fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(reqname));
- return 1;
- }
- }
- else if(args[1] == "makeself" || args[1] == "makeselfadv")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("cert"))
- {
- fprintf(stderr, "Error: need 'cert' feature.\n");
- return 1;
- }
-
- QCA::PrivateKey priv = get_K(args[2]);
- if(priv.isNull())
- return 1;
-
- printf("\n");
-
- bool advanced = (args[1] == "makeselfadv") ? true: false;
-
- QCA::CertificateOptions opts = promptForCertAttributes(advanced, false);
- QCA::Certificate cert(opts, priv);
-
- QString certname = "cert.pem";
- if(cert.toPEMFile(certname))
- printf("Certificate saved to %s\n", qPrintable(certname));
- else
- {
- fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(certname));
- return 1;
- }
- }
- else if(args[1] == "validate")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::Certificate target = get_C(args[2]);
- if(target.isNull())
- return 1;
-
- // get roots
- QCA::CertificateCollection roots;
- if(!nosys)
- roots += QCA::systemStore();
- if(!rootsFile.isEmpty())
- roots += QCA::CertificateCollection::fromFlatTextFile(rootsFile);
-
- // get nonroots
- QCA::CertificateCollection nonroots;
- if(!nonRootsFile.isEmpty())
- nonroots = QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
-
- QCA::Validity v = target.validate(roots, nonroots);
- if(v == QCA::ValidityGood)
- printf("Certificate is valid\n");
- else
- {
- printf("Certificate is NOT valid: %s\n", qPrintable(validityToString(v)));
- return 1;
- }
- }
- else
- {
- usage();
- return 1;
- }
- }
- else if(args[0] == "keybundle")
- {
- if(args.count() < 2)
- {
- usage();
- return 1;
- }
-
- if(args[1] == "make")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("pkcs12"))
- {
- fprintf(stderr, "Error: need 'pkcs12' feature.\n");
- return 1;
- }
-
- QCA::PrivateKey priv = get_K(args[2]);
- if(priv.isNull())
- return 1;
-
- QCA::Certificate cert = get_C(args[3]);
- if(cert.isNull())
- return 1;
-
- // get roots
- QCA::CertificateCollection roots;
- if(!nosys)
- roots += QCA::systemStore();
- if(!rootsFile.isEmpty())
- roots += QCA::CertificateCollection::fromFlatTextFile(rootsFile);
-
- // get nonroots
- QCA::CertificateCollection nonroots;
- if(!nonRootsFile.isEmpty())
- nonroots = QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
-
- QList<QCA::Certificate> issuer_pool = roots.certificates() + nonroots.certificates();
-
- QCA::CertificateChain chain;
- chain += cert;
- chain = chain.complete(issuer_pool);
-
- QCA::KeyBundle key;
- key.setName(chain.primary().commonName());
- key.setCertificateChainAndKey(chain, priv);
-
- if(!allowprompt && !have_newpass)
- {
- fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
- return 1;
- }
-
- // prompt for new passphrase if necessary
- if(!have_newpass)
- {
- while(!promptForNewPassphrase(&newpass))
- {
- }
- have_newpass = true;
- }
-
- if(newpass.isEmpty())
- {
- fprintf(stderr, "Error: keybundles cannot have empty passphrases.\n");
- return 1;
- }
-
- QString newFileName = "cert.p12";
-
- if(key.toFile(newFileName, newpass))
- printf("Keybundle saved to %s\n", qPrintable(newFileName));
- else
- {
- fprintf(stderr, "Error: can't encode keybundle.\n");
- return 1;
- }
- }
- else if(args[1] == "extract")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::KeyBundle key = get_X(args[2]);
- if(key.isNull())
- return 1;
-
- QCA::PrivateKey priv = key.privateKey();
- bool export_priv = priv.canExport();
-
- if(export_priv)
- {
- fprintf(stderr, "You will need to create a passphrase for the extracted private key.\n");
-
- if(!allowprompt && !have_newpass)
- {
- fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
- return 1;
- }
-
- // prompt for new passphrase if necessary
- if(!have_newpass)
- {
- while(!promptForNewPassphrase(&newpass))
- {
- }
- have_newpass = true;
- }
- }
-
- printf("Certs: (first is primary)\n");
- QCA::CertificateChain chain = key.certificateChain();
- for(int n = 0; n < chain.count(); ++n)
- printf("%s", qPrintable(chain[n].toPEM()));
- printf("Private Key:\n");
- if(export_priv)
- {
- QString out;
- if(!newpass.isEmpty())
- out = priv.toPEM(newpass);
- else
- out = priv.toPEM();
- printf("%s", qPrintable(out));
- }
- else
- {
- printf("(Key is not exportable)\n");
- }
- }
- else if(args[1] == "changepass")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::KeyBundle key = get_X(args[2]);
- if(key.isNull())
- return 1;
-
- if(!key.privateKey().canExport())
- {
- fprintf(stderr, "Error: private key not exportable.\n");
- return 1;
- }
-
- if(!allowprompt && !have_newpass)
- {
- fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
- return 1;
- }
-
- // prompt for new passphrase if necessary
- if(!have_newpass)
- {
- while(!promptForNewPassphrase(&newpass))
- {
- }
- have_newpass = true;
- }
-
- if(newpass.isEmpty())
- {
- fprintf(stderr, "Error: keybundles cannot have empty passphrases.\n");
- return 1;
- }
-
- QFileInfo fi(args[2]);
- QString newFileName = fi.baseName() + "_new.p12";
-
- if(key.toFile(newFileName, newpass))
- printf("Keybundle saved to %s\n", qPrintable(newFileName));
- else
- {
- fprintf(stderr, "Error: can't encode keybundle.\n");
- return 1;
- }
- }
- else
- {
- usage();
- return 1;
- }
- }
- else if(args[0] == "keystore")
- {
- if(args.count() < 2)
- {
- usage();
- return 1;
- }
-
- if(args[1] == "list-stores")
- {
- ksm_start_and_wait();
-
- QCA::KeyStoreManager ksm;
- QStringList storeList = ksm.keyStores();
-
- for(int n = 0; n < storeList.count(); ++n)
- {
- QCA::KeyStore ks(storeList[n], &ksm);
- QString type = kstype_to_string(ks.type());
- printf("%s %s [%s]\n", qPrintable(type), qPrintable(idHash(ks.id())), qPrintable(ks.name()));
- }
-
- if(debug)
- output_keystore_diagnostic_text();
- }
- else if(args[1] == "list")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- ksm_start_and_wait();
-
- QCA::KeyStoreManager ksm;
- QCA::KeyStore store(getKeyStore(args[2]), &ksm);
- if(!store.isValid())
- {
- if(debug)
- output_keystore_diagnostic_text();
-
- fprintf(stderr, "Error: no such store\n");
- return 1;
- }
-
- QList<QCA::KeyStoreEntry> list = store.entryList();
- for(int n = 0; n < list.count(); ++n)
- {
- QCA::KeyStoreEntry i = list[n];
- QString type = ksentrytype_to_string(i.type());
- printf("%s %s [%s]\n", qPrintable(type), qPrintable(idHash(i.id())), qPrintable(i.name()));
- }
-
- if(debug)
- output_keystore_diagnostic_text();
- }
- else if(args[1] == "monitor")
- {
- KeyStoreMonitor::monitor();
-
- if(debug)
- output_keystore_diagnostic_text();
- }
- else if(args[1] == "export")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::KeyStoreEntry entry = get_E(args[2]);
- if(entry.isNull())
- return 1;
-
- if(entry.type() == QCA::KeyStoreEntry::TypeCertificate)
- printf("%s", qPrintable(entry.certificate().toPEM()));
- else if(entry.type() == QCA::KeyStoreEntry::TypeCRL)
- printf("%s", qPrintable(entry.crl().toPEM()));
- else if(entry.type() == QCA::KeyStoreEntry::TypePGPPublicKey || entry.type() == QCA::KeyStoreEntry::TypePGPSecretKey)
- printf("%s", qPrintable(entry.pgpPublicKey().toString()));
- else if(entry.type() == QCA::KeyStoreEntry::TypeKeyBundle)
- {
- fprintf(stderr, "Error: use 'keybundle extract' command instead.\n");
- return 1;
- }
- else
- {
- fprintf(stderr, "Error: cannot export type '%d'.\n", entry.type());
- return 1;
- }
- }
- else if(args[1] == "exportref")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::KeyStoreEntry entry = get_E(args[2]);
- if(entry.isNull())
- return 1;
- printf("%s", make_ksentry_string(entry.toString()).toUtf8().data());
- }
- else if(args[1] == "addkb")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- ksm_start_and_wait();
-
- QCA::KeyStoreManager ksm;
- QCA::KeyStore store(getKeyStore(args[2]), &ksm);
- if(!store.isValid())
- {
- fprintf(stderr, "Error: no such store\n");
- return 1;
- }
-
- QCA::KeyBundle key = get_X(args[3]);
- if(key.isNull())
- return 1;
-
- if(!store.writeEntry(key).isEmpty())
- printf("Entry written.\n");
- else
- {
- fprintf(stderr, "Error: unable to write entry.\n");
- return 1;
- }
- }
- else if(args[1] == "addpgp")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("openpgp"))
- {
- fprintf(stderr, "Error: need 'openpgp' feature.\n");
- return 1;
- }
-
- ksm_start_and_wait();
-
- QCA::KeyStoreManager ksm;
- QCA::KeyStore store(getKeyStore(args[2]), &ksm);
- if(!store.isValid())
- {
- fprintf(stderr, "Error: no such store\n");
- return 1;
- }
-
- QCA::PGPKey pub = QCA::PGPKey::fromFile(args[3]);
- if(pub.isNull())
- return 1;
-
- if(!store.writeEntry(pub).isEmpty())
- printf("Entry written.\n");
- else
- {
- fprintf(stderr, "Error: unable to write entry.\n");
- return 1;
- }
- }
- else if(args[1] == "remove")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::KeyStoreEntry entry = get_E(args[2]);
- if(entry.isNull())
- return 1;
-
- QCA::KeyStoreManager ksm;
- QCA::KeyStore store(entry.storeId(), &ksm);
- if(!store.isValid())
- {
- fprintf(stderr, "Error: no such store\n");
- return 1;
- }
-
- if(store.removeEntry(entry.id()))
- printf("Entry removed.\n");
- else
- {
- fprintf(stderr, "Error: unable to remove entry.\n");
- return 1;
- }
- }
- else
- {
- usage();
- return 1;
- }
- }
- else if(args[0] == "show")
- {
- if(args.count() < 2)
- {
- usage();
- return 1;
- }
-
- if(args[1] == "cert")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::Certificate cert = get_C(args[2]);
- if(cert.isNull())
- return 1;
-
- print_cert(cert, ordered);
- }
- else if(args[1] == "req")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("csr"))
- {
- fprintf(stderr, "Error: need 'csr' feature.\n");
- return 1;
- }
-
- QCA::CertificateRequest req(args[2]);
- if(req.isNull())
- {
- fprintf(stderr, "Error: can't read/process certificate request file.\n");
- return 1;
- }
-
- print_certreq(req, ordered);
- }
- else if(args[1] == "crl")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("crl"))
- {
- fprintf(stderr, "Error: need 'crl' feature.\n");
- return 1;
- }
-
- QCA::CRL crl;
- if(is_pem_file(args[2]))
- crl = QCA::CRL::fromPEMFile(args[2]);
- else
- crl = QCA::CRL::fromDER(read_der_file(args[2]));
- if(crl.isNull())
- {
- fprintf(stderr, "Error: unable to read/process CRL file.\n");
- return 1;
- }
-
- print_crl(crl, ordered);
- }
- else if(args[1] == "kb")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::KeyBundle key = get_X(args[2]);
- if(key.isNull())
- return 1;
-
- printf("Keybundle contains %d certificates. Displaying primary:\n", key.certificateChain().count());
- print_cert(key.certificateChain().primary(), ordered);
- }
- else if(args[1] == "pgp")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- // try for secret key, then try public key
- QCA::PGPKey key = get_S(args[2], true).first;
- if(key.isNull())
- {
- key = get_P(args[2]);
- if(key.isNull())
- return 1;
- }
-
- print_pgp(key);
- }
- else
- {
- usage();
- return 1;
- }
- }
- else if(args[0] == "message")
- {
- if(args.count() < 2)
- {
- usage();
- return 1;
- }
-
- if(args[1] == "sign")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- QCA::SecureMessageSystem *sms;
- QCA::SecureMessageKey skey;
- QCA::SecureMessage::SignMode mode;
- bool pgp = false;
-
- if(args[2] == "pgp")
- {
- if(!QCA::isSupported("openpgp"))
- {
- fprintf(stderr, "Error: need 'openpgp' feature.\n");
- return 1;
- }
-
- QPair<QCA::PGPKey, QCA::PGPKey> key = get_S(args[3]);
- if(key.first.isNull())
- return 1;
-
- sms = new QCA::OpenPGP;
- skey.setPGPSecretKey(key.first);
- mode = QCA::SecureMessage::Clearsign;
- pgp = true;
- }
- else if(args[2] == "pgpdetach")
- {
- if(!QCA::isSupported("openpgp"))
- {
- fprintf(stderr, "Error: need 'openpgp' feature.\n");
- return 1;
- }
-
- QPair<QCA::PGPKey, QCA::PGPKey> key = get_S(args[3]);
- if(key.first.isNull())
- return 1;
-
- sms = new QCA::OpenPGP;
- skey.setPGPSecretKey(key.first);
- mode = QCA::SecureMessage::Detached;
- pgp = true;
- }
- else if(args[2] == "smime")
- {
- if(!QCA::isSupported("cms"))
- {
- fprintf(stderr, "Error: need 'cms' feature.\n");
- return 1;
- }
-
- QCA::KeyBundle key = get_X(args[3]);
- if(key.isNull())
- return 1;
-
- // get nonroots
- QCA::CertificateCollection nonroots;
- if(!nonRootsFile.isEmpty())
- nonroots = QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
-
- QList<QCA::Certificate> issuer_pool = nonroots.certificates();
-
- QCA::CertificateChain chain = key.certificateChain();
- chain = chain.complete(issuer_pool);
-
- sms = new QCA::CMS;
- skey.setX509CertificateChain(chain);
- skey.setX509PrivateKey(key.privateKey());
- mode = QCA::SecureMessage::Detached;
- }
- else
- {
- usage();
- return 1;
- }
-
- // read input data from stdin all at once
- QByteArray plain;
- while(!feof(stdin))
- {
- QByteArray block(1024, 0);
- int n = fread(block.data(), 1, 1024, stdin);
- if(n < 0)
- break;
- block.resize(n);
- plain += block;
- }
-
- // smime envelope
- if(!pgp)
- {
- QString text = add_cr(QString::fromUtf8(plain));
- plain = QString(mime_signpart).arg(text).toUtf8();
- }
-
- QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
- msg->setSigner(skey);
- // pgp should always be ascii
- if(pgp)
- msg->setFormat(QCA::SecureMessage::Ascii);
- msg->setBundleSignerEnabled(!nobundle);
- msg->startSign(mode);
- msg->update(plain);
- msg->end();
- msg->waitForFinished(-1);
-
- if(debug)
- {
- output_keystore_diagnostic_text();
- output_message_diagnostic_text(msg);
- }
-
- if(!msg->success())
- {
- QString errstr = smErrorToString(msg->errorCode());
- delete msg;
- delete sms;
-
- fprintf(stderr, "Error: unable to sign: %s\n", qPrintable(errstr));
- return 1;
- }
-
- QString hashName = msg->hashName();
-
- QByteArray output;
- if(mode == QCA::SecureMessage::Detached)
- output = msg->signature();
- else
- output = msg->read();
-
- delete msg;
- delete sms;
-
- // smime envelope
- if(!pgp)
- {
- QCA::Base64 enc;
- enc.setLineBreaksEnabled(true);
- enc.setLineBreaksColumn(76);
- QString sigtext = add_cr(enc.arrayToString(output));
- QString str = QString(mime_signed).arg(hashName).arg(QString::fromUtf8(plain)).arg(sigtext);
- output = str.toUtf8();
- }
-
- printf("%s", output.data());
- }
- else if(args[1] == "encrypt")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- QCA::SecureMessageSystem *sms;
- QCA::SecureMessageKey skey;
- bool pgp = false;
-
- if(args[2] == "pgp")
- {
- if(!QCA::isSupported("openpgp"))
- {
- fprintf(stderr, "Error: need 'openpgp' feature.\n");
- return 1;
- }
-
- QCA::PGPKey key = get_P(args[3]);
- if(key.isNull())
- return 1;
-
- sms = new QCA::OpenPGP;
- skey.setPGPPublicKey(key);
- pgp = true;
- }
- else if(args[2] == "smime")
- {
- if(!QCA::isSupported("cms"))
- {
- fprintf(stderr, "Error: need 'cms' feature.\n");
- return 1;
- }
-
- QCA::Certificate cert = get_C(args[3]);
- if(cert.isNull())
- return 1;
-
- sms = new QCA::CMS;
- skey.setX509CertificateChain(cert);
- }
- else
- {
- usage();
- return 1;
- }
-
- // read input data from stdin all at once
- QByteArray plain;
- while(!feof(stdin))
- {
- QByteArray block(1024, 0);
- int n = fread(block.data(), 1, 1024, stdin);
- if(n < 0)
- break;
- block.resize(n);
- plain += block;
- }
-
- QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
- msg->setRecipient(skey);
- // pgp should always be ascii
- if(pgp)
- msg->setFormat(QCA::SecureMessage::Ascii);
- msg->startEncrypt();
- msg->update(plain);
- msg->end();
- msg->waitForFinished(-1);
-
- if(debug)
- {
- output_keystore_diagnostic_text();
- output_message_diagnostic_text(msg);
- }
-
- if(!msg->success())
- {
- QString errstr = smErrorToString(msg->errorCode());
- delete msg;
- delete sms;
- fprintf(stderr, "Error: unable to encrypt: %s\n", qPrintable(errstr));
- return 1;
- }
-
- QByteArray output = msg->read();
- delete msg;
- delete sms;
-
- // smime envelope
- if(!pgp)
- {
- QCA::Base64 enc;
- enc.setLineBreaksEnabled(true);
- enc.setLineBreaksColumn(76);
- QString enctext = add_cr(enc.arrayToString(output));
- QString str = QString(mime_enveloped).arg(enctext);
- output = str.toUtf8();
- }
-
- printf("%s", output.data());
- }
- else if(args[1] == "signencrypt")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("openpgp"))
- {
- fprintf(stderr, "Error: need 'openpgp' feature.\n");
- return 1;
- }
-
- QCA::SecureMessageSystem *sms;
- QCA::SecureMessageKey skey;
- QCA::SecureMessageKey rkey;
-
- {
- QPair<QCA::PGPKey,QCA::PGPKey> sec = get_S(args[2]);
- if(sec.first.isNull())
- return 1;
-
- QCA::PGPKey pub = get_P(args[3]);
- if(pub.isNull())
- return 1;
-
- sms = new QCA::OpenPGP;
- skey.setPGPSecretKey(sec.first);
- rkey.setPGPPublicKey(pub);
- }
-
- // read input data from stdin all at once
- QByteArray plain;
- while(!feof(stdin))
- {
- QByteArray block(1024, 0);
- int n = fread(block.data(), 1, 1024, stdin);
- if(n < 0)
- break;
- block.resize(n);
- plain += block;
- }
-
- QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
- if(!msg->canSignAndEncrypt())
- {
- delete msg;
- delete sms;
- fprintf(stderr, "Error: cannot perform integrated sign and encrypt.\n");
- return 1;
- }
-
- msg->setSigner(skey);
- msg->setRecipient(rkey);
- msg->setFormat(QCA::SecureMessage::Ascii);
- msg->startSignAndEncrypt();
- msg->update(plain);
- msg->end();
- msg->waitForFinished(-1);
-
- if(debug)
- {
- output_keystore_diagnostic_text();
- output_message_diagnostic_text(msg);
- }
-
- if(!msg->success())
- {
- QString errstr = smErrorToString(msg->errorCode());
- delete msg;
- delete sms;
- fprintf(stderr, "Error: unable to sign and encrypt: %s\n", qPrintable(errstr));
- return 1;
- }
-
- QByteArray output = msg->read();
- delete msg;
- delete sms;
-
- printf("%s", output.data());
- }
- else if(args[1] == "verify")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::SecureMessageSystem *sms;
- bool pgp = false;
-
- if(args[2] == "pgp")
- {
- if(!QCA::isSupported("openpgp"))
- {
- fprintf(stderr, "Error: need 'openpgp' feature.\n");
- return 1;
- }
-
- sms = new QCA::OpenPGP;
- pgp = true;
- }
- else if(args[2] == "smime")
- {
- if(!QCA::isSupported("cms"))
- {
- fprintf(stderr, "Error: need 'cms' feature.\n");
- return 1;
- }
-
- // get roots
- QCA::CertificateCollection roots;
- if(!nosys)
- roots += QCA::systemStore();
- if(!rootsFile.isEmpty())
- roots += QCA::CertificateCollection::fromFlatTextFile(rootsFile);
-
- // get intermediates and possible signers, in case
- // the message does not have them.
- QCA::CertificateCollection nonroots;
- if(!nonRootsFile.isEmpty())
- nonroots += QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
-
- sms = new QCA::CMS;
- ((QCA::CMS *)sms)->setTrustedCertificates(roots);
- ((QCA::CMS *)sms)->setUntrustedCertificates(nonroots);
- }
- else
- {
- usage();
- return 1;
- }
-
- QByteArray data, sig;
- QString smime_text;
- {
- // read input data from stdin all at once
- QByteArray plain;
- while(!feof(stdin))
- {
- QByteArray block(1024, 0);
- int n = fread(block.data(), 1, 1024, stdin);
- if(n < 0)
- break;
- block.resize(n);
- plain += block;
- }
-
- if(pgp)
- {
- // pgp can be either a detached signature followed
- // by data, or an integrated message.
-
- // detached signature?
- if(plain.startsWith("-----BEGIN PGP SIGNATURE-----"))
- {
- QString footer = "-----END PGP SIGNATURE-----\n";
- int n = plain.indexOf(footer);
- if(n == -1)
- {
- delete sms;
- fprintf(stderr, "Error: pgp signature header, but no footer.\n");
- return 1;
- }
-
- n += footer.length();
- sig = plain.mid(0, n);
- data = plain.mid(n);
- }
- else
- {
- data = plain;
- }
- }
- else
- {
- // smime envelope
- QString in = QString::fromUtf8(plain);
- in = add_cr(in); // change the line endings?!
- QString str, sigtext;
- if(!open_mime_data_sig(in, &str, &sigtext))
- {
- fprintf(stderr, "Error: can't parse message file.\n");
- return 1;
- }
-
- data = str.toUtf8();
- smime_text = str;
-
- QCA::Base64 dec;
- dec.setLineBreaksEnabled(true);
- sig = dec.stringToArray(rem_cr(sigtext)).toByteArray();
- }
- }
-
- QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
- if(pgp)
- msg->setFormat(QCA::SecureMessage::Ascii);
- msg->startVerify(sig);
- msg->update(data);
- msg->end();
- msg->waitForFinished(-1);
-
- if(debug)
- {
- output_keystore_diagnostic_text();
- output_message_diagnostic_text(msg);
- }
-
- if(!msg->success())
- {
- QString errstr = smErrorToString(msg->errorCode());
- delete msg;
- delete sms;
- fprintf(stderr, "Error: verify failed: %s\n", qPrintable(errstr));
- return 1;
- }
-
- QByteArray output;
- if(pgp && sig.isEmpty())
- output = msg->read();
-
- QList<QCA::SecureMessageSignature> signers = msg->signers();
- delete msg;
- delete sms;
-
- // for pgp clearsign, pgp signed (non-detached), and smime,
- // the signed content was inside of the message. we need
- // to print that content now
- if(pgp)
- {
- printf("%s", output.data());
- }
- else
- {
- QString str = open_mime_envelope(smime_text);
- printf("%s", str.toUtf8().data());
- }
-
- smDisplaySignatures(signers);
-
- bool allgood = true;
- foreach(const QCA::SecureMessageSignature &signer, signers)
- {
- if(signer.identityResult() != QCA::SecureMessageSignature::Valid)
- {
- allgood = false;
- break;
- }
- }
-
- if(!allgood)
- return 1;
- }
- else if(args[1] == "decrypt")
- {
- if(args.count() < 3)
- {
- usage();
- return 1;
- }
-
- QCA::SecureMessageSystem *sms;
- bool pgp = false;
-
- if(args[2] == "pgp")
- {
- if(!QCA::isSupported("openpgp"))
- {
- fprintf(stderr, "Error: need 'openpgp' feature.\n");
- return 1;
- }
-
- sms = new QCA::OpenPGP;
- pgp = true;
- }
- else if(args[2] == "smime")
- {
- if(args.count() < 4)
- {
- usage();
- return 1;
- }
-
- if(!QCA::isSupported("cms"))
- {
- fprintf(stderr, "Error: need 'cms' feature.\n");
- return 1;
- }
-
- // user can provide many possible decrypt keys
- QList<QCA::KeyBundle> keys;
- for(int n = 3; n < args.count(); ++n)
- {
- QCA::KeyBundle key = get_X(args[n]);
- if(key.isNull())
- return 1;
- keys += key;
- }
-
- sms = new QCA::CMS;
-
- QList<QCA::SecureMessageKey> skeys;
- foreach(const QCA::KeyBundle &key, keys)
- {
- QCA::SecureMessageKey skey;
- skey.setX509CertificateChain(key.certificateChain());
- skey.setX509PrivateKey(key.privateKey());
- skeys += skey;
- }
-
- ((QCA::CMS*)sms)->setPrivateKeys(skeys);
- }
- else
- {
- usage();
- return 1;
- }
-
- // read input data from stdin all at once
- QByteArray plain;
- while(!feof(stdin))
- {
- QByteArray block(1024, 0);
- int n = fread(block.data(), 1, 1024, stdin);
- if(n < 0)
- break;
- block.resize(n);
- plain += block;
- }
-
- // smime envelope
- if(!pgp)
- {
- QString in = QString::fromUtf8(plain);
- QString str = open_mime_envelope(in);
- if(str.isEmpty())
- {
- delete sms;
- fprintf(stderr, "Error: can't parse message file.\n");
- return 1;
- }
-
- QCA::Base64 dec;
- dec.setLineBreaksEnabled(true);
- plain = dec.stringToArray(rem_cr(str)).toByteArray();
- }
-
- QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
- if(pgp)
- msg->setFormat(QCA::SecureMessage::Ascii);
- msg->startDecrypt();
- msg->update(plain);
- msg->end();
- msg->waitForFinished(-1);
-
- if(debug)
- {
- output_keystore_diagnostic_text();
- output_message_diagnostic_text(msg);
- }
-
- if(!msg->success())
- {
- QString errstr = smErrorToString(msg->errorCode());
- delete msg;
- delete sms;
- fprintf(stderr, "Error: decrypt failed: %s\n", qPrintable(errstr));
- return 1;
- }
-
- QByteArray output = msg->read();
-
- QList<QCA::SecureMessageSignature> signers;
- bool wasSigned = false;
- if(msg->wasSigned())
- {
- signers = msg->signers();
- wasSigned = true;
- }
- delete msg;
- delete sms;
-
- printf("%s", output.data());
-
- if(wasSigned)
- {
- fprintf(stderr, "Message was also signed:\n");
-
- smDisplaySignatures(signers);
-
- bool allgood = true;
- foreach(const QCA::SecureMessageSignature &signer, signers)
- {
- if(signer.identityResult() != QCA::SecureMessageSignature::Valid)
- {
- allgood = false;
- break;
- }
- }
-
- if(!allgood)
- return 1;
- }
- }
- else if(args[1] == "exportcerts")
- {
- if(!QCA::isSupported("cms"))
- {
- fprintf(stderr, "Error: need 'cms' feature.\n");
- return 1;
- }
-
- QCA::SecureMessageSystem *sms = new QCA::CMS;
-
- QByteArray data, sig;
- QString smime_text;
- {
- // read input data from stdin all at once
- QByteArray plain;
- while(!feof(stdin))
- {
- QByteArray block(1024, 0);
- int n = fread(block.data(), 1, 1024, stdin);
- if(n < 0)
- break;
- block.resize(n);
- plain += block;
- }
-
- // smime envelope
- QString in = QString::fromUtf8(plain);
- QString str, sigtext;
- if(!open_mime_data_sig(in, &str, &sigtext))
- {
- delete sms;
- fprintf(stderr, "Error: can't parse message file.\n");
- return 1;
- }
-
- data = str.toUtf8();
- smime_text = str;
-
- QCA::Base64 dec;
- dec.setLineBreaksEnabled(true);
- sig = dec.stringToArray(rem_cr(sigtext)).toByteArray();
- }
-
- QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
- msg->startVerify(sig);
- msg->update(data);
- msg->end();
- msg->waitForFinished(-1);
-
- if(debug)
- output_message_diagnostic_text(msg);
-
- if(!msg->success())
- {
- QString errstr = smErrorToString(msg->errorCode());
- delete msg;
- delete sms;
- fprintf(stderr, "Error: export failed: %s\n", qPrintable(errstr));
- return 1;
- }
-
- QList<QCA::SecureMessageSignature> signers = msg->signers();
- delete msg;
- delete sms;
-
- // print out all certs of all signers
- foreach(const QCA::SecureMessageSignature &signer, signers)
- {
- QCA::SecureMessageKey key = signer.key();
- if(!key.isNull())
- {
- foreach(const QCA::Certificate &c, key.x509CertificateChain())
- printf("%s", qPrintable(c.toPEM()));
- }
- }
- }
- else
- {
- usage();
- return 1;
- }
- }
- else
- {
- usage();
- return 1;
- }
-
- return 0;
+ QCA::Initializer qcaInit;
+ QCoreApplication app(argc, argv);
+ QFile logFile;
+ QTextStream logStream(stderr);
+ StreamLogger streamLogger(logStream);
+
+ QStringList args;
+ for (int n = 1; n < argc; ++n) {
+ args.append(QString::fromLocal8Bit(argv[n]));
+ }
+
+ if (args.count() < 1) {
+ usage();
+ return 1;
+ }
+
+ bool have_pass = false;
+ bool have_newpass = false;
+ QCA::SecureArray pass, newpass;
+ bool allowprompt = true;
+ bool ordered = false;
+ bool debug = false;
+ bool nosys = false;
+ bool nobundle = false;
+ QString rootsFile, nonRootsFile;
+
+ for (int n = 0; n < args.count(); ++n) {
+ QString s = args[n];
+ if (!s.startsWith("--")) {
+ continue;
+ }
+ QString var;
+ QString val;
+ int x = s.indexOf('=');
+ if (x != -1) {
+ var = s.mid(2, x - 2);
+ val = s.mid(x + 1);
+ } else {
+ var = s.mid(2);
+ }
+
+ bool known = true;
+
+ if (var == "pass") {
+ have_pass = true;
+ pass = val.toUtf8();
+ } else if (var == "newpass") {
+ have_newpass = true;
+ newpass = val.toUtf8();
+ } else if (var == "log-file") {
+ logFile.setFileName(val);
+ logFile.open(QIODevice::Append | QIODevice::Text | QIODevice::Unbuffered);
+ logStream.setDevice(&logFile);
+ } else if (var == "log-level") {
+ QCA::logger()->setLevel((QCA::Logger::Severity)val.toInt());
+ } else if (var == "noprompt") {
+ allowprompt = false;
+ } else if (var == "ordered") {
+ ordered = true;
+ } else if (var == "debug") {
+ debug = true;
+ } else if (var == "roots") {
+ rootsFile = val;
+ } else if (var == "nonroots") {
+ nonRootsFile = val;
+ } else if (var == "nosys") {
+ nosys = true;
+ } else if (var == "nobundle") {
+ nobundle = true;
+ } else {
+ known = false;
+ }
+
+ if (known) {
+ args.removeAt(n);
+ --n; // adjust position
+ }
+ }
+
+ // help
+ if (args.isEmpty() || args[0] == "help" || args[0] == "--help" || args[0] == "-h") {
+ usage();
+ return 0;
+ }
+
+ // version
+ if (args[0] == "version" || args[0] == "--version" || args[0] == "-v") {
+ int ver = qcaVersion();
+ int maj = (ver >> 16) & 0xff;
+ int min = (ver >> 8) & 0xff;
+ int bug = ver & 0xff;
+ printf("%s version %s by Justin Karneges\n", APPNAME, VERSION);
+ printf("Using QCA version %d.%d.%d\n", maj, min, bug);
+ return 0;
+ }
+
+ // show plugins
+ if (args[0] == "plugins") {
+ QStringList paths = QCA::pluginPaths();
+ if (!paths.isEmpty()) {
+ for (int n = 0; n < paths.count(); ++n) {
+ printf(" %s\n", qPrintable(QDir::toNativeSeparators(paths[n])));
+ }
+ } else {
+ printf(" (none)\n");
+ }
+
+ QCA::ProviderList list = QCA::providers();
+
+ if (debug) {
+ output_plugin_diagnostic_text();
+ }
+
+ printf("Available Providers:\n");
+ if (!list.isEmpty()) {
+ for (int n = 0; n < list.count(); ++n) {
+ printf(" %s\n", qPrintable(list[n]->name()));
+ QString credit = list[n]->credit();
+ if (!credit.isEmpty()) {
+ QStringList lines = wrapstring(credit, 74);
+ foreach (const QString &s, lines) {
+ printf(" %s\n", qPrintable(s));
+ }
+ }
+ if (debug) {
+ QStringList capabilities = list[n]->features();
+ foreach (const QString &capability, capabilities) {
+ printf(" *%s", qPrintable(capability));
+ if (!QCA::isSupported(qPrintable(capability), list[n]->name())) {
+ printf("(NOT supported) - bug");
+ }
+ printf("\n");
+ }
+ }
+ }
+ } else {
+ printf(" (none)\n");
+ }
+
+ QCA::unloadAllPlugins();
+
+ if (debug) {
+ output_plugin_diagnostic_text();
+ }
+
+ return 0;
+ }
+
+ // config stuff
+ if (args[0] == "config") {
+ if (args.count() < 2) {
+ usage();
+ return 1;
+ }
+
+ if (args[1] == "save") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QString name = args[2];
+ QCA::Provider *p = QCA::findProvider(name);
+ if (!p) {
+ fprintf(stderr, "Error: no such provider '%s'.\n", qPrintable(name));
+ return 1;
+ }
+
+ QVariantMap map1 = p->defaultConfig();
+ if (map1.isEmpty()) {
+ fprintf(stderr, "Error: provider does not support configuration.\n");
+ return 1;
+ }
+
+ // set and save
+ QCA::setProviderConfig(name, map1);
+ QCA::saveProviderConfig(name);
+ printf("Done.\n");
+ return 0;
+ } else if (args[1] == "edit") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QString name = args[2];
+ if (!QCA::findProvider(name)) {
+ fprintf(stderr, "Error: no such provider '%s'.\n", qPrintable(name));
+ return 1;
+ }
+
+ QVariantMap map1 = QCA::getProviderConfig(name);
+ if (map1.isEmpty()) {
+ fprintf(stderr, "Error: provider does not support configuration.\n");
+ return 1;
+ }
+
+ printf("Editing configuration for %s ...\n", qPrintable(name));
+ printf("Note: to clear a string entry, type whitespace and press enter.\n");
+
+ map1 = provider_config_edit(map1);
+ if (map1.isEmpty()) {
+ return 1;
+ }
+
+ // set and save
+ QCA::setProviderConfig(name, map1);
+ QCA::saveProviderConfig(name);
+ printf("Done.\n");
+ return 0;
+ } else {
+ usage();
+ return 1;
+ }
+ }
+
+ // enable console passphrase prompt
+ PassphrasePromptThread passphrasePrompt;
+ if (!allowprompt) {
+ passphrasePrompt.pp->allowPrompt = false;
+ }
+ if (have_pass) {
+ passphrasePrompt.pp->setExplicitPassword(pass);
+ }
+
+ if (args[0] == "key") {
+ if (args.count() < 2) {
+ usage();
+ return 1;
+ }
+
+ if (args[1] == "make") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ bool genrsa;
+ int bits;
+
+ if (args[2] == "rsa") {
+ if (!QCA::isSupported("rsa")) {
+ fprintf(stderr, "Error: need 'rsa' feature.\n");
+ return 1;
+ }
+
+ genrsa = true;
+ bits = args[3].toInt();
+ if (bits < 512) {
+ fprintf(stderr, "Error: RSA bits must be at least 512.\n");
+ return 1;
+ }
+ } else if (args[2] == "dsa") {
+ if (!QCA::isSupported("dsa")) {
+ fprintf(stderr, "Error: need 'dsa' feature.\n");
+ return 1;
+ }
+
+ if (!QCA::isSupported("dlgroup")) {
+ fprintf(stderr, "Error: need 'dlgroup' feature.\n");
+ return 1;
+ }
+
+ genrsa = false;
+ bits = args[3].toInt();
+ if (bits != 512 && bits != 768 && bits != 1024) {
+ fprintf(stderr, "Error: DSA bits must be 512, 768, or 1024.\n");
+ return 1;
+ }
+ } else {
+ usage();
+ return 1;
+ }
+
+ if (!allowprompt && !have_newpass) {
+ fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
+ return 1;
+ }
+
+ QCA::PrivateKey priv;
+ QString pubFileName, privFileName;
+
+ if (genrsa) {
+ // note: third arg is bogus, doesn't apply to RSA
+ priv = AnimatedKeyGen::makeKey(QCA::PKey::RSA, bits, QCA::DSA_512);
+ pubFileName = "rsapub.pem";
+ privFileName = "rsapriv.pem";
+ } else { // dsa
+ QCA::DLGroupSet set;
+ if (bits == 512) {
+ set = QCA::DSA_512;
+ } else if (bits == 768) {
+ set = QCA::DSA_768;
+ } else { // 1024
+ set = QCA::DSA_1024;
+ }
+
+ // note: second arg is bogus, doesn't apply to DSA
+ priv = AnimatedKeyGen::makeKey(QCA::PKey::DSA, 0, set);
+ pubFileName = "dsapub.pem";
+ privFileName = "dsapriv.pem";
+ }
+
+ if (priv.isNull()) {
+ fprintf(stderr, "Error: unable to generate key.\n");
+ return 1;
+ }
+
+ QCA::PublicKey pub = priv.toPublicKey();
+
+ // prompt for new passphrase if necessary
+ if (!have_newpass) {
+ while (!promptForNewPassphrase(&newpass)) {
+ }
+ have_newpass = true;
+ }
+
+ if (pub.toPEMFile(pubFileName)) {
+ printf("Public key saved to %s\n", qPrintable(pubFileName));
+ } else {
+ fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(pubFileName));
+ return 1;
+ }
+
+ bool ok;
+ if (!newpass.isEmpty()) {
+ ok = priv.toPEMFile(privFileName, newpass);
+ } else {
+ ok = priv.toPEMFile(privFileName);
+ }
+ if (ok) {
+ printf("Private key saved to %s\n", qPrintable(privFileName));
+ } else {
+ fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(privFileName));
+ return 1;
+ }
+ } else if (args[1] == "changepass") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::PrivateKey priv = get_K(args[2]);
+ if (priv.isNull()) {
+ return 1;
+ }
+
+ if (!allowprompt && !have_newpass) {
+ fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
+ return 1;
+ }
+
+ // prompt for new passphrase if necessary
+ if (!have_newpass) {
+ while (!promptForNewPassphrase(&newpass)) {
+ }
+ have_newpass = true;
+ }
+
+ QString out;
+ if (!newpass.isEmpty()) {
+ out = priv.toPEM(newpass);
+ } else {
+ out = priv.toPEM();
+ }
+ if (!out.isEmpty()) {
+ printf("%s", qPrintable(out));
+ } else {
+ fprintf(stderr, "Error: can't encode key.\n");
+ return 1;
+ }
+ } else {
+ usage();
+ return 1;
+ }
+ } else if (args[0] == "cert") {
+ if (args.count() < 2) {
+ usage();
+ return 1;
+ }
+
+ if (args[1] == "makereq" || args[1] == "makereqadv") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("csr")) {
+ fprintf(stderr, "Error: need 'csr' feature.\n");
+ return 1;
+ }
+
+ QCA::PrivateKey priv = get_K(args[2]);
+ if (priv.isNull()) {
+ return 1;
+ }
+
+ printf("\n");
+
+ bool advanced = (args[1] == "makereqadv") ? true : false;
+
+ QCA::CertificateOptions opts = promptForCertAttributes(advanced, true);
+ QCA::CertificateRequest req(opts, priv);
+
+ QString reqname = "certreq.pem";
+ if (req.toPEMFile(reqname)) {
+ printf("Certificate request saved to %s\n", qPrintable(reqname));
+ } else {
+ fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(reqname));
+ return 1;
+ }
+ } else if (args[1] == "makeself" || args[1] == "makeselfadv") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("cert")) {
+ fprintf(stderr, "Error: need 'cert' feature.\n");
+ return 1;
+ }
+
+ QCA::PrivateKey priv = get_K(args[2]);
+ if (priv.isNull()) {
+ return 1;
+ }
+
+ printf("\n");
+
+ bool advanced = (args[1] == "makeselfadv") ? true : false;
+
+ QCA::CertificateOptions opts = promptForCertAttributes(advanced, false);
+ QCA::Certificate cert(opts, priv);
+
+ QString certname = "cert.pem";
+ if (cert.toPEMFile(certname)) {
+ printf("Certificate saved to %s\n", qPrintable(certname));
+ } else {
+ fprintf(stderr, "Error: can't encode/write %s\n", qPrintable(certname));
+ return 1;
+ }
+ } else if (args[1] == "validate") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::Certificate target = get_C(args[2]);
+ if (target.isNull()) {
+ return 1;
+ }
+
+ // get roots
+ QCA::CertificateCollection roots;
+ if (!nosys) {
+ roots += QCA::systemStore();
+ }
+ if (!rootsFile.isEmpty()) {
+ roots += QCA::CertificateCollection::fromFlatTextFile(rootsFile);
+ }
+
+ // get nonroots
+ QCA::CertificateCollection nonroots;
+ if (!nonRootsFile.isEmpty()) {
+ nonroots = QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
+ }
+
+ QCA::Validity v = target.validate(roots, nonroots);
+ if (v == QCA::ValidityGood) {
+ printf("Certificate is valid\n");
+ } else {
+ printf("Certificate is NOT valid: %s\n", qPrintable(validityToString(v)));
+ return 1;
+ }
+ } else {
+ usage();
+ return 1;
+ }
+ } else if (args[0] == "keybundle") {
+ if (args.count() < 2) {
+ usage();
+ return 1;
+ }
+
+ if (args[1] == "make") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("pkcs12")) {
+ fprintf(stderr, "Error: need 'pkcs12' feature.\n");
+ return 1;
+ }
+
+ QCA::PrivateKey priv = get_K(args[2]);
+ if (priv.isNull()) {
+ return 1;
+ }
+
+ QCA::Certificate cert = get_C(args[3]);
+ if (cert.isNull()) {
+ return 1;
+ }
+
+ // get roots
+ QCA::CertificateCollection roots;
+ if (!nosys) {
+ roots += QCA::systemStore();
+ }
+ if (!rootsFile.isEmpty()) {
+ roots += QCA::CertificateCollection::fromFlatTextFile(rootsFile);
+ }
+
+ // get nonroots
+ QCA::CertificateCollection nonroots;
+ if (!nonRootsFile.isEmpty()) {
+ nonroots = QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
+ }
+
+ QList<QCA::Certificate> issuer_pool = roots.certificates() + nonroots.certificates();
+
+ QCA::CertificateChain chain;
+ chain += cert;
+ chain = chain.complete(issuer_pool);
+
+ QCA::KeyBundle key;
+ key.setName(chain.primary().commonName());
+ key.setCertificateChainAndKey(chain, priv);
+
+ if (!allowprompt && !have_newpass) {
+ fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
+ return 1;
+ }
+
+ // prompt for new passphrase if necessary
+ if (!have_newpass) {
+ while (!promptForNewPassphrase(&newpass)) {
+ }
+ have_newpass = true;
+ }
+
+ if (newpass.isEmpty()) {
+ fprintf(stderr, "Error: keybundles cannot have empty passphrases.\n");
+ return 1;
+ }
+
+ QString newFileName = "cert.p12";
+
+ if (key.toFile(newFileName, newpass)) {
+ printf("Keybundle saved to %s\n", qPrintable(newFileName));
+ } else {
+ fprintf(stderr, "Error: can't encode keybundle.\n");
+ return 1;
+ }
+ } else if (args[1] == "extract") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::KeyBundle key = get_X(args[2]);
+ if (key.isNull()) {
+ return 1;
+ }
+
+ QCA::PrivateKey priv = key.privateKey();
+ bool export_priv = priv.canExport();
+
+ if (export_priv) {
+ fprintf(stderr, "You will need to create a passphrase for the extracted private key.\n");
+
+ if (!allowprompt && !have_newpass) {
+ fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
+ return 1;
+ }
+
+ // prompt for new passphrase if necessary
+ if (!have_newpass) {
+ while (!promptForNewPassphrase(&newpass)) {
+ }
+ have_newpass = true;
+ }
+ }
+
+ printf("Certs: (first is primary)\n");
+ QCA::CertificateChain chain = key.certificateChain();
+ for (int n = 0; n < chain.count(); ++n) {
+ printf("%s", qPrintable(chain[n].toPEM()));
+ }
+ printf("Private Key:\n");
+ if (export_priv) {
+ QString out;
+ if (!newpass.isEmpty()) {
+ out = priv.toPEM(newpass);
+ } else {
+ out = priv.toPEM();
+ }
+ printf("%s", qPrintable(out));
+ } else {
+ printf("(Key is not exportable)\n");
+ }
+ } else if (args[1] == "changepass") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::KeyBundle key = get_X(args[2]);
+ if (key.isNull()) {
+ return 1;
+ }
+
+ if (!key.privateKey().canExport()) {
+ fprintf(stderr, "Error: private key not exportable.\n");
+ return 1;
+ }
+
+ if (!allowprompt && !have_newpass) {
+ fprintf(stderr, "Error: no passphrase specified (use '--newpass=' for none).\n");
+ return 1;
+ }
+
+ // prompt for new passphrase if necessary
+ if (!have_newpass) {
+ while (!promptForNewPassphrase(&newpass)) {
+ }
+ have_newpass = true;
+ }
+
+ if (newpass.isEmpty()) {
+ fprintf(stderr, "Error: keybundles cannot have empty passphrases.\n");
+ return 1;
+ }
+
+ QFileInfo fi(args[2]);
+ QString newFileName = fi.baseName() + "_new.p12";
+
+ if (key.toFile(newFileName, newpass)) {
+ printf("Keybundle saved to %s\n", qPrintable(newFileName));
+ } else {
+ fprintf(stderr, "Error: can't encode keybundle.\n");
+ return 1;
+ }
+ } else {
+ usage();
+ return 1;
+ }
+ } else if (args[0] == "keystore") {
+ if (args.count() < 2) {
+ usage();
+ return 1;
+ }
+
+ if (args[1] == "list-stores") {
+ ksm_start_and_wait();
+
+ QCA::KeyStoreManager ksm;
+ QStringList storeList = ksm.keyStores();
+
+ for (int n = 0; n < storeList.count(); ++n) {
+ QCA::KeyStore ks(storeList[n], &ksm);
+ QString type = kstype_to_string(ks.type());
+ printf("%s %s [%s]\n", qPrintable(type), qPrintable(idHash(ks.id())), qPrintable(ks.name()));
+ }
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ }
+ } else if (args[1] == "list") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ ksm_start_and_wait();
+
+ QCA::KeyStoreManager ksm;
+ QCA::KeyStore store(getKeyStore(args[2]), &ksm);
+ if (!store.isValid()) {
+ if (debug) {
+ output_keystore_diagnostic_text();
+ }
+
+ fprintf(stderr, "Error: no such store\n");
+ return 1;
+ }
+
+ QList<QCA::KeyStoreEntry> list = store.entryList();
+ for (int n = 0; n < list.count(); ++n) {
+ QCA::KeyStoreEntry i = list[n];
+ QString type = ksentrytype_to_string(i.type());
+ printf("%s %s [%s]\n", qPrintable(type), qPrintable(idHash(i.id())), qPrintable(i.name()));
+ }
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ }
+ } else if (args[1] == "monitor") {
+ KeyStoreMonitor::monitor();
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ }
+ } else if (args[1] == "export") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::KeyStoreEntry entry = get_E(args[2]);
+ if (entry.isNull()) {
+ return 1;
+ }
+
+ if (entry.type() == QCA::KeyStoreEntry::TypeCertificate) {
+ printf("%s", qPrintable(entry.certificate().toPEM()));
+ } else if (entry.type() == QCA::KeyStoreEntry::TypeCRL) {
+ printf("%s", qPrintable(entry.crl().toPEM()));
+ } else if (entry.type() == QCA::KeyStoreEntry::TypePGPPublicKey || entry.type() == QCA::KeyStoreEntry::TypePGPSecretKey) {
+ printf("%s", qPrintable(entry.pgpPublicKey().toString()));
+ } else if (entry.type() == QCA::KeyStoreEntry::TypeKeyBundle) {
+ fprintf(stderr, "Error: use 'keybundle extract' command instead.\n");
+ return 1;
+ } else {
+ fprintf(stderr, "Error: cannot export type '%d'.\n", entry.type());
+ return 1;
+ }
+ } else if (args[1] == "exportref") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::KeyStoreEntry entry = get_E(args[2]);
+ if (entry.isNull()) {
+ return 1;
+ }
+ printf("%s", make_ksentry_string(entry.toString()).toUtf8().data());
+ } else if (args[1] == "addkb") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ ksm_start_and_wait();
+
+ QCA::KeyStoreManager ksm;
+ QCA::KeyStore store(getKeyStore(args[2]), &ksm);
+ if (!store.isValid()) {
+ fprintf(stderr, "Error: no such store\n");
+ return 1;
+ }
+
+ QCA::KeyBundle key = get_X(args[3]);
+ if (key.isNull()) {
+ return 1;
+ }
+
+ if (!store.writeEntry(key).isEmpty()) {
+ printf("Entry written.\n");
+ } else {
+ fprintf(stderr, "Error: unable to write entry.\n");
+ return 1;
+ }
+ } else if (args[1] == "addpgp") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("openpgp")) {
+ fprintf(stderr, "Error: need 'openpgp' feature.\n");
+ return 1;
+ }
+
+ ksm_start_and_wait();
+
+ QCA::KeyStoreManager ksm;
+ QCA::KeyStore store(getKeyStore(args[2]), &ksm);
+ if (!store.isValid()) {
+ fprintf(stderr, "Error: no such store\n");
+ return 1;
+ }
+
+ QCA::PGPKey pub = QCA::PGPKey::fromFile(args[3]);
+ if (pub.isNull()) {
+ return 1;
+ }
+
+ if (!store.writeEntry(pub).isEmpty()) {
+ printf("Entry written.\n");
+ } else {
+ fprintf(stderr, "Error: unable to write entry.\n");
+ return 1;
+ }
+ } else if (args[1] == "remove") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::KeyStoreEntry entry = get_E(args[2]);
+ if (entry.isNull()) {
+ return 1;
+ }
+
+ QCA::KeyStoreManager ksm;
+ QCA::KeyStore store(entry.storeId(), &ksm);
+ if (!store.isValid()) {
+ fprintf(stderr, "Error: no such store\n");
+ return 1;
+ }
+
+ if (store.removeEntry(entry.id())) {
+ printf("Entry removed.\n");
+ } else {
+ fprintf(stderr, "Error: unable to remove entry.\n");
+ return 1;
+ }
+ } else {
+ usage();
+ return 1;
+ }
+ } else if (args[0] == "show") {
+ if (args.count() < 2) {
+ usage();
+ return 1;
+ }
+
+ if (args[1] == "cert") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::Certificate cert = get_C(args[2]);
+ if (cert.isNull()) {
+ return 1;
+ }
+
+ print_cert(cert, ordered);
+ } else if (args[1] == "req") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("csr")) {
+ fprintf(stderr, "Error: need 'csr' feature.\n");
+ return 1;
+ }
+
+ QCA::CertificateRequest req(args[2]);
+ if (req.isNull()) {
+ fprintf(stderr, "Error: can't read/process certificate request file.\n");
+ return 1;
+ }
+
+ print_certreq(req, ordered);
+ } else if (args[1] == "crl") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("crl")) {
+ fprintf(stderr, "Error: need 'crl' feature.\n");
+ return 1;
+ }
+
+ QCA::CRL crl;
+ if (is_pem_file(args[2])) {
+ crl = QCA::CRL::fromPEMFile(args[2]);
+ } else {
+ crl = QCA::CRL::fromDER(read_der_file(args[2]));
+ }
+ if (crl.isNull()) {
+ fprintf(stderr, "Error: unable to read/process CRL file.\n");
+ return 1;
+ }
+
+ print_crl(crl, ordered);
+ } else if (args[1] == "kb") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::KeyBundle key = get_X(args[2]);
+ if (key.isNull()) {
+ return 1;
+ }
+
+ printf("Keybundle contains %d certificates. Displaying primary:\n", key.certificateChain().count());
+ print_cert(key.certificateChain().primary(), ordered);
+ } else if (args[1] == "pgp") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ // try for secret key, then try public key
+ QCA::PGPKey key = get_S(args[2], true).first;
+ if (key.isNull()) {
+ key = get_P(args[2]);
+ if (key.isNull()) {
+ return 1;
+ }
+ }
+
+ print_pgp(key);
+ } else {
+ usage();
+ return 1;
+ }
+ } else if (args[0] == "message") {
+ if (args.count() < 2) {
+ usage();
+ return 1;
+ }
+
+ if (args[1] == "sign") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ QCA::SecureMessageSystem *sms;
+ QCA::SecureMessageKey skey;
+ QCA::SecureMessage::SignMode mode;
+ bool pgp = false;
+
+ if (args[2] == "pgp") {
+ if (!QCA::isSupported("openpgp")) {
+ fprintf(stderr, "Error: need 'openpgp' feature.\n");
+ return 1;
+ }
+
+ QPair<QCA::PGPKey, QCA::PGPKey> key = get_S(args[3]);
+ if (key.first.isNull()) {
+ return 1;
+ }
+
+ sms = new QCA::OpenPGP;
+ skey.setPGPSecretKey(key.first);
+ mode = QCA::SecureMessage::Clearsign;
+ pgp = true;
+ } else if (args[2] == "pgpdetach") {
+ if (!QCA::isSupported("openpgp")) {
+ fprintf(stderr, "Error: need 'openpgp' feature.\n");
+ return 1;
+ }
+
+ QPair<QCA::PGPKey, QCA::PGPKey> key = get_S(args[3]);
+ if (key.first.isNull()) {
+ return 1;
+ }
+
+ sms = new QCA::OpenPGP;
+ skey.setPGPSecretKey(key.first);
+ mode = QCA::SecureMessage::Detached;
+ pgp = true;
+ } else if (args[2] == "smime") {
+ if (!QCA::isSupported("cms")) {
+ fprintf(stderr, "Error: need 'cms' feature.\n");
+ return 1;
+ }
+
+ QCA::KeyBundle key = get_X(args[3]);
+ if (key.isNull()) {
+ return 1;
+ }
+
+ // get nonroots
+ QCA::CertificateCollection nonroots;
+ if (!nonRootsFile.isEmpty()) {
+ nonroots = QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
+ }
+
+ QList<QCA::Certificate> issuer_pool = nonroots.certificates();
+
+ QCA::CertificateChain chain = key.certificateChain();
+ chain = chain.complete(issuer_pool);
+
+ sms = new QCA::CMS;
+ skey.setX509CertificateChain(chain);
+ skey.setX509PrivateKey(key.privateKey());
+ mode = QCA::SecureMessage::Detached;
+ } else {
+ usage();
+ return 1;
+ }
+
+ // read input data from stdin all at once
+ QByteArray plain;
+ while (!feof(stdin)) {
+ QByteArray block(1024, 0);
+ int n = fread(block.data(), 1, 1024, stdin);
+ if (n < 0) {
+ break;
+ }
+ block.resize(n);
+ plain += block;
+ }
+
+ // smime envelope
+ if (!pgp) {
+ QString text = add_cr(QString::fromUtf8(plain));
+ plain = QString(mime_signpart).arg(text).toUtf8();
+ }
+
+ QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
+ msg->setSigner(skey);
+ // pgp should always be ascii
+ if (pgp) {
+ msg->setFormat(QCA::SecureMessage::Ascii);
+ }
+ msg->setBundleSignerEnabled(!nobundle);
+ msg->startSign(mode);
+ msg->update(plain);
+ msg->end();
+ msg->waitForFinished(-1);
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ output_message_diagnostic_text(msg);
+ }
+
+ if (!msg->success()) {
+ QString errstr = smErrorToString(msg->errorCode());
+ delete msg;
+ delete sms;
+
+ fprintf(stderr, "Error: unable to sign: %s\n", qPrintable(errstr));
+ return 1;
+ }
+
+ QString hashName = msg->hashName();
+
+ QByteArray output;
+ if (mode == QCA::SecureMessage::Detached) {
+ output = msg->signature();
+ } else {
+ output = msg->read();
+ }
+
+ delete msg;
+ delete sms;
+
+ // smime envelope
+ if (!pgp) {
+ QCA::Base64 enc;
+ enc.setLineBreaksEnabled(true);
+ enc.setLineBreaksColumn(76);
+ QString sigtext = add_cr(enc.arrayToString(output));
+ QString str = QString(mime_signed).arg(hashName).arg(QString::fromUtf8(plain)).arg(sigtext);
+ output = str.toUtf8();
+ }
+
+ printf("%s", output.data());
+ } else if (args[1] == "encrypt") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ QCA::SecureMessageSystem *sms;
+ QCA::SecureMessageKey skey;
+ bool pgp = false;
+
+ if (args[2] == "pgp") {
+ if (!QCA::isSupported("openpgp")) {
+ fprintf(stderr, "Error: need 'openpgp' feature.\n");
+ return 1;
+ }
+
+ QCA::PGPKey key = get_P(args[3]);
+ if (key.isNull()) {
+ return 1;
+ }
+
+ sms = new QCA::OpenPGP;
+ skey.setPGPPublicKey(key);
+ pgp = true;
+ } else if (args[2] == "smime") {
+ if (!QCA::isSupported("cms")) {
+ fprintf(stderr, "Error: need 'cms' feature.\n");
+ return 1;
+ }
+
+ QCA::Certificate cert = get_C(args[3]);
+ if (cert.isNull()) {
+ return 1;
+ }
+
+ sms = new QCA::CMS;
+ skey.setX509CertificateChain(cert);
+ } else {
+ usage();
+ return 1;
+ }
+
+ // read input data from stdin all at once
+ QByteArray plain;
+ while (!feof(stdin)) {
+ QByteArray block(1024, 0);
+ int n = fread(block.data(), 1, 1024, stdin);
+ if (n < 0) {
+ break;
+ }
+ block.resize(n);
+ plain += block;
+ }
+
+ QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
+ msg->setRecipient(skey);
+ // pgp should always be ascii
+ if (pgp) {
+ msg->setFormat(QCA::SecureMessage::Ascii);
+ }
+ msg->startEncrypt();
+ msg->update(plain);
+ msg->end();
+ msg->waitForFinished(-1);
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ output_message_diagnostic_text(msg);
+ }
+
+ if (!msg->success()) {
+ QString errstr = smErrorToString(msg->errorCode());
+ delete msg;
+ delete sms;
+ fprintf(stderr, "Error: unable to encrypt: %s\n", qPrintable(errstr));
+ return 1;
+ }
+
+ QByteArray output = msg->read();
+ delete msg;
+ delete sms;
+
+ // smime envelope
+ if (!pgp) {
+ QCA::Base64 enc;
+ enc.setLineBreaksEnabled(true);
+ enc.setLineBreaksColumn(76);
+ QString enctext = add_cr(enc.arrayToString(output));
+ QString str = QString(mime_enveloped).arg(enctext);
+ output = str.toUtf8();
+ }
+
+ printf("%s", output.data());
+ } else if (args[1] == "signencrypt") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("openpgp")) {
+ fprintf(stderr, "Error: need 'openpgp' feature.\n");
+ return 1;
+ }
+
+ QCA::SecureMessageSystem *sms;
+ QCA::SecureMessageKey skey;
+ QCA::SecureMessageKey rkey;
+
+ {
+ QPair<QCA::PGPKey, QCA::PGPKey> sec = get_S(args[2]);
+ if (sec.first.isNull()) {
+ return 1;
+ }
+
+ QCA::PGPKey pub = get_P(args[3]);
+ if (pub.isNull()) {
+ return 1;
+ }
+
+ sms = new QCA::OpenPGP;
+ skey.setPGPSecretKey(sec.first);
+ rkey.setPGPPublicKey(pub);
+ }
+
+ // read input data from stdin all at once
+ QByteArray plain;
+ while (!feof(stdin)) {
+ QByteArray block(1024, 0);
+ int n = fread(block.data(), 1, 1024, stdin);
+ if (n < 0) {
+ break;
+ }
+ block.resize(n);
+ plain += block;
+ }
+
+ QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
+ if (!msg->canSignAndEncrypt()) {
+ delete msg;
+ delete sms;
+ fprintf(stderr, "Error: cannot perform integrated sign and encrypt.\n");
+ return 1;
+ }
+
+ msg->setSigner(skey);
+ msg->setRecipient(rkey);
+ msg->setFormat(QCA::SecureMessage::Ascii);
+ msg->startSignAndEncrypt();
+ msg->update(plain);
+ msg->end();
+ msg->waitForFinished(-1);
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ output_message_diagnostic_text(msg);
+ }
+
+ if (!msg->success()) {
+ QString errstr = smErrorToString(msg->errorCode());
+ delete msg;
+ delete sms;
+ fprintf(stderr, "Error: unable to sign and encrypt: %s\n", qPrintable(errstr));
+ return 1;
+ }
+
+ QByteArray output = msg->read();
+ delete msg;
+ delete sms;
+
+ printf("%s", output.data());
+ } else if (args[1] == "verify") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::SecureMessageSystem *sms;
+ bool pgp = false;
+
+ if (args[2] == "pgp") {
+ if (!QCA::isSupported("openpgp")) {
+ fprintf(stderr, "Error: need 'openpgp' feature.\n");
+ return 1;
+ }
+
+ sms = new QCA::OpenPGP;
+ pgp = true;
+ } else if (args[2] == "smime") {
+ if (!QCA::isSupported("cms")) {
+ fprintf(stderr, "Error: need 'cms' feature.\n");
+ return 1;
+ }
+
+ // get roots
+ QCA::CertificateCollection roots;
+ if (!nosys) {
+ roots += QCA::systemStore();
+ }
+ if (!rootsFile.isEmpty()) {
+ roots += QCA::CertificateCollection::fromFlatTextFile(rootsFile);
+ }
+
+ // get intermediates and possible signers, in case
+ // the message does not have them.
+ QCA::CertificateCollection nonroots;
+ if (!nonRootsFile.isEmpty()) {
+ nonroots += QCA::CertificateCollection::fromFlatTextFile(nonRootsFile);
+ }
+
+ sms = new QCA::CMS;
+ ((QCA::CMS *)sms)->setTrustedCertificates(roots);
+ ((QCA::CMS *)sms)->setUntrustedCertificates(nonroots);
+ } else {
+ usage();
+ return 1;
+ }
+
+ QByteArray data, sig;
+ QString smime_text;
+ {
+ // read input data from stdin all at once
+ QByteArray plain;
+ while (!feof(stdin)) {
+ QByteArray block(1024, 0);
+ int n = fread(block.data(), 1, 1024, stdin);
+ if (n < 0) {
+ break;
+ }
+ block.resize(n);
+ plain += block;
+ }
+
+ if (pgp) {
+ // pgp can be either a detached signature followed
+ // by data, or an integrated message.
+
+ // detached signature?
+ if (plain.startsWith("-----BEGIN PGP SIGNATURE-----")) {
+ QString footer = "-----END PGP SIGNATURE-----\n";
+ int n = plain.indexOf(footer);
+ if (n == -1) {
+ delete sms;
+ fprintf(stderr, "Error: pgp signature header, but no footer.\n");
+ return 1;
+ }
+
+ n += footer.length();
+ sig = plain.mid(0, n);
+ data = plain.mid(n);
+ } else {
+ data = plain;
+ }
+ } else {
+ // smime envelope
+ QString in = QString::fromUtf8(plain);
+ in = add_cr(in); // change the line endings?!
+ QString str, sigtext;
+ if (!open_mime_data_sig(in, &str, &sigtext)) {
+ fprintf(stderr, "Error: can't parse message file.\n");
+ return 1;
+ }
+
+ data = str.toUtf8();
+ smime_text = str;
+
+ QCA::Base64 dec;
+ dec.setLineBreaksEnabled(true);
+ sig = dec.stringToArray(rem_cr(sigtext)).toByteArray();
+ }
+ }
+
+ QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
+ if (pgp) {
+ msg->setFormat(QCA::SecureMessage::Ascii);
+ }
+ msg->startVerify(sig);
+ msg->update(data);
+ msg->end();
+ msg->waitForFinished(-1);
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ output_message_diagnostic_text(msg);
+ }
+
+ if (!msg->success()) {
+ QString errstr = smErrorToString(msg->errorCode());
+ delete msg;
+ delete sms;
+ fprintf(stderr, "Error: verify failed: %s\n", qPrintable(errstr));
+ return 1;
+ }
+
+ QByteArray output;
+ if (pgp && sig.isEmpty()) {
+ output = msg->read();
+ }
+
+ QList<QCA::SecureMessageSignature> signers = msg->signers();
+ delete msg;
+ delete sms;
+
+ // for pgp clearsign, pgp signed (non-detached), and smime,
+ // the signed content was inside of the message. we need
+ // to print that content now
+ if (pgp) {
+ printf("%s", output.data());
+ } else {
+ QString str = open_mime_envelope(smime_text);
+ printf("%s", str.toUtf8().data());
+ }
+
+ smDisplaySignatures(signers);
+
+ bool allgood = true;
+ foreach (const QCA::SecureMessageSignature &signer, signers) {
+ if (signer.identityResult() != QCA::SecureMessageSignature::Valid) {
+ allgood = false;
+ break;
+ }
+ }
+
+ if (!allgood) {
+ return 1;
+ }
+ } else if (args[1] == "decrypt") {
+ if (args.count() < 3) {
+ usage();
+ return 1;
+ }
+
+ QCA::SecureMessageSystem *sms;
+ bool pgp = false;
+
+ if (args[2] == "pgp") {
+ if (!QCA::isSupported("openpgp")) {
+ fprintf(stderr, "Error: need 'openpgp' feature.\n");
+ return 1;
+ }
+
+ sms = new QCA::OpenPGP;
+ pgp = true;
+ } else if (args[2] == "smime") {
+ if (args.count() < 4) {
+ usage();
+ return 1;
+ }
+
+ if (!QCA::isSupported("cms")) {
+ fprintf(stderr, "Error: need 'cms' feature.\n");
+ return 1;
+ }
+
+ // user can provide many possible decrypt keys
+ QList<QCA::KeyBundle> keys;
+ for (int n = 3; n < args.count(); ++n) {
+ QCA::KeyBundle key = get_X(args[n]);
+ if (key.isNull()) {
+ return 1;
+ }
+ keys += key;
+ }
+
+ sms = new QCA::CMS;
+
+ QList<QCA::SecureMessageKey> skeys;
+ foreach (const QCA::KeyBundle &key, keys) {
+ QCA::SecureMessageKey skey;
+ skey.setX509CertificateChain(key.certificateChain());
+ skey.setX509PrivateKey(key.privateKey());
+ skeys += skey;
+ }
+
+ ((QCA::CMS *)sms)->setPrivateKeys(skeys);
+ } else {
+ usage();
+ return 1;
+ }
+
+ // read input data from stdin all at once
+ QByteArray plain;
+ while (!feof(stdin)) {
+ QByteArray block(1024, 0);
+ int n = fread(block.data(), 1, 1024, stdin);
+ if (n < 0) {
+ break;
+ }
+ block.resize(n);
+ plain += block;
+ }
+
+ // smime envelope
+ if (!pgp) {
+ QString in = QString::fromUtf8(plain);
+ QString str = open_mime_envelope(in);
+ if (str.isEmpty()) {
+ delete sms;
+ fprintf(stderr, "Error: can't parse message file.\n");
+ return 1;
+ }
+
+ QCA::Base64 dec;
+ dec.setLineBreaksEnabled(true);
+ plain = dec.stringToArray(rem_cr(str)).toByteArray();
+ }
+
+ QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
+ if (pgp) {
+ msg->setFormat(QCA::SecureMessage::Ascii);
+ }
+ msg->startDecrypt();
+ msg->update(plain);
+ msg->end();
+ msg->waitForFinished(-1);
+
+ if (debug) {
+ output_keystore_diagnostic_text();
+ output_message_diagnostic_text(msg);
+ }
+
+ if (!msg->success()) {
+ QString errstr = smErrorToString(msg->errorCode());
+ delete msg;
+ delete sms;
+ fprintf(stderr, "Error: decrypt failed: %s\n", qPrintable(errstr));
+ return 1;
+ }
+
+ QByteArray output = msg->read();
+
+ QList<QCA::SecureMessageSignature> signers;
+ bool wasSigned = false;
+ if (msg->wasSigned()) {
+ signers = msg->signers();
+ wasSigned = true;
+ }
+ delete msg;
+ delete sms;
+
+ printf("%s", output.data());
+
+ if (wasSigned) {
+ fprintf(stderr, "Message was also signed:\n");
+
+ smDisplaySignatures(signers);
+
+ bool allgood = true;
+ foreach (const QCA::SecureMessageSignature &signer, signers) {
+ if (signer.identityResult() != QCA::SecureMessageSignature::Valid) {
+ allgood = false;
+ break;
+ }
+ }
+
+ if (!allgood) {
+ return 1;
+ }
+ }
+ } else if (args[1] == "exportcerts") {
+ if (!QCA::isSupported("cms")) {
+ fprintf(stderr, "Error: need 'cms' feature.\n");
+ return 1;
+ }
+
+ QCA::SecureMessageSystem *sms = new QCA::CMS;
+
+ QByteArray data, sig;
+ QString smime_text;
+ {
+ // read input data from stdin all at once
+ QByteArray plain;
+ while (!feof(stdin)) {
+ QByteArray block(1024, 0);
+ int n = fread(block.data(), 1, 1024, stdin);
+ if (n < 0) {
+ break;
+ }
+ block.resize(n);
+ plain += block;
+ }
+
+ // smime envelope
+ QString in = QString::fromUtf8(plain);
+ QString str, sigtext;
+ if (!open_mime_data_sig(in, &str, &sigtext)) {
+ delete sms;
+ fprintf(stderr, "Error: can't parse message file.\n");
+ return 1;
+ }
+
+ data = str.toUtf8();
+ smime_text = str;
+
+ QCA::Base64 dec;
+ dec.setLineBreaksEnabled(true);
+ sig = dec.stringToArray(rem_cr(sigtext)).toByteArray();
+ }
+
+ QCA::SecureMessage *msg = new QCA::SecureMessage(sms);
+ msg->startVerify(sig);
+ msg->update(data);
+ msg->end();
+ msg->waitForFinished(-1);
+
+ if (debug) {
+ output_message_diagnostic_text(msg);
+ }
+
+ if (!msg->success()) {
+ QString errstr = smErrorToString(msg->errorCode());
+ delete msg;
+ delete sms;
+ fprintf(stderr, "Error: export failed: %s\n", qPrintable(errstr));
+ return 1;
+ }
+
+ QList<QCA::SecureMessageSignature> signers = msg->signers();
+ delete msg;
+ delete sms;
+
+ // print out all certs of all signers
+ foreach (const QCA::SecureMessageSignature &signer, signers) {
+ QCA::SecureMessageKey key = signer.key();
+ if (!key.isNull()) {
+ foreach (const QCA::Certificate &c, key.x509CertificateChain()) {
+ printf("%s", qPrintable(c.toPEM()));
+ }
+ }
+ }
+ } else {
+ usage();
+ return 1;
+ }
+ } else {
+ usage();
+ return 1;
+ }
+
+ return 0;
}
#include "main.moc"
diff --git a/unittest/base64unittest/base64unittest.cpp b/unittest/base64unittest/base64unittest.cpp
index b354aead..2c890731 100644
--- a/unittest/base64unittest/base64unittest.cpp
+++ b/unittest/base64unittest/base64unittest.cpp
@@ -1,130 +1,129 @@
/**
* base64unittest.cpp
*
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class Base64UnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void test1_data();
void test1();
void test2_data();
void test2();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void Base64UnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void Base64UnitTest::cleanupTestCase()
{
delete m_init;
}
void Base64UnitTest::test1_data()
{
QTest::addColumn<QString>("raw");
QTest::addColumn<QString>("encoded");
// these are from the Botan test suite. Note that these are hex encoded!
QTest::newRow("31") << QString("31") << QString("4d513d3d");
QTest::newRow("235c91") << QString("235c91") << QString("49317952");
QTest::newRow("414") << QString("4142634452313236")
- << QString("51554a6a524649784d6a593d");
+ << QString("51554a6a524649784d6a593d");
QTest::newRow("241") << QString("241bb300a3989a620659")
- << QString("4a42757a414b4f596d6d494757513d3d");
+ << QString("4a42757a414b4f596d6d494757513d3d");
QTest::newRow("313") << QString("31323537374343666671333435337836")
- << QString("4d5449314e7a644451325a6d63544d304e544e344e673d3d");
+ << QString("4d5449314e7a644451325a6d63544d304e544e344e673d3d");
QTest::newRow("60e") << QString("60e8e5ebb1a5eac95a01ec7f8796b2dce471")
- << QString("594f6a6c3637476c36736c614165782f68356179334f5278");
+ << QString("594f6a6c3637476c36736c614165782f68356179334f5278");
QTest::newRow("3134") << QString("31346d354f33313333372c31274d754e7354307050346231333a29")
- << QString("4d5452744e55387a4d544d7a4e7977784a303131546e4e554d4842514e4749784d7a6f70");
+ << QString("4d5452744e55387a4d544d7a4e7977784a303131546e4e554d4842514e4749784d7a6f70");
}
-
void Base64UnitTest::test2_data()
{
QTest::addColumn<QString>("raw");
QTest::addColumn<QString>("encoded");
// these are from Python 2.3's tests for base64
QTest::newRow("www.python.org") << QString("www.python.org")
- << QString("d3d3LnB5dGhvbi5vcmc=");
+ << QString("d3d3LnB5dGhvbi5vcmc=");
QTest::newRow("a") << QString("a") << QString("YQ==");
QTest::newRow("ab") << QString("ab") << QString("YWI=");
QTest::newRow("abc") << QString("abc") << QString("YWJj");
QTest::newRow("empty") << QString("") << QString("");
QTest::newRow("a-Z") << QString("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#0^&*();:<>,. []{}")
- << QString("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NTY3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==");
+ << QString("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NTY3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==");
// these are generated by Python 2.3. I removed the trailing newline
QTest::newRow("31") << QString("31") << QString("MzE=");
QTest::newRow("QCA_2.0") << QString("QCA_2.0") << QString("UUNBXzIuMA==");
QTest::newRow("j-0") << QString("jh/*-*/*-/4983589230")
- << QString("amgvKi0qLyotLzQ5ODM1ODkyMzA=");
+ << QString("amgvKi0qLyotLzQ5ODM1ODkyMzA=");
}
void Base64UnitTest::test1()
{
QCA::Base64 base64Object;
QFETCH(QString, raw);
QFETCH(QString, encoded);
QCOMPARE(QCA::arrayToHex(base64Object.encode(QCA::hexToArray(raw)).toByteArray()), encoded);
QCOMPARE(QCA::arrayToHex(base64Object.decode(QCA::hexToArray(encoded)).toByteArray()), raw);
}
void Base64UnitTest::test2()
{
QCA::Base64 base64Object;
QFETCH(QString, raw);
QFETCH(QString, encoded);
- QCOMPARE( base64Object.encodeString(raw), encoded );
- QCOMPARE( base64Object.decodeString(encoded), raw );
+ QCOMPARE(base64Object.encodeString(raw), encoded);
+ QCOMPARE(base64Object.decodeString(encoded), raw);
- QCOMPARE( QCA::arrayToBase64(raw.toUtf8()), encoded );
- QCOMPARE( QLatin1String(QCA::base64ToArray(encoded)), raw );
+ QCOMPARE(QCA::arrayToBase64(raw.toUtf8()), encoded);
+ QCOMPARE(QLatin1String(QCA::base64ToArray(encoded)), raw);
}
QTEST_MAIN(Base64UnitTest)
#include "base64unittest.moc"
diff --git a/unittest/bigintunittest/bigintunittest.cpp b/unittest/bigintunittest/bigintunittest.cpp
index fc6c14b3..2e98e46a 100644
--- a/unittest/bigintunittest/bigintunittest.cpp
+++ b/unittest/bigintunittest/bigintunittest.cpp
@@ -1,688 +1,684 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class BigIntUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void allTests();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void BigIntUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void BigIntUnitTest::cleanupTestCase()
{
delete m_init;
}
void BigIntUnitTest::allTests()
{
QCA::BigInteger result;
// Some string conversion tests
- QCOMPARE( QCA::BigInteger("255").toString(), QCA::BigInteger(255).toString() );
- QCOMPARE( QCA::BigInteger("-255").toString(), QCA::BigInteger(-255).toString() );
- QCOMPARE( QCA::BigInteger("255").toString(), QString("255") );
- QCOMPARE( QCA::BigInteger("-255").toString(), QString("-255") );
+ QCOMPARE(QCA::BigInteger("255").toString(), QCA::BigInteger(255).toString());
+ QCOMPARE(QCA::BigInteger("-255").toString(), QCA::BigInteger(-255).toString());
+ QCOMPARE(QCA::BigInteger("255").toString(), QString("255"));
+ QCOMPARE(QCA::BigInteger("-255").toString(), QString("-255"));
// Some operator tests
- QCOMPARE( QCA::BigInteger("255") == QCA::BigInteger(255), true );
- QCOMPARE( QCA::BigInteger("-255") == QCA::BigInteger(-255), true );
- QCOMPARE( QCA::BigInteger("256") != QCA::BigInteger(255), true );
- QCOMPARE( QCA::BigInteger("-256") != QCA::BigInteger(-255), true );
+ QCOMPARE(QCA::BigInteger("255") == QCA::BigInteger(255), true);
+ QCOMPARE(QCA::BigInteger("-255") == QCA::BigInteger(-255), true);
+ QCOMPARE(QCA::BigInteger("256") != QCA::BigInteger(255), true);
+ QCOMPARE(QCA::BigInteger("-256") != QCA::BigInteger(-255), true);
// Some comparison tests
- QCA::BigInteger a( "4000000000000" );
- QCA::BigInteger b( "-4000000000000" );
- QCA::BigInteger c( "2000000000000" );
- QCOMPARE( a < b, false );
- QCOMPARE( a <= b, false );
- QCOMPARE( a.compare(b), 1 );
- QCOMPARE( a > b, true );
- QCOMPARE( a >= b, true );
- QCOMPARE( a > c, true );
- QCOMPARE( c.compare(b), 1 );
- QCOMPARE( c.compare(a), -1 );
+ QCA::BigInteger a("4000000000000");
+ QCA::BigInteger b("-4000000000000");
+ QCA::BigInteger c("2000000000000");
+ QCOMPARE(a < b, false);
+ QCOMPARE(a <= b, false);
+ QCOMPARE(a.compare(b), 1);
+ QCOMPARE(a > b, true);
+ QCOMPARE(a >= b, true);
+ QCOMPARE(a > c, true);
+ QCOMPARE(c.compare(b), 1);
+ QCOMPARE(c.compare(a), -1);
// Check if the stream operator is any good
QString testString;
- QTextStream ts( &testString, QIODevice::WriteOnly);
+ QTextStream ts(&testString, QIODevice::WriteOnly);
ts << a << b << c << endl;
- QCOMPARE( testString, QString( "4000000000000-40000000000002000000000000\n") );
+ QCOMPARE(testString, QString("4000000000000-40000000000002000000000000\n"));
// Botan's addition tests
- QCOMPARE( QCA::BigInteger( 255 ) += QCA::BigInteger ( 1 ), QCA::BigInteger( 256 ) );
- result = QCA::BigInteger( 255 ) += QCA::BigInteger( 1 );
- QCOMPARE( result.toString(), QCA::BigInteger( 256 ).toString() );
+ QCOMPARE(QCA::BigInteger(255) += QCA::BigInteger(1), QCA::BigInteger(256));
+ result = QCA::BigInteger(255) += QCA::BigInteger(1);
+ QCOMPARE(result.toString(), QCA::BigInteger(256).toString());
- result = QCA::BigInteger( "65535" ) += QCA::BigInteger( "1" );
- QCOMPARE( result.toString(), QString( "65536" ) );
- QCOMPARE( result, QCA::BigInteger( "65536") );
+ result = QCA::BigInteger("65535") += QCA::BigInteger("1");
+ QCOMPARE(result.toString(), QString("65536"));
+ QCOMPARE(result, QCA::BigInteger("65536"));
- result = QCA::BigInteger( "4294967295" ) += QCA::BigInteger( 1 );
- QCOMPARE( result.toString(), QString( "4294967296" ) );
- QCOMPARE( result, QCA::BigInteger( "4294967296" ) );
+ result = QCA::BigInteger("4294967295") += QCA::BigInteger(1);
+ QCOMPARE(result.toString(), QString("4294967296"));
+ QCOMPARE(result, QCA::BigInteger("4294967296"));
- result = QCA::BigInteger( "18446744073709551615" ) += QCA::BigInteger( 1 );
- QCOMPARE( result.toString(), QString( "18446744073709551616" ) );
- QCOMPARE( result, QCA::BigInteger( "18446744073709551616" ) );
+ result = QCA::BigInteger("18446744073709551615") += QCA::BigInteger(1);
+ QCOMPARE(result.toString(), QString("18446744073709551616"));
+ QCOMPARE(result, QCA::BigInteger("18446744073709551616"));
- result = QCA::BigInteger( "124536363637272472" ) += QCA::BigInteger( "124536363637272472" );
- QCOMPARE( result.toString(), QString ( "249072727274544944" ) );
- QCOMPARE( result, QCA::BigInteger ( "249072727274544944" ) );
+ result = QCA::BigInteger("124536363637272472") += QCA::BigInteger("124536363637272472");
+ QCOMPARE(result.toString(), QString("249072727274544944"));
+ QCOMPARE(result, QCA::BigInteger("249072727274544944"));
- result = QCA::BigInteger( "9223372036854775807" ) += QCA::BigInteger( "281474976710655" );
- QCOMPARE( result.toString(), QString ( "9223653511831486462" ) );
- QCOMPARE( result, QCA::BigInteger ( "9223653511831486462" ) );
-
- result = QCA::BigInteger( "9223372036854775807" ) += QCA::BigInteger( "137438953471" );
- QCOMPARE( result.toString(), QString( "9223372174293729278" ) );
- QCOMPARE( result, QCA::BigInteger( "9223372174293729278" ) );
+ result = QCA::BigInteger("9223372036854775807") += QCA::BigInteger("281474976710655");
+ QCOMPARE(result.toString(), QString("9223653511831486462"));
+ QCOMPARE(result, QCA::BigInteger("9223653511831486462"));
+ result = QCA::BigInteger("9223372036854775807") += QCA::BigInteger("137438953471");
+ QCOMPARE(result.toString(), QString("9223372174293729278"));
+ QCOMPARE(result, QCA::BigInteger("9223372174293729278"));
// Botan's carry tests
- result = QCA::BigInteger( "340282366920938463463374607431768211455" )
- += QCA::BigInteger( "340282366920938463463374607431768211455" );
- QCOMPARE( result.toString(), QString( "680564733841876926926749214863536422910" ) );
- QCOMPARE( result, QCA::BigInteger( "680564733841876926926749214863536422910" ) );
-
- result = QCA::BigInteger( "340282366920938463463374607431768211455" )
- += QCA::BigInteger( "340282366920938463463374607431768211450" );
- QCOMPARE( result.toString(), QString( "680564733841876926926749214863536422905" ) );
- QCOMPARE( result, QCA::BigInteger( "680564733841876926926749214863536422905" ) );
-
- result = QCA::BigInteger( "115792089237316195423570985008687907853269984665640564039457584007913129639935" )
- += QCA::BigInteger( "115792089237316195423570985008687907853269984665640564039457584007913129639935" );
- QCOMPARE( result.toString(), QString( "231584178474632390847141970017375815706539969331281128078915168015826259279870" ) );
- QCOMPARE( result, QCA::BigInteger( "231584178474632390847141970017375815706539969331281128078915168015826259279870" ) );
-
- result = QCA::BigInteger( "115792089237316195423570985008687907853269984665640564039457584007913129639935" )
- += QCA::BigInteger( "115792089237316195423570985008687907853269984665640564039457584007913129639919" );
- QCOMPARE( result.toString(), QString( "231584178474632390847141970017375815706539969331281128078915168015826259279854") );
- QCOMPARE( result, QCA::BigInteger( "231584178474632390847141970017375815706539969331281128078915168015826259279854") );
-
- result = QCA::BigInteger( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095" )
- += QCA::BigInteger( "18446744073709551616" );
- QCOMPARE( result.toString(), QString( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946588393177722715635711" ) );
- QCOMPARE( result, QCA::BigInteger( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946588393177722715635711" ) );
-
-
- result = QCA::BigInteger( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095" )
- += QCA::BigInteger( "1" );
- QCOMPARE( result.toString(), QString( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096" ) );
- QCOMPARE( result, QCA::BigInteger( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096" ) );
-
- result = QCA::BigInteger( "-39794270013919406610834826960427146769766189764838473416502965291920535601112688579198627475284777498059330306128763345008528325994574657552726381901" )
- += QCA::BigInteger( "-342238655038" );
- QCOMPARE( result.toString(), QString( "-39794270013919406610834826960427146769766189764838473416502965291920535601112688579198627475284777498059330306128763345008528325994574657894965036939" ) );
- QCOMPARE( result, QCA::BigInteger( "-39794270013919406610834826960427146769766189764838473416502965291920535601112688579198627475284777498059330306128763345008528325994574657894965036939" ) );
-
- result = QCA::BigInteger( "25110291853498940831251897922987678157346336093292373576945426289097725034326735312448621015537884914" )
- += QCA::BigInteger( "-36551081154398645734533965739979697527373251608055056627686956281114038842935173436543461" );
- QCOMPARE( result.toString(), QString( "25110291853462389750097499277253144191606356395765000325337371232470038078045621273605685842101341453") );
- QCOMPARE( result, QCA::BigInteger( "25110291853462389750097499277253144191606356395765000325337371232470038078045621273605685842101341453") );
-
- result = QCA::BigInteger( "27802650352" )
- += QCA::BigInteger( "660736146705288303126411072388564329913778942" );
- QCOMPARE( result.toString(), QString( "660736146705288303126411072388564357716429294" ) );
- QCOMPARE( result, QCA::BigInteger( "660736146705288303126411072388564357716429294" ) );
-
- result = QCA::BigInteger( "-1348245899955041864800954463709881466231496038216683608715424566397833766910915722793041224478985289" )
- += QCA::BigInteger( "11517149522866182358565152643595266257020228597058539113114732218008332987904361457299261161227276764386173666571334749062651694592291882972" );
- QCOMPARE( result.toString(), QString( "11517149522866182358565152643595266257018880351158584071249931263544623106438129961261044477618561339819775832804423833339858653367812897683" ) );
- QCOMPARE( result, QCA::BigInteger( "11517149522866182358565152643595266257018880351158584071249931263544623106438129961261044477618561339819775832804423833339858653367812897683" ) );
-
- result = QCA::BigInteger( "-17540530441681616962868251635133601915039026254996886583618243914226325157426408929602625346567256761818" )
- += QCA::BigInteger( "865200427983527245206901810160356641402419461642082623179544681519016990" );
- QCOMPARE( result.toString(), QString( "-17540530441681616962868251635132736714611042727751679681808083557584922737964766846979445801885737744828" ) );
- QCOMPARE( result, QCA::BigInteger( "-17540530441681616962868251635132736714611042727751679681808083557584922737964766846979445801885737744828" ) );
-
- result = QCA::BigInteger( "128844776074298261556398714096948603458177018275051329218555498374" )
- += QCA::BigInteger( "443816313829150876362052235134610603220548928107697961229953611873695276391917150913346479060246759720475193648" );
- QCOMPARE( result.toString(), QString( "443816313829150876362052235134610603220548928236542737304251873430093990488865754371523497335298088939030692022" ) );
- QCOMPARE( result, QCA::BigInteger( "443816313829150876362052235134610603220548928236542737304251873430093990488865754371523497335298088939030692022" ) );
-
- result = QCA::BigInteger( "1709484189262457846620911889502097055085989595277300243221975568275935717696463" )
- += QCA::BigInteger( "-1646592344139809206374540620411514484579951199941360" );
- QCOMPARE( result.toString(), QString( "1709484189262457846620911887855504710946180388902759622810461083695984517755103" ) );
- QCOMPARE( result, QCA::BigInteger( "1709484189262457846620911887855504710946180388902759622810461083695984517755103" ) );
-
- result = QCA::BigInteger( "320175865429637176165709341576187102540180627806418015204928771170233538951323952509055929139673223273528062883083030595199153877335714942842" )
- += QCA::BigInteger( "-2828241696960736089879965882386687935938570856545481227619497640844399275054327390050478930503975773972" );
- QCOMPARE( result.toString(), QString( "320175865429637176165709341576187102537352386109457279115048805287846851015385381652510447912053725632683663608028703205148674946831739168870" ) );
- QCOMPARE( result, QCA::BigInteger( "320175865429637176165709341576187102537352386109457279115048805287846851015385381652510447912053725632683663608028703205148674946831739168870" ) );
-
- result = QCA::BigInteger( "-4035398360542181725908295312107496142105415014744259439963377204111754181625695349185753326709217" )
- += QCA::BigInteger( "85450213703789913646546187382091037800" );
- QCOMPARE( result.toString(), QString( "-4035398360542181725908295312107496142105415014744259439963291753898050391712048802998371235671417" ) );
- QCOMPARE( result, QCA::BigInteger( "-4035398360542181725908295312107496142105415014744259439963291753898050391712048802998371235671417" ) );
-
- result = QCA::BigInteger( "-1292166446073479876801522363382357887431657639184151284775525387363973852756087726243671676713861533673009088319851" )
- += QCA::BigInteger( "804538895874518175537499425282375058236245531798590350403343841766955572070643267141945695624895109330242749935754739434394691714971" );
- QCOMPARE( result.toString(), QString( "804538895874518174245332979208895181434723168416232462971686202582804287295117879777971842868807383086571073221893205761385603395120" ) );
- QCOMPARE( result, QCA::BigInteger( "804538895874518174245332979208895181434723168416232462971686202582804287295117879777971842868807383086571073221893205761385603395120" ) );
-
- result = QCA::BigInteger( "-451986588700926309459451756852005697379481014956007968529234251884946522682901215022086432597024324062240835564200177389" )
- += QCA::BigInteger( "15762983479" );
- QCOMPARE( result.toString(), QString( "-451986588700926309459451756852005697379481014956007968529234251884946522682901215022086432597024324062240835548437193910" ) );
- QCOMPARE( result, QCA::BigInteger( "-451986588700926309459451756852005697379481014956007968529234251884946522682901215022086432597024324062240835548437193910" ) );
-
- result = QCA::BigInteger( "-3907475412115728816974567022055278374116794025624287474334038831885743634200801846649105209920908153587891040882946582394429615396962188674594744360388466" )
- += QCA::BigInteger( "193893611236537854694879677478106237157079207398283117392998175454362643521031390" );
- QCOMPARE( result.toString(), QString( "-3907475412115728816974567022055278374116794025624287474334038831885743634006908235412567355226028476109784803725867374996146498003964013220232100839357076" ) );
- QCOMPARE( result, QCA::BigInteger( "-3907475412115728816974567022055278374116794025624287474334038831885743634006908235412567355226028476109784803725867374996146498003964013220232100839357076" ) );
-
-
- result = QCA::BigInteger( "-72603710637966201224690926289" )
- += QCA::BigInteger( "-13618442642298533261581255034923612640512507150728017106768861506299813289801666559564532" );
- QCOMPARE( result.toString(), QString( "-13618442642298533261581255034923612640512507150728017106768934110010451256002891250490821" ) );
- QCOMPARE( result, QCA::BigInteger( "-13618442642298533261581255034923612640512507150728017106768934110010451256002891250490821" ) );
-
- result = QCA::BigInteger( "56077960835713056831402948406790747107889446769357509759472207603483968107693997028111823994257399379783658853302692762256851623103019589392739" )
- += QCA::BigInteger( "-427057313888431079237360487703561848638868677065083968842" );
- QCOMPARE( result.toString(), QString( "56077960835713056831402948406790747107889446769357509759472207603483968107693997028111396936943510948704421492814989200408212754425954505423897" ) );
- QCOMPARE( result, QCA::BigInteger( "56077960835713056831402948406790747107889446769357509759472207603483968107693997028111396936943510948704421492814989200408212754425954505423897" ) );
-
- result = QCA::BigInteger( "-2209800838508504443494783762534800337712101405156784708782197580824527899758308" )
- += QCA::BigInteger( "42844076503039495864500213925837598507817708418354152774112078596443089606598570396235816327987463393971710495985285591895096794994387176281079" );
- QCOMPARE( result.toString(), QString( "42844076503039495864500213925837598507817708418354152774112078594233288768090065952741032565452663056259609090828500883112899214169859276522771" ) );
- QCOMPARE( result, QCA::BigInteger( "42844076503039495864500213925837598507817708418354152774112078594233288768090065952741032565452663056259609090828500883112899214169859276522771" ) );
-
- result = QCA::BigInteger( "33887767308809826842417841176152232321272231788338404526859019370507113927387984766381329515371768224976188337692" )
- += QCA::BigInteger( "349484339542971517481628970179002500341" );
- QCOMPARE( result.toString(), QString( "33887767308809826842417841176152232321272231788338404526859019370507113927737469105924301032853397195155190838033" ) );
- QCOMPARE( result, QCA::BigInteger( "33887767308809826842417841176152232321272231788338404526859019370507113927737469105924301032853397195155190838033" ) );
-
- result = QCA::BigInteger( "85748089639858660722587321621536298082690707526412426951630101551228144063151688592419555048867068162" )
- += QCA::BigInteger( "-383634567691961960211191292397062452265352651123492760493087381707279" );
- QCOMPARE( result.toString(), QString( "85748089639858660722587321621535914448123015564452215760337704488775878710500565099659061961485360883" ) );
- QCOMPARE( result, QCA::BigInteger( "85748089639858660722587321621535914448123015564452215760337704488775878710500565099659061961485360883" ) );
-
- result = QCA::BigInteger( "23889807888563742283608049816129153552608399262924421832404872043475" )
- += QCA::BigInteger( "995" );
- QCOMPARE( result.toString(), QString( "23889807888563742283608049816129153552608399262924421832404872044470" ) );
- QCOMPARE( result, QCA::BigInteger( "23889807888563742283608049816129153552608399262924421832404872044470" ) );
-
- result = QCA::BigInteger( "-654786925833474864669230962582694222611472680701859262466465606239654996048306783957549697781271829257774329538985" )
- += QCA::BigInteger( "-276137507159648540503039013089014674747" );
- QCOMPARE( result.toString(), QString( "-654786925833474864669230962582694222611472680701859262466465606239654996048582921464709346321774868270863344213732" ) );
- QCOMPARE( result, QCA::BigInteger( "-654786925833474864669230962582694222611472680701859262466465606239654996048582921464709346321774868270863344213732" ) );
-
- result = QCA::BigInteger( "50463316268089933" )
- += QCA::BigInteger( "-140591583463431806921000349498135287589005423318927850947894242995310138569473157521312413652439234324419130527702899917161307657443381774866237429" );
- QCOMPARE( result.toString(), QString( "-140591583463431806921000349498135287589005423318927850947894242995310138569473157521312413652439234324419130527702899917161307657392918458598147496" ) );
- QCOMPARE( result, QCA::BigInteger( "-140591583463431806921000349498135287589005423318927850947894242995310138569473157521312413652439234324419130527702899917161307657392918458598147496" ) );
-
- result = QCA::BigInteger( "1339015021665554488163337105187026760232395594198925052890859936\
-418304234254229440059229155546157793544192" )
- += QCA::BigInteger( "6294037420283433712414743361937677483761554699961644450461297486224793278823004487175687771163597590566132592591599249970281125781761944353272" );
- QCOMPARE( result.toString(), QString( "6294037420283433712414743361937677485100569721627198938624634591411820039055400081374612824054457526984436826845828690029510281327919737897464" ) );
- QCOMPARE( result, QCA::BigInteger( "6294037420283433712414743361937677485100569721627198938624634591411820039055400081374612824054457526984436826845828690029510281327919737897464" ) );
-
- result = QCA::BigInteger( "-241446683" )
- += QCA::BigInteger( "-282671163032866994488211995758272717472259277760825940523445628\
-442206062910449311538519756165635175664610569214430918184214" );
- QCOMPARE( result.toString(), QString( "-282671163032866994488211995758272717472259277760825940523445628442206062910449311538519756165635175664610569214431159630897" ) );
- QCOMPARE( result, QCA::BigInteger( "-282671163032866994488211995758272717472259277760825940523445628442206062910449311538519756165635175664610569214431159630897" ) );
-
- result = QCA::BigInteger( "2358605503303452637996081421902056515951744611718383128442445119505739707550326378912342448355046239066896995563581" )
- += QCA::BigInteger( "-3830437229145325165273364525551261440648845791949681661260946956860463720730123941973615" );
- QCOMPARE( result.toString(), QString( "2358605503303452637996081418071619286806419446445018602891183678856893915600644717651395491494582518336773053589966" ) );
- QCOMPARE( result, QCA::BigInteger( "2358605503303452637996081418071619286806419446445018602891183678856893915600644717651395491494582518336773053589966" ) );
-
- result = QCA::BigInteger( "1860794367587960058388097846258490" )
- += QCA::BigInteger( "-237344494507203983863096991896035366478949095337787603280" );
- QCOMPARE( result.toString(), QString( "-237344494507203983863095131101667778518890707239941344790" ) );
- QCOMPARE( result, QCA::BigInteger( "-237344494507203983863095131101667778518890707239941344790" ) );
-
- result = QCA::BigInteger( "-286399096802321907543674770412181810379003627366516307780436082546" )
- += QCA::BigInteger( "6433131620680089024037442172197761714707480582555136398379812339597187475099646442833150194" );
- QCOMPARE( result.toString(), QString( "6433131620680089024037441885798664912385573038880365986198001960593560108583338662397067648" ) );
- QCOMPARE( result, QCA::BigInteger( "6433131620680089024037441885798664912385573038880365986198001960593560108583338662397067648" ) );
-
- result = QCA::BigInteger( "181180339077102369559537817583627894783322804181859729574752442572146800569023773490164987520541203125338295785763244283224569259250011493" )
- += QCA::BigInteger( "-1199127665773503170250307078028035875479459397657178356959526245067549497129923023348187933280753018204983010837846725666878521137637491" );
- QCOMPARE( result.toString(), QString( "179981211411328866389287510505599858907843344784202551217792916327079251071893850466816799587260450107133312774925397557557690738112374002" ) );
- QCOMPARE( result, QCA::BigInteger( "179981211411328866389287510505599858907843344784202551217792916327079251071893850466816799587260450107133312774925397557557690738112374002" ) );
-
- result = QCA::BigInteger( "-64140201395555533811408642891620184652051275811075926176282032144915585503450776768366775652419022149512034611311149858695307750874152" )
- += QCA::BigInteger( "174441039" );
- QCOMPARE( result.toString(), QString( "-64140201395555533811408642891620184652051275811075926176282032144915585503450776768366775652419022149512034611311149858695307576433113" ) );
- QCOMPARE( result, QCA::BigInteger( "-64140201395555533811408642891620184652051275811075926176282032144915585503450776768366775652419022149512034611311149858695307576433113" ) );
-
- result = QCA::BigInteger( "1272757944308835857208037878018507337530557445422230495561634616503724419877512717512360239259640193513601352202821462208896049331599624285621" )
- += QCA::BigInteger( "7326562354017884140300121264633612334070903165496641915889499701\
-38457507491850467631029977010" );
- QCOMPARE( result.toString(), QString( "1272757944308835857208037878018507337530557445422963151797036404917754432003976078745767329576189857705190302172959919716387899799230654262631" ) );
- QCOMPARE( result, QCA::BigInteger( "1272757944308835857208037878018507337530557445422963151797036404917754432003976078745767329576189857705190302172959919716387899799230654262631" ) );
-
- result = QCA::BigInteger( "-296171972628230" )
- += QCA::BigInteger( "-8295766099121843219000823699362222865173820102569731517716391727126741710202086962877467940292139" );
- QCOMPARE( result.toString(), QString( "-8295766099121843219000823699362222865173820102569731517716391727126741710202086963173639912920369" ) );
- QCOMPARE( result, QCA::BigInteger( "-8295766099121843219000823699362222865173820102569731517716391727126741710202086963173639912920369" ) );
-
- result = QCA::BigInteger( "746985914068199510024843682108839444828414222769191520615967632362127522466922882591" )
- += QCA::BigInteger( "-20487191102299831461877807785745372724903547246374023" );
- QCOMPARE( result.toString(), QString( "746985914068199510024843682108818957637311922937729642808181886989402618919676508568" ) );
- QCOMPARE( result, QCA::BigInteger( "746985914068199510024843682108818957637311922937729642808181886989402618919676508568" ) );
-
- result = QCA::BigInteger( "-4" )
- += QCA::BigInteger( "-2344390090753264806043234960981151613122271366762590006930318876906455201397017135" );
- QCOMPARE( result.toString(), QString( "-2344390090753264806043234960981151613122271366762590006930318876906455201397017139" ) );
- QCOMPARE( result, QCA::BigInteger( "-2344390090753264806043234960981151613122271366762590006930318876906455201397017139" ) );
-
- result = QCA::BigInteger( "-44876180273995737337769331875058141129678736711749946388832275767882143882764" )
- += QCA::BigInteger( "20982187786" );
- QCOMPARE( result.toString(), QString( "-44876180273995737337769331875058141129678736711749946388832275767861161694978" ) );
- QCOMPARE( result, QCA::BigInteger( "-44876180273995737337769331875058141129678736711749946388832275767861161694978" ) );
-
- result = QCA::BigInteger( "-6019440082648243511340058232981487443695615379104154368957939907896782179207195666302228625496897271988494" )
- += QCA::BigInteger( "532566302499155416003316607801593784583652720754079760364736422291735917382015688217276924340984564880" );
- QCOMPARE( result.toString(), QString( "-6018907516345744355924054916373685849911031726383400289197575171474490443289813650614011348572556287423614" ) );
- QCOMPARE( result, QCA::BigInteger( "-6018907516345744355924054916373685849911031726383400289197575171474490443289813650614011348572556287423614" ) );
-
- result = QCA::BigInteger( "-73755471563616026847726349357167530833850959662921059052928229237814728719448868719278211294785998253117976812683153264088230182865250970217610487" )
- += QCA::BigInteger( "-30100016097092378349958946184353117306134810372681" );
- QCOMPARE( result.toString(), QString( "-73755471563616026847726349357167530833850959662921059052928229237814728719448868719278211294786028353134073905061503223034414535982557105027983168" ) );
- QCOMPARE( result, QCA::BigInteger( "-73755471563616026847726349357167530833850959662921059052928229237814728719448868719278211294786028353134073905061503223034414535982557105027983168" ) );
-
- result = QCA::BigInteger( "-2211177066689704345686852756638946306674958952044447080285364283965878599873864667094550865713828159912" )
- += QCA::BigInteger( "-5365560439372456892007565798761606781997269201538475736814780300517383963455858081652308237033460360040921820049494698892905680307378540208" );
- QCOMPARE( result.toString(), QString( "-5365560439372456892007565798761606784208446268228180082501633057156330270130817033696755317318824644006800419923359365987456546021206700120" ) );
- QCOMPARE( result, QCA::BigInteger( "-5365560439372456892007565798761606784208446268228180082501633057156330270130817033696755317318824644006800419923359365987456546021206700120" ) );
-
- result = QCA::BigInteger( "6074122512337108841968521649035076841633691574254417104144285970819068715158037023149867252146570418484850234979838064249373816163440" )
- += QCA::BigInteger( "301843614094506325875637699" );
- QCOMPARE( result.toString(), QString( "6074122512337108841968521649035076841633691574254417104144285970819068715158037023149867252146570418484850536823452158755699691801139" ) );
- QCOMPARE( result, QCA::BigInteger( "6074122512337108841968521649035076841633691574254417104144285970819068715158037023149867252146570418484850536823452158755699691801139" ) );
-
- result = QCA::BigInteger( "-518214776931158149908771340564348982010543985108065053479219152734659892042499774128809654713651547833087206893256740737426200715673766732196603988" )
- += QCA::BigInteger( "-29835172557747693726115525887386137004674545311422557345658884038760353928226157702249175218280718951979" );
- QCOMPARE( result.toString(), QString( "-518214776931158149908771340564348982010544014943237611226912878850185779428636778803354966136208893491971245653610668963583902964848985012915555967" ) );
- QCOMPARE( result, QCA::BigInteger( "-518214776931158149908771340564348982010544014943237611226912878850185779428636778803354966136208893491971245653610668963583902964848985012915555967" ) );
-
- result = QCA::BigInteger( "15937412249227240968245047444122" )
- += QCA::BigInteger( "186214680376169426108822450700978827886569053440254258585576645530381613666540347032550716844628275956253" );
- QCOMPARE( result.toString(), QString( "186214680376169426108822450700978827886569053440254258585576645530381613682477759281777957812873323400375" ) );
- QCOMPARE( result, QCA::BigInteger( "186214680376169426108822450700978827886569053440254258585576645530381613682477759281777957812873323400375" ) );
-
- result = QCA::BigInteger( "-12528010116258685855047504252928107623923105458701761707911969527003855713485846140551107967495813584097081777160" )
- += QCA::BigInteger( "-539986280927242338236008809854961759996986302156061552378097160849129372827386927545686899193598721998757419572890" );
- QCOMPARE( result.toString(), QString( "-552514291043501024091056314107889867620909407614763314086009130376133228540872773686238007161094535582854501350050" ) );
- QCOMPARE( result, QCA::BigInteger( "-552514291043501024091056314107889867620909407614763314086009130376133228540872773686238007161094535582854501350050" ) );
-
- result = QCA::BigInteger( "-2454746908" )
- += QCA::BigInteger( "-3822957127889394780055242156360370187075592078655552376050604679934415014573879513870030211860839641756441626913419699098985245833920954444218" );
- QCOMPARE( result.toString(), QString( "-3822957127889394780055242156360370187075592078655552376050604679934415014573879513870030211860839641756441626913419699098985245833923409191126" ) );
- QCOMPARE( result, QCA::BigInteger( "-3822957127889394780055242156360370187075592078655552376050604679934415014573879513870030211860839641756441626913419699098985245833923409191126" ) );
-
-
- result = QCA::BigInteger( "-54288706131860071583318409080596095357980447323635" )
- += QCA::BigInteger( "-425339410556015631098973742993327323051438456819027069606294261157940297643297240559452124432779202181589763874" );
- QCOMPARE( result.toString(), QString( "-425339410556015631098973742993327323051438456819027069606294315446646429503368823877861205028874560162037087509" ) );
- QCOMPARE( result, QCA::BigInteger( "-425339410556015631098973742993327323051438456819027069606294315446646429503368823877861205028874560162037087509" ) );
-
- result = QCA::BigInteger( "1418766894051319870818496026367686195459604395660119754151922014257535705077512233275240217434104" )
- += QCA::BigInteger( "-111987390206074845527" );
- QCOMPARE( result.toString(), QString( "1418766894051319870818496026367686195459604395660119754151922014257535705077400245885034142588577" ) );
- QCOMPARE( result, QCA::BigInteger( "1418766894051319870818496026367686195459604395660119754151922014257535705077400245885034142588577" ) );
-
- result = QCA::BigInteger( "-690410131860410477456103857594543515409677479242833618634809302452962600476353286822550168231234854116465153078845744722987447719420052500874721214723" )
- += QCA::BigInteger( "-2584690377433946747311356992432788361455494791066739384837409609897387109736539600623155880918146331681272708396146283818299" );
- QCOMPARE( result.toString(), QString( "-690410131860410477456103860179233892843624226554190611067597663908457391543092671659959778128621963853004753702001625641133779400692760897021005033022" ) );
- QCOMPARE( result, QCA::BigInteger( "-690410131860410477456103860179233892843624226554190611067597663908457391543092671659959778128621963853004753702001625641133779400692760897021005033022" ) );
-
- result = QCA::BigInteger( "-2326153002179462643778624079324592172489363679671158" )
- += QCA::BigInteger( "-109819757548464054181938329012610459679" );
- QCOMPARE( result.toString(), QString( "-2326153002179572463536172543378774110818376290130837" ) );
- QCOMPARE( result, QCA::BigInteger( "-2326153002179572463536172543378774110818376290130837" ) );
-
- result = QCA::BigInteger( "-4428752250566525488353857709194941742993785578807911414016959206453045495320705299466107784149485981354180907411034982168391" )
- += QCA::BigInteger( "-39247778259374215325521768005388007526581235832446540589720560855741992694947322437679214611686905696" );
- QCOMPARE( result.toString(), QString( "-4428752250566525488353896956973201117209111100575916802024485787688877941861295020026963526142180928676618586625646669074087" ) );
- QCOMPARE( result, QCA::BigInteger( "-4428752250566525488353896956973201117209111100575916802024485787688877941861295020026963526142180928676618586625646669074087" ) );
-
- result = QCA::BigInteger( "3047" )
- += QCA::BigInteger( "-73564587850313153523776932163719610733433776890390204618040173797196000100856070829277943048343156165795282307508135277641315214" );
- QCOMPARE( result.toString(), QString( "-73564587850313153523776932163719610733433776890390204618040173797196000100856070829277943048343156165795282307508135277641312167" ) );
- QCOMPARE( result, QCA::BigInteger( "-73564587850313153523776932163719610733433776890390204618040173797196000100856070829277943048343156165795282307508135277641312167" ) );
-
- result = QCA::BigInteger( "71397189765381049110362731262243394989390499523719445987286843598407339615555456955143712741779487184644001767776382991377987516772847242986" )
- += QCA::BigInteger( "-5821969555717973232123574849275726788359152255219972775831" );
- QCOMPARE( result.toString(), QString( "71397189765381049110362731262243394989390499523719445987286843598407339615555456949321743186061513952520426918500656203018835261552874467155" ) );
- QCOMPARE( result, QCA::BigInteger( "71397189765381049110362731262243394989390499523719445987286843598407339615555456949321743186061513952520426918500656203018835261552874467155" ) );
-
- result = QCA::BigInteger( "-181409752656613138777964092635909379021826360390960647186726991165227400176766831466541160049935205507919070233410228328274" )
- += QCA::BigInteger( "-523301382154855044703947051892202646490840761177533623732372519689918420769842424772676407501350528096714904915297347684247802773107355881667545916901" );
- QCOMPARE( result.toString(), QString( "-523301382154855044703947052073612399147453899955497716368281898711744781160803071959403398666577928273481736381838507734183008281026426115077774245175" ) );
- QCOMPARE( result, QCA::BigInteger( "-523301382154855044703947052073612399147453899955497716368281898711744781160803071959403398666577928273481736381838507734183008281026426115077774245175" ) );
-
- result = QCA::BigInteger( "6858961373707073067" )
- += QCA::BigInteger( "-334051508933893061433844279764271107181974906283364991309903077649971606436918071327072869826471946094594594115614990907" );
- QCOMPARE( result.toString(), QString( "-334051508933893061433844279764271107181974906283364991309903077649971606436918071327072869826471946087735632741907917840" ) );
- QCOMPARE( result, QCA::BigInteger( "-334051508933893061433844279764271107181974906283364991309903077649971606436918071327072869826471946087735632741907917840" ) );
-
- result = QCA::BigInteger( "-23635098930374569407171906960429616870908424281519944658490940109956689534874971218650241680916564611" )
- += QCA::BigInteger( "-18958917875779522833599589133142827952448539301142718746979271443846670235982743793439686626736428198541647202983677887505430060922528525205" );
- QCOMPARE( result.toString(), QString( "-18958917875779522833599589133142827952472174400073093316386443350807099852853652217721206571394919138651603892518552858724080302603445089816" ) );
- QCOMPARE( result, QCA::BigInteger( "-18958917875779522833599589133142827952472174400073093316386443350807099852853652217721206571394919138651603892518552858724080302603445089816" ) );
+ result = QCA::BigInteger("340282366920938463463374607431768211455")
+ += QCA::BigInteger("340282366920938463463374607431768211455");
+ QCOMPARE(result.toString(), QString("680564733841876926926749214863536422910"));
+ QCOMPARE(result, QCA::BigInteger("680564733841876926926749214863536422910"));
+
+ result = QCA::BigInteger("340282366920938463463374607431768211455")
+ += QCA::BigInteger("340282366920938463463374607431768211450");
+ QCOMPARE(result.toString(), QString("680564733841876926926749214863536422905"));
+ QCOMPARE(result, QCA::BigInteger("680564733841876926926749214863536422905"));
+
+ result = QCA::BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639935")
+ += QCA::BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639935");
+ QCOMPARE(result.toString(), QString("231584178474632390847141970017375815706539969331281128078915168015826259279870"));
+ QCOMPARE(result, QCA::BigInteger("231584178474632390847141970017375815706539969331281128078915168015826259279870"));
+
+ result = QCA::BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639935")
+ += QCA::BigInteger("115792089237316195423570985008687907853269984665640564039457584007913129639919");
+ QCOMPARE(result.toString(), QString("231584178474632390847141970017375815706539969331281128078915168015826259279854"));
+ QCOMPARE(result, QCA::BigInteger("231584178474632390847141970017375815706539969331281128078915168015826259279854"));
+
+ result = QCA::BigInteger("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095")
+ += QCA::BigInteger("18446744073709551616");
+ QCOMPARE(result.toString(), QString("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946588393177722715635711"));
+ QCOMPARE(result, QCA::BigInteger("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946588393177722715635711"));
+
+ result = QCA::BigInteger("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095")
+ += QCA::BigInteger("1");
+ QCOMPARE(result.toString(), QString("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096"));
+ QCOMPARE(result, QCA::BigInteger("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096"));
+
+ result = QCA::BigInteger("-39794270013919406610834826960427146769766189764838473416502965291920535601112688579198627475284777498059330306128763345008528325994574657552726381901")
+ += QCA::BigInteger("-342238655038");
+ QCOMPARE(result.toString(), QString("-39794270013919406610834826960427146769766189764838473416502965291920535601112688579198627475284777498059330306128763345008528325994574657894965036939"));
+ QCOMPARE(result, QCA::BigInteger("-39794270013919406610834826960427146769766189764838473416502965291920535601112688579198627475284777498059330306128763345008528325994574657894965036939"));
+
+ result = QCA::BigInteger("25110291853498940831251897922987678157346336093292373576945426289097725034326735312448621015537884914")
+ += QCA::BigInteger("-36551081154398645734533965739979697527373251608055056627686956281114038842935173436543461");
+ QCOMPARE(result.toString(), QString("25110291853462389750097499277253144191606356395765000325337371232470038078045621273605685842101341453"));
+ QCOMPARE(result, QCA::BigInteger("25110291853462389750097499277253144191606356395765000325337371232470038078045621273605685842101341453"));
+
+ result = QCA::BigInteger("27802650352")
+ += QCA::BigInteger("660736146705288303126411072388564329913778942");
+ QCOMPARE(result.toString(), QString("660736146705288303126411072388564357716429294"));
+ QCOMPARE(result, QCA::BigInteger("660736146705288303126411072388564357716429294"));
+
+ result = QCA::BigInteger("-1348245899955041864800954463709881466231496038216683608715424566397833766910915722793041224478985289")
+ += QCA::BigInteger("11517149522866182358565152643595266257020228597058539113114732218008332987904361457299261161227276764386173666571334749062651694592291882972");
+ QCOMPARE(result.toString(), QString("11517149522866182358565152643595266257018880351158584071249931263544623106438129961261044477618561339819775832804423833339858653367812897683"));
+ QCOMPARE(result, QCA::BigInteger("11517149522866182358565152643595266257018880351158584071249931263544623106438129961261044477618561339819775832804423833339858653367812897683"));
+
+ result = QCA::BigInteger("-17540530441681616962868251635133601915039026254996886583618243914226325157426408929602625346567256761818")
+ += QCA::BigInteger("865200427983527245206901810160356641402419461642082623179544681519016990");
+ QCOMPARE(result.toString(), QString("-17540530441681616962868251635132736714611042727751679681808083557584922737964766846979445801885737744828"));
+ QCOMPARE(result, QCA::BigInteger("-17540530441681616962868251635132736714611042727751679681808083557584922737964766846979445801885737744828"));
+
+ result = QCA::BigInteger("128844776074298261556398714096948603458177018275051329218555498374")
+ += QCA::BigInteger("443816313829150876362052235134610603220548928107697961229953611873695276391917150913346479060246759720475193648");
+ QCOMPARE(result.toString(), QString("443816313829150876362052235134610603220548928236542737304251873430093990488865754371523497335298088939030692022"));
+ QCOMPARE(result, QCA::BigInteger("443816313829150876362052235134610603220548928236542737304251873430093990488865754371523497335298088939030692022"));
+
+ result = QCA::BigInteger("1709484189262457846620911889502097055085989595277300243221975568275935717696463")
+ += QCA::BigInteger("-1646592344139809206374540620411514484579951199941360");
+ QCOMPARE(result.toString(), QString("1709484189262457846620911887855504710946180388902759622810461083695984517755103"));
+ QCOMPARE(result, QCA::BigInteger("1709484189262457846620911887855504710946180388902759622810461083695984517755103"));
+
+ result = QCA::BigInteger("320175865429637176165709341576187102540180627806418015204928771170233538951323952509055929139673223273528062883083030595199153877335714942842")
+ += QCA::BigInteger("-2828241696960736089879965882386687935938570856545481227619497640844399275054327390050478930503975773972");
+ QCOMPARE(result.toString(), QString("320175865429637176165709341576187102537352386109457279115048805287846851015385381652510447912053725632683663608028703205148674946831739168870"));
+ QCOMPARE(result, QCA::BigInteger("320175865429637176165709341576187102537352386109457279115048805287846851015385381652510447912053725632683663608028703205148674946831739168870"));
+
+ result = QCA::BigInteger("-4035398360542181725908295312107496142105415014744259439963377204111754181625695349185753326709217")
+ += QCA::BigInteger("85450213703789913646546187382091037800");
+ QCOMPARE(result.toString(), QString("-4035398360542181725908295312107496142105415014744259439963291753898050391712048802998371235671417"));
+ QCOMPARE(result, QCA::BigInteger("-4035398360542181725908295312107496142105415014744259439963291753898050391712048802998371235671417"));
+
+ result = QCA::BigInteger("-1292166446073479876801522363382357887431657639184151284775525387363973852756087726243671676713861533673009088319851")
+ += QCA::BigInteger("804538895874518175537499425282375058236245531798590350403343841766955572070643267141945695624895109330242749935754739434394691714971");
+ QCOMPARE(result.toString(), QString("804538895874518174245332979208895181434723168416232462971686202582804287295117879777971842868807383086571073221893205761385603395120"));
+ QCOMPARE(result, QCA::BigInteger("804538895874518174245332979208895181434723168416232462971686202582804287295117879777971842868807383086571073221893205761385603395120"));
+
+ result = QCA::BigInteger("-451986588700926309459451756852005697379481014956007968529234251884946522682901215022086432597024324062240835564200177389")
+ += QCA::BigInteger("15762983479");
+ QCOMPARE(result.toString(), QString("-451986588700926309459451756852005697379481014956007968529234251884946522682901215022086432597024324062240835548437193910"));
+ QCOMPARE(result, QCA::BigInteger("-451986588700926309459451756852005697379481014956007968529234251884946522682901215022086432597024324062240835548437193910"));
+
+ result = QCA::BigInteger("-3907475412115728816974567022055278374116794025624287474334038831885743634200801846649105209920908153587891040882946582394429615396962188674594744360388466")
+ += QCA::BigInteger("193893611236537854694879677478106237157079207398283117392998175454362643521031390");
+ QCOMPARE(result.toString(), QString("-3907475412115728816974567022055278374116794025624287474334038831885743634006908235412567355226028476109784803725867374996146498003964013220232100839357076"));
+ QCOMPARE(result, QCA::BigInteger("-3907475412115728816974567022055278374116794025624287474334038831885743634006908235412567355226028476109784803725867374996146498003964013220232100839357076"));
+
+ result = QCA::BigInteger("-72603710637966201224690926289")
+ += QCA::BigInteger("-13618442642298533261581255034923612640512507150728017106768861506299813289801666559564532");
+ QCOMPARE(result.toString(), QString("-13618442642298533261581255034923612640512507150728017106768934110010451256002891250490821"));
+ QCOMPARE(result, QCA::BigInteger("-13618442642298533261581255034923612640512507150728017106768934110010451256002891250490821"));
+
+ result = QCA::BigInteger("56077960835713056831402948406790747107889446769357509759472207603483968107693997028111823994257399379783658853302692762256851623103019589392739")
+ += QCA::BigInteger("-427057313888431079237360487703561848638868677065083968842");
+ QCOMPARE(result.toString(), QString("56077960835713056831402948406790747107889446769357509759472207603483968107693997028111396936943510948704421492814989200408212754425954505423897"));
+ QCOMPARE(result, QCA::BigInteger("56077960835713056831402948406790747107889446769357509759472207603483968107693997028111396936943510948704421492814989200408212754425954505423897"));
+
+ result = QCA::BigInteger("-2209800838508504443494783762534800337712101405156784708782197580824527899758308")
+ += QCA::BigInteger("42844076503039495864500213925837598507817708418354152774112078596443089606598570396235816327987463393971710495985285591895096794994387176281079");
+ QCOMPARE(result.toString(), QString("42844076503039495864500213925837598507817708418354152774112078594233288768090065952741032565452663056259609090828500883112899214169859276522771"));
+ QCOMPARE(result, QCA::BigInteger("42844076503039495864500213925837598507817708418354152774112078594233288768090065952741032565452663056259609090828500883112899214169859276522771"));
+
+ result = QCA::BigInteger("33887767308809826842417841176152232321272231788338404526859019370507113927387984766381329515371768224976188337692")
+ += QCA::BigInteger("349484339542971517481628970179002500341");
+ QCOMPARE(result.toString(), QString("33887767308809826842417841176152232321272231788338404526859019370507113927737469105924301032853397195155190838033"));
+ QCOMPARE(result, QCA::BigInteger("33887767308809826842417841176152232321272231788338404526859019370507113927737469105924301032853397195155190838033"));
+
+ result = QCA::BigInteger("85748089639858660722587321621536298082690707526412426951630101551228144063151688592419555048867068162")
+ += QCA::BigInteger("-383634567691961960211191292397062452265352651123492760493087381707279");
+ QCOMPARE(result.toString(), QString("85748089639858660722587321621535914448123015564452215760337704488775878710500565099659061961485360883"));
+ QCOMPARE(result, QCA::BigInteger("85748089639858660722587321621535914448123015564452215760337704488775878710500565099659061961485360883"));
+
+ result = QCA::BigInteger("23889807888563742283608049816129153552608399262924421832404872043475")
+ += QCA::BigInteger("995");
+ QCOMPARE(result.toString(), QString("23889807888563742283608049816129153552608399262924421832404872044470"));
+ QCOMPARE(result, QCA::BigInteger("23889807888563742283608049816129153552608399262924421832404872044470"));
+
+ result = QCA::BigInteger("-654786925833474864669230962582694222611472680701859262466465606239654996048306783957549697781271829257774329538985")
+ += QCA::BigInteger("-276137507159648540503039013089014674747");
+ QCOMPARE(result.toString(), QString("-654786925833474864669230962582694222611472680701859262466465606239654996048582921464709346321774868270863344213732"));
+ QCOMPARE(result, QCA::BigInteger("-654786925833474864669230962582694222611472680701859262466465606239654996048582921464709346321774868270863344213732"));
+
+ result = QCA::BigInteger("50463316268089933")
+ += QCA::BigInteger("-140591583463431806921000349498135287589005423318927850947894242995310138569473157521312413652439234324419130527702899917161307657443381774866237429");
+ QCOMPARE(result.toString(), QString("-140591583463431806921000349498135287589005423318927850947894242995310138569473157521312413652439234324419130527702899917161307657392918458598147496"));
+ QCOMPARE(result, QCA::BigInteger("-140591583463431806921000349498135287589005423318927850947894242995310138569473157521312413652439234324419130527702899917161307657392918458598147496"));
+
+ result = QCA::BigInteger("1339015021665554488163337105187026760232395594198925052890859936\
+418304234254229440059229155546157793544192")
+ += QCA::BigInteger("6294037420283433712414743361937677483761554699961644450461297486224793278823004487175687771163597590566132592591599249970281125781761944353272");
+ QCOMPARE(result.toString(), QString("6294037420283433712414743361937677485100569721627198938624634591411820039055400081374612824054457526984436826845828690029510281327919737897464"));
+ QCOMPARE(result, QCA::BigInteger("6294037420283433712414743361937677485100569721627198938624634591411820039055400081374612824054457526984436826845828690029510281327919737897464"));
+
+ result = QCA::BigInteger("-241446683")
+ += QCA::BigInteger("-282671163032866994488211995758272717472259277760825940523445628\
+442206062910449311538519756165635175664610569214430918184214");
+ QCOMPARE(result.toString(), QString("-282671163032866994488211995758272717472259277760825940523445628442206062910449311538519756165635175664610569214431159630897"));
+ QCOMPARE(result, QCA::BigInteger("-282671163032866994488211995758272717472259277760825940523445628442206062910449311538519756165635175664610569214431159630897"));
+
+ result = QCA::BigInteger("2358605503303452637996081421902056515951744611718383128442445119505739707550326378912342448355046239066896995563581")
+ += QCA::BigInteger("-3830437229145325165273364525551261440648845791949681661260946956860463720730123941973615");
+ QCOMPARE(result.toString(), QString("2358605503303452637996081418071619286806419446445018602891183678856893915600644717651395491494582518336773053589966"));
+ QCOMPARE(result, QCA::BigInteger("2358605503303452637996081418071619286806419446445018602891183678856893915600644717651395491494582518336773053589966"));
+
+ result = QCA::BigInteger("1860794367587960058388097846258490")
+ += QCA::BigInteger("-237344494507203983863096991896035366478949095337787603280");
+ QCOMPARE(result.toString(), QString("-237344494507203983863095131101667778518890707239941344790"));
+ QCOMPARE(result, QCA::BigInteger("-237344494507203983863095131101667778518890707239941344790"));
+
+ result = QCA::BigInteger("-286399096802321907543674770412181810379003627366516307780436082546")
+ += QCA::BigInteger("6433131620680089024037442172197761714707480582555136398379812339597187475099646442833150194");
+ QCOMPARE(result.toString(), QString("6433131620680089024037441885798664912385573038880365986198001960593560108583338662397067648"));
+ QCOMPARE(result, QCA::BigInteger("6433131620680089024037441885798664912385573038880365986198001960593560108583338662397067648"));
+
+ result = QCA::BigInteger("181180339077102369559537817583627894783322804181859729574752442572146800569023773490164987520541203125338295785763244283224569259250011493")
+ += QCA::BigInteger("-1199127665773503170250307078028035875479459397657178356959526245067549497129923023348187933280753018204983010837846725666878521137637491");
+ QCOMPARE(result.toString(), QString("179981211411328866389287510505599858907843344784202551217792916327079251071893850466816799587260450107133312774925397557557690738112374002"));
+ QCOMPARE(result, QCA::BigInteger("179981211411328866389287510505599858907843344784202551217792916327079251071893850466816799587260450107133312774925397557557690738112374002"));
+
+ result = QCA::BigInteger("-64140201395555533811408642891620184652051275811075926176282032144915585503450776768366775652419022149512034611311149858695307750874152")
+ += QCA::BigInteger("174441039");
+ QCOMPARE(result.toString(), QString("-64140201395555533811408642891620184652051275811075926176282032144915585503450776768366775652419022149512034611311149858695307576433113"));
+ QCOMPARE(result, QCA::BigInteger("-64140201395555533811408642891620184652051275811075926176282032144915585503450776768366775652419022149512034611311149858695307576433113"));
+
+ result = QCA::BigInteger("1272757944308835857208037878018507337530557445422230495561634616503724419877512717512360239259640193513601352202821462208896049331599624285621")
+ += QCA::BigInteger("7326562354017884140300121264633612334070903165496641915889499701\
+38457507491850467631029977010");
+ QCOMPARE(result.toString(), QString("1272757944308835857208037878018507337530557445422963151797036404917754432003976078745767329576189857705190302172959919716387899799230654262631"));
+ QCOMPARE(result, QCA::BigInteger("1272757944308835857208037878018507337530557445422963151797036404917754432003976078745767329576189857705190302172959919716387899799230654262631"));
+
+ result = QCA::BigInteger("-296171972628230")
+ += QCA::BigInteger("-8295766099121843219000823699362222865173820102569731517716391727126741710202086962877467940292139");
+ QCOMPARE(result.toString(), QString("-8295766099121843219000823699362222865173820102569731517716391727126741710202086963173639912920369"));
+ QCOMPARE(result, QCA::BigInteger("-8295766099121843219000823699362222865173820102569731517716391727126741710202086963173639912920369"));
+
+ result = QCA::BigInteger("746985914068199510024843682108839444828414222769191520615967632362127522466922882591")
+ += QCA::BigInteger("-20487191102299831461877807785745372724903547246374023");
+ QCOMPARE(result.toString(), QString("746985914068199510024843682108818957637311922937729642808181886989402618919676508568"));
+ QCOMPARE(result, QCA::BigInteger("746985914068199510024843682108818957637311922937729642808181886989402618919676508568"));
+
+ result = QCA::BigInteger("-4")
+ += QCA::BigInteger("-2344390090753264806043234960981151613122271366762590006930318876906455201397017135");
+ QCOMPARE(result.toString(), QString("-2344390090753264806043234960981151613122271366762590006930318876906455201397017139"));
+ QCOMPARE(result, QCA::BigInteger("-2344390090753264806043234960981151613122271366762590006930318876906455201397017139"));
+
+ result = QCA::BigInteger("-44876180273995737337769331875058141129678736711749946388832275767882143882764")
+ += QCA::BigInteger("20982187786");
+ QCOMPARE(result.toString(), QString("-44876180273995737337769331875058141129678736711749946388832275767861161694978"));
+ QCOMPARE(result, QCA::BigInteger("-44876180273995737337769331875058141129678736711749946388832275767861161694978"));
+
+ result = QCA::BigInteger("-6019440082648243511340058232981487443695615379104154368957939907896782179207195666302228625496897271988494")
+ += QCA::BigInteger("532566302499155416003316607801593784583652720754079760364736422291735917382015688217276924340984564880");
+ QCOMPARE(result.toString(), QString("-6018907516345744355924054916373685849911031726383400289197575171474490443289813650614011348572556287423614"));
+ QCOMPARE(result, QCA::BigInteger("-6018907516345744355924054916373685849911031726383400289197575171474490443289813650614011348572556287423614"));
+
+ result = QCA::BigInteger("-73755471563616026847726349357167530833850959662921059052928229237814728719448868719278211294785998253117976812683153264088230182865250970217610487")
+ += QCA::BigInteger("-30100016097092378349958946184353117306134810372681");
+ QCOMPARE(result.toString(), QString("-73755471563616026847726349357167530833850959662921059052928229237814728719448868719278211294786028353134073905061503223034414535982557105027983168"));
+ QCOMPARE(result, QCA::BigInteger("-73755471563616026847726349357167530833850959662921059052928229237814728719448868719278211294786028353134073905061503223034414535982557105027983168"));
+
+ result = QCA::BigInteger("-2211177066689704345686852756638946306674958952044447080285364283965878599873864667094550865713828159912")
+ += QCA::BigInteger("-5365560439372456892007565798761606781997269201538475736814780300517383963455858081652308237033460360040921820049494698892905680307378540208");
+ QCOMPARE(result.toString(), QString("-5365560439372456892007565798761606784208446268228180082501633057156330270130817033696755317318824644006800419923359365987456546021206700120"));
+ QCOMPARE(result, QCA::BigInteger("-5365560439372456892007565798761606784208446268228180082501633057156330270130817033696755317318824644006800419923359365987456546021206700120"));
+
+ result = QCA::BigInteger("6074122512337108841968521649035076841633691574254417104144285970819068715158037023149867252146570418484850234979838064249373816163440")
+ += QCA::BigInteger("301843614094506325875637699");
+ QCOMPARE(result.toString(), QString("6074122512337108841968521649035076841633691574254417104144285970819068715158037023149867252146570418484850536823452158755699691801139"));
+ QCOMPARE(result, QCA::BigInteger("6074122512337108841968521649035076841633691574254417104144285970819068715158037023149867252146570418484850536823452158755699691801139"));
+
+ result = QCA::BigInteger("-518214776931158149908771340564348982010543985108065053479219152734659892042499774128809654713651547833087206893256740737426200715673766732196603988")
+ += QCA::BigInteger("-29835172557747693726115525887386137004674545311422557345658884038760353928226157702249175218280718951979");
+ QCOMPARE(result.toString(), QString("-518214776931158149908771340564348982010544014943237611226912878850185779428636778803354966136208893491971245653610668963583902964848985012915555967"));
+ QCOMPARE(result, QCA::BigInteger("-518214776931158149908771340564348982010544014943237611226912878850185779428636778803354966136208893491971245653610668963583902964848985012915555967"));
+
+ result = QCA::BigInteger("15937412249227240968245047444122")
+ += QCA::BigInteger("186214680376169426108822450700978827886569053440254258585576645530381613666540347032550716844628275956253");
+ QCOMPARE(result.toString(), QString("186214680376169426108822450700978827886569053440254258585576645530381613682477759281777957812873323400375"));
+ QCOMPARE(result, QCA::BigInteger("186214680376169426108822450700978827886569053440254258585576645530381613682477759281777957812873323400375"));
+
+ result = QCA::BigInteger("-12528010116258685855047504252928107623923105458701761707911969527003855713485846140551107967495813584097081777160")
+ += QCA::BigInteger("-539986280927242338236008809854961759996986302156061552378097160849129372827386927545686899193598721998757419572890");
+ QCOMPARE(result.toString(), QString("-552514291043501024091056314107889867620909407614763314086009130376133228540872773686238007161094535582854501350050"));
+ QCOMPARE(result, QCA::BigInteger("-552514291043501024091056314107889867620909407614763314086009130376133228540872773686238007161094535582854501350050"));
+
+ result = QCA::BigInteger("-2454746908")
+ += QCA::BigInteger("-3822957127889394780055242156360370187075592078655552376050604679934415014573879513870030211860839641756441626913419699098985245833920954444218");
+ QCOMPARE(result.toString(), QString("-3822957127889394780055242156360370187075592078655552376050604679934415014573879513870030211860839641756441626913419699098985245833923409191126"));
+ QCOMPARE(result, QCA::BigInteger("-3822957127889394780055242156360370187075592078655552376050604679934415014573879513870030211860839641756441626913419699098985245833923409191126"));
+
+ result = QCA::BigInteger("-54288706131860071583318409080596095357980447323635")
+ += QCA::BigInteger("-425339410556015631098973742993327323051438456819027069606294261157940297643297240559452124432779202181589763874");
+ QCOMPARE(result.toString(), QString("-425339410556015631098973742993327323051438456819027069606294315446646429503368823877861205028874560162037087509"));
+ QCOMPARE(result, QCA::BigInteger("-425339410556015631098973742993327323051438456819027069606294315446646429503368823877861205028874560162037087509"));
+
+ result = QCA::BigInteger("1418766894051319870818496026367686195459604395660119754151922014257535705077512233275240217434104")
+ += QCA::BigInteger("-111987390206074845527");
+ QCOMPARE(result.toString(), QString("1418766894051319870818496026367686195459604395660119754151922014257535705077400245885034142588577"));
+ QCOMPARE(result, QCA::BigInteger("1418766894051319870818496026367686195459604395660119754151922014257535705077400245885034142588577"));
+
+ result = QCA::BigInteger("-690410131860410477456103857594543515409677479242833618634809302452962600476353286822550168231234854116465153078845744722987447719420052500874721214723")
+ += QCA::BigInteger("-2584690377433946747311356992432788361455494791066739384837409609897387109736539600623155880918146331681272708396146283818299");
+ QCOMPARE(result.toString(), QString("-690410131860410477456103860179233892843624226554190611067597663908457391543092671659959778128621963853004753702001625641133779400692760897021005033022"));
+ QCOMPARE(result, QCA::BigInteger("-690410131860410477456103860179233892843624226554190611067597663908457391543092671659959778128621963853004753702001625641133779400692760897021005033022"));
+
+ result = QCA::BigInteger("-2326153002179462643778624079324592172489363679671158")
+ += QCA::BigInteger("-109819757548464054181938329012610459679");
+ QCOMPARE(result.toString(), QString("-2326153002179572463536172543378774110818376290130837"));
+ QCOMPARE(result, QCA::BigInteger("-2326153002179572463536172543378774110818376290130837"));
+
+ result = QCA::BigInteger("-4428752250566525488353857709194941742993785578807911414016959206453045495320705299466107784149485981354180907411034982168391")
+ += QCA::BigInteger("-39247778259374215325521768005388007526581235832446540589720560855741992694947322437679214611686905696");
+ QCOMPARE(result.toString(), QString("-4428752250566525488353896956973201117209111100575916802024485787688877941861295020026963526142180928676618586625646669074087"));
+ QCOMPARE(result, QCA::BigInteger("-4428752250566525488353896956973201117209111100575916802024485787688877941861295020026963526142180928676618586625646669074087"));
+
+ result = QCA::BigInteger("3047")
+ += QCA::BigInteger("-73564587850313153523776932163719610733433776890390204618040173797196000100856070829277943048343156165795282307508135277641315214");
+ QCOMPARE(result.toString(), QString("-73564587850313153523776932163719610733433776890390204618040173797196000100856070829277943048343156165795282307508135277641312167"));
+ QCOMPARE(result, QCA::BigInteger("-73564587850313153523776932163719610733433776890390204618040173797196000100856070829277943048343156165795282307508135277641312167"));
+
+ result = QCA::BigInteger("71397189765381049110362731262243394989390499523719445987286843598407339615555456955143712741779487184644001767776382991377987516772847242986")
+ += QCA::BigInteger("-5821969555717973232123574849275726788359152255219972775831");
+ QCOMPARE(result.toString(), QString("71397189765381049110362731262243394989390499523719445987286843598407339615555456949321743186061513952520426918500656203018835261552874467155"));
+ QCOMPARE(result, QCA::BigInteger("71397189765381049110362731262243394989390499523719445987286843598407339615555456949321743186061513952520426918500656203018835261552874467155"));
+
+ result = QCA::BigInteger("-181409752656613138777964092635909379021826360390960647186726991165227400176766831466541160049935205507919070233410228328274")
+ += QCA::BigInteger("-523301382154855044703947051892202646490840761177533623732372519689918420769842424772676407501350528096714904915297347684247802773107355881667545916901");
+ QCOMPARE(result.toString(), QString("-523301382154855044703947052073612399147453899955497716368281898711744781160803071959403398666577928273481736381838507734183008281026426115077774245175"));
+ QCOMPARE(result, QCA::BigInteger("-523301382154855044703947052073612399147453899955497716368281898711744781160803071959403398666577928273481736381838507734183008281026426115077774245175"));
+
+ result = QCA::BigInteger("6858961373707073067")
+ += QCA::BigInteger("-334051508933893061433844279764271107181974906283364991309903077649971606436918071327072869826471946094594594115614990907");
+ QCOMPARE(result.toString(), QString("-334051508933893061433844279764271107181974906283364991309903077649971606436918071327072869826471946087735632741907917840"));
+ QCOMPARE(result, QCA::BigInteger("-334051508933893061433844279764271107181974906283364991309903077649971606436918071327072869826471946087735632741907917840"));
+
+ result = QCA::BigInteger("-23635098930374569407171906960429616870908424281519944658490940109956689534874971218650241680916564611")
+ += QCA::BigInteger("-18958917875779522833599589133142827952448539301142718746979271443846670235982743793439686626736428198541647202983677887505430060922528525205");
+ QCOMPARE(result.toString(), QString("-18958917875779522833599589133142827952472174400073093316386443350807099852853652217721206571394919138651603892518552858724080302603445089816"));
+ QCOMPARE(result, QCA::BigInteger("-18958917875779522833599589133142827952472174400073093316386443350807099852853652217721206571394919138651603892518552858724080302603445089816"));
// Botan's subtraction tests
- result = QCA::BigInteger( "0" )
- -= QCA::BigInteger( "0" );
- QCOMPARE( result.toString(), QString( "0" ) );
- QCOMPARE( result, QCA::BigInteger( "0" ) );
+ result = QCA::BigInteger("0")
+ -= QCA::BigInteger("0");
+ QCOMPARE(result.toString(), QString("0"));
+ QCOMPARE(result, QCA::BigInteger("0"));
- result = QCA::BigInteger( "0" )
- -= QCA::BigInteger( "1" );
- QCOMPARE( result.toString(), QString( "-1" ) );
- QCOMPARE( result, QCA::BigInteger( "-1" ) );
+ result = QCA::BigInteger("0")
+ -= QCA::BigInteger("1");
+ QCOMPARE(result.toString(), QString("-1"));
+ QCOMPARE(result, QCA::BigInteger("-1"));
- result = QCA::BigInteger( "0" )
- -= QCA::BigInteger( "4294967296" );
- QCOMPARE( result.toString(), QString( "-4294967296" ) );
- QCOMPARE( result, QCA::BigInteger( "-4294967296" ) );
+ result = QCA::BigInteger("0")
+ -= QCA::BigInteger("4294967296");
+ QCOMPARE(result.toString(), QString("-4294967296"));
+ QCOMPARE(result, QCA::BigInteger("-4294967296"));
// Next test is labelled # 2^512 - 1
- result = QCA::BigInteger( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095" )
- -= QCA::BigInteger( "1" );
- QCOMPARE( result.toString(), QString( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084094" ) );
- QCOMPARE( result, QCA::BigInteger( "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084094" ) );
-
- result = QCA::BigInteger( "89094716573076464980713547115099137014719483620102078148320806773871083148864" )
- -= QCA::BigInteger( "49505213825110728957828173754776257356620450607893971553289366249708672306581" );
- QCOMPARE( result.toString(), QString( "39589502747965736022885373360322879658099033012208106595031440524162410842283" ) );
- QCOMPARE( result, QCA::BigInteger( "39589502747965736022885373360322879658099033012208106595031440524162410842283" ) );
-
- result = QCA::BigInteger( "65894747009896006767807716946835412110318548717263922395390971078905789585431" )
- -= QCA::BigInteger( "3884269741925508225990715416862047284194603799902650748631039608684367281358" );
- QCOMPARE( result.toString(), QString( "62010477267970498541817001529973364826123944917361271646759931470221422304073" ) );
- QCOMPARE( result, QCA::BigInteger( "62010477267970498541817001529973364826123944917361271646759931470221422304073" ) );
-
- result = QCA::BigInteger( "5950196396451977566902121301707054218364717196893101360011491777761952253736964709165962613347710607164178682987783755894811024288429224592316636383" )
- -= QCA::BigInteger( "8750653273562160761286422180115618621879821429145276197424652349306577311499807887070429373153777028581165316131683348567" );
- QCOMPARE( result.toString(), QString( "5950196396451977566902121292956400944802556435606679179895873155882130824591688511741310264041133295664370795917354382741033995707263908460633287816" ) );
- QCOMPARE( result, QCA::BigInteger( "5950196396451977566902121292956400944802556435606679179895873155882130824591688511741310264041133295664370795917354382741033995707263908460633287816" ) );
-
- result = QCA::BigInteger( "9815262808265519920770782360080149146267723690" )
- -= QCA::BigInteger( "14067005768891609281364919358115291341352189918255780397560060748765650205261663193732434161580120817" );
- QCOMPARE( result.toString(), QString( "-14067005768891609281364919358115291341352189918255780387744797940500130284490880833652285015312397127" ) );
- QCOMPARE( result, QCA::BigInteger( "-14067005768891609281364919358115291341352189918255780387744797940500130284490880833652285015312397127" ) );
-
- result = QCA::BigInteger( "-390149102941948621568479722346940666704376013734485343840154221605853412503154993878886490867020934777530894593416337175399865065870417717658815158195790" )
- -= QCA::BigInteger( "1456031684988128870809574635750149625240648487837308" );
- QCOMPARE( result.toString(), QString( "-390149102941948621568479722346940666704376013734485343840154221605853412503154993878886490867020934778986926278404466046209439701620567342899463646033098" ) );
- QCOMPARE( result, QCA::BigInteger( "-390149102941948621568479722346940666704376013734485343840154221605853412503154993878886490867020934778986926278404466046209439701620567342899463646033098" ) );
-
- result = QCA::BigInteger( "7473774301764883450943" )
- -= QCA::BigInteger( "-26256369859367890755157372820052387483402723790185562908491933812453" );
- QCOMPARE( result.toString(), QString( "26256369859367890755157372820052387483402723797659337210256817263396" ) );
- QCOMPARE( result, QCA::BigInteger( "26256369859367890755157372820052387483402723797659337210256817263396" ) );
-
- result = QCA::BigInteger( "36246343251214922024139186757009148849295485593397952003237349660142296147421019916619944353877490544706223768684758263065399016597969" )
- -= QCA::BigInteger( "2574427901445527995149185461475228850098549655325125750771680756403104624569522792792597223218143154924988199562355517064962665954307425375180" );
- QCOMPARE( result.toString(), QString( "-2574427865199184743934263437336042093089400806029640157373728753165754964427226645371577306598198801047497654856131748380204402888908408777211" ) );
- QCOMPARE( result, QCA::BigInteger( "-2574427865199184743934263437336042093089400806029640157373728753165754964427226645371577306598198801047497654856131748380204402888908408777211" ) );
-
- result = QCA::BigInteger( "30129746266682790628283889040897642317014108334116727" )
- -= QCA::BigInteger( "-1580480523895398762563721715474380903630073871362143915864398724834897608423" );
- QCOMPARE( result.toString(), QString( "1580480523895398762563751845220647586420702155251184813506715738943231725150" ) );
- QCOMPARE( result, QCA::BigInteger( "1580480523895398762563751845220647586420702155251184813506715738943231725150" ) );
-
- result = QCA::BigInteger( "-4614735863800137951667138933166372061" )
- -= QCA::BigInteger( "87175694379075561307234146162193190462135078700346746992273" );
- QCOMPARE( result.toString(), QString( "-87175694379075561307238760898056990600086745839279913364334" ) );
- QCOMPARE( result, QCA::BigInteger( "-87175694379075561307238760898056990600086745839279913364334" ) );
-
- result = QCA::BigInteger( "-3753904" )
- -= QCA::BigInteger( "-11269137783745339515071988205310702154422777729974" );
- QCOMPARE( result.toString(), QString( "11269137783745339515071988205310702154422773976070" ) );
- QCOMPARE( result, QCA::BigInteger( "11269137783745339515071988205310702154422773976070" ) );
-
- result = QCA::BigInteger( "592523948495379440082021279738170088402918858455470050140652787171830058864932939900794505955437856926902975870288" )
- -= QCA::BigInteger( "-205854658295495452479104108497931263758143158076949293929661651111" );
- QCOMPARE( result.toString(), QString( "592523948495379440082021279738170088402918858455675904798948282624309162973430871164552649113514806220832637521399" ) );
- QCOMPARE( result, QCA::BigInteger( "592523948495379440082021279738170088402918858455675904798948282624309162973430871164552649113514806220832637521399" ) );
-
- result = QCA::BigInteger( "-33993701617495591491176844355" )
- -= QCA::BigInteger( "3438065097398894672826284379125235190693300918673662774192379185002391232383325160416036963599856704698280" );
- QCOMPARE( result.toString(), QString( "-3438065097398894672826284379125235190693300918673662774192379185002391232383359154117654459191347881542635" ) );
- QCOMPARE( result, QCA::BigInteger( "-3438065097398894672826284379125235190693300918673662774192379185002391232383359154117654459191347881542635" ) );
-
- result = QCA::BigInteger( "26876428790838270949718735111909136008255051776703" )
- -= QCA::BigInteger( "-1781128112966810373286192008831149275546995635268767241859967609117529616872536681035700534316457543887601645022" );
- QCOMPARE( result.toString(), QString( "1781128112966810373286192008831149275546995635268767241859967635993958407710807630754435646225593552142653421725" ) );
- QCOMPARE( result, QCA::BigInteger( "1781128112966810373286192008831149275546995635268767241859967635993958407710807630754435646225593552142653421725" ) );
-
- result = QCA::BigInteger( "2059771092932179758019770618974659367350250375647433386639519387\
-69317693429941871882153770641334267205446421916220398066553188" )
- -= QCA::BigInteger( "3342500267594994347156312297990633112620923791590960237694328174171473763026" );
- QCOMPARE( result.toString(), QString( "205977109293217975801977061897465936735025037564739996163684343774970537117643881249041149717542676245208727588046226592790162" ) );
- QCOMPARE( result, QCA::BigInteger( "205977109293217975801977061897465936735025037564739996163684343774970537117643881249041149717542676245208727588046226592790162" ) );
-
- result = QCA::BigInteger( "5545520403000578843599072515870982842927227412121917598877293331575380404618111609" )
- -= QCA::BigInteger( "5991287327241003718821424770352575362437680738923552868139860461945460339860477495902" );
- QCOMPARE( result.toString(), QString( "-5985741806838003139977825697836704379594753511511430950540983168613884959455859384293" ) );
- QCOMPARE( result, QCA::BigInteger( "-5985741806838003139977825697836704379594753511511430950540983168613884959455859384293" ) );
-
- result = QCA::BigInteger( "248039029608125071340" )
- -= QCA::BigInteger( "3664608673" );
- QCOMPARE( result.toString(), QString( "248039029604460462667" ) );
- QCOMPARE( result, QCA::BigInteger( "248039029604460462667" ) );
-
- result = QCA::BigInteger( "15425705711415937103627" )
- -= QCA::BigInteger( "-1435504065517745703440045276868982910754081405474123003767554211132837427846963435621523810229738262235546179779885824" );
- QCOMPARE( result.toString(), QString( "1435504065517745703440045276868982910754081405474123003767554211132837427846963435621523810229753687941257595716989451" ) );
- QCOMPARE( result, QCA::BigInteger( "1435504065517745703440045276868982910754081405474123003767554211132837427846963435621523810229753687941257595716989451" ) );
-
- result = QCA::BigInteger( "50882847205108645607281568922683652688671738236030732914347600821086" )
- -= QCA::BigInteger( "12176160963158" );
- QCOMPARE( result.toString(), QString( "50882847205108645607281568922683652688671738236030732902171439857928" ) );
- QCOMPARE( result, QCA::BigInteger( "50882847205108645607281568922683652688671738236030732902171439857928" ) );
-
- result = QCA::BigInteger( "-35426518565985818947670047877033022885542172461973566228509771053416312543201815881190953762207629232160412058300173038824256783171761132" )
- -= QCA::BigInteger( "-4864862607366468843184694353123830534588538011093812418208808135799" );
- QCOMPARE( result.toString(), QString( "-35426518565985818947670047877033022885542172461973566228509771053416307678339208514722110577513276108329877469762161945011838574363625333" ) );
- QCOMPARE( result, QCA::BigInteger( "-35426518565985818947670047877033022885542172461973566228509771053416307678339208514722110577513276108329877469762161945011838574363625333" ) );
-
- result = QCA::BigInteger( "-1428596214712268310382144828171384812520179141608121870013556402879770424002218157546599921571184" )
- -= QCA::BigInteger( "-4054101" );
- QCOMPARE( result.toString(), QString( "-1428596214712268310382144828171384812520179141608121870013556402879770424002218157546599917517083" ) );
- QCOMPARE( result, QCA::BigInteger( "-1428596214712268310382144828171384812520179141608121870013556402879770424002218157546599917517083" ) );
-
- result = QCA::BigInteger( "-200931" )
- -= QCA::BigInteger( "-44558802460130495759482832913160717791151786725570519475449607659705171682283111490834930835045735142966847483009157514950177565952218520297258834187372" );
- QCOMPARE( result.toString(), QString( "44558802460130495759482832913160717791151786725570519475449607659705171682283111490834930835045735142966847483009157514950177565952218520297258833986441" ) );
- QCOMPARE( result, QCA::BigInteger( "44558802460130495759482832913160717791151786725570519475449607659705171682283111490834930835045735142966847483009157514950177565952218520297258833986441" ) );
-
- result = QCA::BigInteger( "105704314890799915321259" )
- -= QCA::BigInteger( "827923545945076415574912438499169814414563066877494100831657761190490697473854369477784874118787495351405549803329615347120938123226038208" );
- QCOMPARE( result.toString(), QString( "-827923545945076415574912438499169814414563066877494100831657761190490697473854369477784874118787495351405549803329509642806047323310716949" ) );
- QCOMPARE( result, QCA::BigInteger( "-827923545945076415574912438499169814414563066877494100831657761190490697473854369477784874118787495351405549803329509642806047323310716949" ) );
-
- result = QCA::BigInteger( "1448979433940064018828919290452280235308901982649341" )
- -= QCA::BigInteger( "303926827425887072291878308433008512899006711759770318009" );
- QCOMPARE( result.toString(), QString( "-303925378446453132227859479513718060618771402857787668668" ) );
- QCOMPARE( result, QCA::BigInteger( "-303925378446453132227859479513718060618771402857787668668" ) );
-
- result = QCA::BigInteger( "-243237595290235750457450892290434789864" )
- -= QCA::BigInteger( "19817702076334276402981273067417321098467533300947463865383702005126562800253466403934608765512316565811954342319565128573969" );
- QCOMPARE( result.toString(), QString( "-19817702076334276402981273067417321098467533300947463865383702005126562800253466403934852003107606801562411793211855563363833" ) );
- QCOMPARE( result, QCA::BigInteger( "-19817702076334276402981273067417321098467533300947463865383702005126562800253466403934852003107606801562411793211855563363833" ) );
-
- result = QCA::BigInteger( "294037338365659932242802023634" )
- -= QCA::BigInteger( "4401245995535867764294876849802142926077599828776505639975554254356763769548465" );
- QCOMPARE( result.toString(), QString( "-4401245995535867764294876849802142926077599828776211602637188594424520967524831" ) );
- QCOMPARE( result, QCA::BigInteger( "-4401245995535867764294876849802142926077599828776211602637188594424520967524831" ) );
-
- result = QCA::BigInteger( "7303853946195223307036710881687367004566538357189824031021831088365362" )
- -= QCA::BigInteger( "119286025999378935715794641163321741" );
- QCOMPARE( result.toString(), QString( "7303853946195223307036710881687366885280512357810888315227189925043621" ) );
- QCOMPARE( result, QCA::BigInteger( "7303853946195223307036710881687366885280512357810888315227189925043621" ) );
-
- result = QCA::BigInteger( "571167355343287235687602610714110416067426289363505412908804940696550592413192300554016875" )
- -= QCA::BigInteger( "15872188842802631759540597" );
- QCOMPARE( result.toString(), QString( "571167355343287235687602610714110416067426289363505412908804940680678403570389668794476278" ) );
- QCOMPARE( result, QCA::BigInteger( "571167355343287235687602610714110416067426289363505412908804940680678403570389668794476278" ) );
-
- result = QCA::BigInteger( "1002240129784524388754179399598974973256811336031329881209395070412702275169416754240" )
- -= QCA::BigInteger( "59429482478860591343145393540420033516478305952872349006715789477946474753657206800070515207967709079933420746952" );
- QCOMPARE( result.toString(), QString( "-59429482478860591343145393539417793386693781564118169607116814504689663417625876918861120137555006804764003992712" ) );
- QCOMPARE( result, QCA::BigInteger( "-59429482478860591343145393539417793386693781564118169607116814504689663417625876918861120137555006804764003992712" ) );
-
- result = QCA::BigInteger( "1370431648825444838359719050380239722263203134555431526491525074601463042144798545817957389" )
- -= QCA::BigInteger( "3473869878" );
- QCOMPARE( result.toString(), QString( "1370431648825444838359719050380239722263203134555431526491525074601463042144798542344087511" ) );
- QCOMPARE( result, QCA::BigInteger( "1370431648825444838359719050380239722263203134555431526491525074601463042144798542344087511" ) );
-
- result = QCA::BigInteger( "8548280229254726209" )
- -= QCA::BigInteger( "33066125035269904981849320434016892734943145935582141989968280846973981913056248918" );
- QCOMPARE( result.toString(), QString( "-33066125035269904981849320434016892734943145935582141989968280838425701683801522709" ) );
- QCOMPARE( result, QCA::BigInteger( "-33066125035269904981849320434016892734943145935582141989968280838425701683801522709" ) );
-
- result = QCA::BigInteger( "-19023558832687506489508150795966332175990129963029928958584170111759630293276939647334082100169102538364437859846398095065171936899503" )
- -= QCA::BigInteger( "24899271127523545342283468762809653407638631966220124695751976894193103779443050843040771191227522843088079031762445684377195650493065096847292797" );
- QCOMPARE( result.toString(), QString( "-24899271127542568901116156269299161558434598298396114825715006823151687949554810473334048130874856925188248134300810122237042048588130268784192300" ) );
- QCOMPARE( result, QCA::BigInteger( "-24899271127542568901116156269299161558434598298396114825715006823151687949554810473334048130874856925188248134300810122237042048588130268784192300" ) );
-
- result = QCA::BigInteger( "-1800353575522706389288305623797196690530870204356722928042061228497437075035917720399302198953687023" )
- -= QCA::BigInteger( "-11875668261530466053708538730940776412171106483072624532757177471384128016458332544642788404765469924496127460164" );
- QCOMPARE( result.toString(), QString( "11875668261528665700133016024551488106547309286382093662552820748456085955229835107567752487045070622297173773141" ) );
- QCOMPARE( result, QCA::BigInteger( "11875668261528665700133016024551488106547309286382093662552820748456085955229835107567752487045070622297173773141" ) );
-
- result = QCA::BigInteger( "-29861551039945217879" )
- -= QCA::BigInteger( "1113473025916855642353456146647542930581669082348409639697282960877889226500319996380838232582376232872868947624793789212829885934" );
- QCOMPARE( result.toString(), QString( "-1113473025916855642353456146647542930581669082348409639697282960877889226500319996380838232582376232872868947654655340252775103813" ) );
- QCOMPARE( result, QCA::BigInteger( "-1113473025916855642353456146647542930581669082348409639697282960877889226500319996380838232582376232872868947654655340252775103813" ) );
-
- result = QCA::BigInteger( "565532963656761153838218277564957917658707297649757920676303301655328103665512287797108510139837643506491641987188791892506290" )
- -= QCA::BigInteger( "-2188105671531473889939411772533707" );
- QCOMPARE( result.toString(), QString( "565532963656761153838218277564957917658707297649757920676303301655328103665512287797108510142025749178023115877128203665039997" ) );
- QCOMPARE( result, QCA::BigInteger( "565532963656761153838218277564957917658707297649757920676303301655328103665512287797108510142025749178023115877128203665039997" ) );
-
- result = QCA::BigInteger( "-349535960680522202843083381184496349093812380954435872337802226" )
- -= QCA::BigInteger( "-1829600726218222026679938" );
- QCOMPARE( result.toString(), QString( "-349535960680522202843083381184496349091982780228217650311122288" ) );
- QCOMPARE( result, QCA::BigInteger( "-349535960680522202843083381184496349091982780228217650311122288" ) );
-
- result = QCA::BigInteger( "-1" ) -= QCA::BigInteger( "-6726974989587128275" );
- QCOMPARE( result.toString(), QString( "6726974989587128274" ) );
- QCOMPARE( result, QCA::BigInteger( "6726974989587128274" ) );
-
- result = QCA::BigInteger( "-107142709838121196902389095205618516687047338619382145236348309762148611647954748824" )
- -= QCA::BigInteger( "42484103615491" );
- QCOMPARE( result.toString(), QString( "-107142709838121196902389095205618516687047338619382145236348309762148654132058364315" ) );
- QCOMPARE( result, QCA::BigInteger( "-107142709838121196902389095205618516687047338619382145236348309762148654132058364315" ) );
-
- result = QCA::BigInteger( "-90546630430085769764839607528116121381848878494574360812027599640018921358040178215575723" )
- -= QCA::BigInteger( "-118922408531468986902800063237122125617455464103913195171141030774109638861272017660698580914239435114280434761425243" );
- QCOMPARE( result.toString(), QString( "118922408531468986902800063146575495187369694339073587643024909392260760366697656848670981274220513756240256545849520" ) );
- QCOMPARE( result, QCA::BigInteger( "118922408531468986902800063146575495187369694339073587643024909392260760366697656848670981274220513756240256545849520" ) );
-
- result = QCA::BigInteger( "-5545044667082427128801726416727657360001588430113578182850657573063241939882570324573086267287272360432363387213743735507218270373633222520429" )
- -= QCA::BigInteger( "-151423255459028627628896755237194376177115" );
- QCOMPARE( result.toString(), QString( "-5545044667082427128801726416727657360001588430113578182850657573063241939882570324573086267287272360280940131754715107878321515136438846343314" ) );
- QCOMPARE( result, QCA::BigInteger( "-5545044667082427128801726416727657360001588430113578182850657573063241939882570324573086267287272360280940131754715107878321515136438846343314" ) );
-
- result = QCA::BigInteger( "-5247636471953421659649611318164848102069" )
- -= QCA::BigInteger( "-4024324110573096565232590473170599175885004" );
- QCOMPARE( result.toString(), QString( "4019076474101143143572940861852434327782935" ) );
- QCOMPARE( result, QCA::BigInteger( "4019076474101143143572940861852434327782935" ) );
-
- result = QCA::BigInteger( "39412892606015043322484854253879371723186457838590224795040178472832" )
- -= QCA::BigInteger( "-5038321321957452145034687815432890684825466579123474921848465393400312" );
- QCOMPARE( result.toString(), QString( "5077734214563467188357172669686770056548653036962065146643505571873144" ) );
- QCOMPARE( result, QCA::BigInteger( "5077734214563467188357172669686770056548653036962065146643505571873144" ) );
-
- result = QCA::BigInteger( "-55979414588009227035683624505208766753187469727799640277204274207843317583292736333912783829528270272642583004969175230274821" )
- -= QCA::BigInteger( "-109633110576212669339535976775635762395927171313557427036242111476016398579345366908401334025571265714128108308032073779442181369365924213118258269679" );
- QCOMPARE( result.toString(), QString( "109633110576212669339535920796221174386700135629932921827475358288546670779705089704127126182253682421391774395248244251171908726782919243943027994858" ) );
- QCOMPARE( result, QCA::BigInteger( "109633110576212669339535920796221174386700135629932921827475358288546670779705089704127126182253682421391774395248244251171908726782919243943027994858" ) );
-
- result = QCA::BigInteger( "-38752353898173389347479216285772999906325286421302866854350737050533204094183249691110" )
- -= QCA::BigInteger( "2428819407377764342156426895396654728835493564788997075896393065230009911546390816091652653701035085361" );
- QCOMPARE( result.toString(), QString( "-2428819407377764380908780793570044076314709850561996982221679486532876765897127866624856747884284776471" ) );
- QCOMPARE( result, QCA::BigInteger( "-2428819407377764380908780793570044076314709850561996982221679486532876765897127866624856747884284776471" ) );
-
- result = QCA::BigInteger( "-2784579005241382005249492720344" )
- -= QCA::BigInteger( "-164204542616919252351131740123094674" );
- QCOMPARE( result.toString(), QString( "164201758037914010969126490630374330" ) );
- QCOMPARE( result, QCA::BigInteger( "164201758037914010969126490630374330" ) );
-
- result = QCA::BigInteger( "200948857420871544747808060972375039052401280822505804851732868100" )
- -= QCA::BigInteger( "-795957177479360455258269298038670876462147576765875895105714" );
- QCOMPARE( result.toString(), QString( "200949653378049024108263319241673077723277742970082570727627973814" ) );
- QCOMPARE( result, QCA::BigInteger( "200949653378049024108263319241673077723277742970082570727627973814" ) );
-
- result = QCA::BigInteger( "217570540819" )
- -= QCA::BigInteger( "121955083597720420983384282166693307394185530431368476834980748302158718406063500763434561937200696970170700" );
- QCOMPARE( result.toString(), QString( "-121955083597720420983384282166693307394185530431368476834980748302158718406063500763434561937200479399629881" ) );
- QCOMPARE( result, QCA::BigInteger( QString("-121955083597720420983384282166693307394185530431368476834980748302158718406063500763434561937200479399629881" ) ) );
-
- result = QCA::BigInteger( QString("2335319252198456765380587281374076367944") )
- -= QCA::BigInteger( QString("-4500271") );
- QCOMPARE( result, QCA::BigInteger( QString( "2335319252198456765380587281374080868215" ) ) );
-
- result = QCA::BigInteger( QString("-393694614027544181700073367147249369966344727230221941008713805434207925307052598" ) )
- -= QCA::BigInteger( QString("-153972676737062409261153899615588515236137907791841623991260363840680295565313157972489168132345521780658007459602823125797806770" ) );
- QCOMPARE( result.toString(), QString( "153972676737062409261153899615588515236137907791447929377232819658980222198165908602522823405115299839649293654168615200490754172" ) );
- QCOMPARE( result, QCA::BigInteger( QString("153972676737062409261153899615588515236137907791447929377232819658980222198165908602522823405115299839649293654168615200490754172" ) ) );
-
- result = QCA::BigInteger( QString("114832549702862263167") )
- -= QCA::BigInteger( QString("12921864907229959558745276418830287875386673600892281022286597165773569473039953984775959232814911435097412913078625") );
- QCOMPARE( result.toString(), QString( "-12921864907229959558745276418830287875386673600892281022286597165773569473039953984775959232814796602547710050815458" ) );
- QCOMPARE( result, QCA::BigInteger( QString( "-12921864907229959558745276418830287875386673600892281022286597165773569473039953984775959232814796602547710050815458" ) ) );
-
- result = QCA::BigInteger( QString( "6489502346837936889305337487724547956628371915228387374094443896266362105931065153072983425911767580294076594078932835008494777866083" ) )
- -= QCA::BigInteger( QString( "1099205476533612407829257935144627350486541654788267826664706620630745291371323154513322608446957760026881954001581" ) );
- QCOMPARE( result.toString(), QString( "6489502346837936888206132011190935548799113980083760023607902241478094279266358532442238134540444425780753985631975074981612823864502" ) );
- QCOMPARE( result, QCA::BigInteger( QString("6489502346837936888206132011190935548799113980083760023607902241478094279266358532442238134540444425780753985631975074981612823864502" ) ) );
-
- result = QCA::BigInteger( QString("169991144123958754253801313173662977337850870273358378951640521601077152994474340806917796870911557233689087716056557" ) )
- -= QCA::BigInteger( QString("-15409167") );
- QCOMPARE( result.toString(), QString( "169991144123958754253801313173662977337850870273358378951640521601077152994474340806917796870911557233689087731465724" ) );
- QCOMPARE( result, QCA::BigInteger( QString("169991144123958754253801313173662977337850870273358378951640521601077152994474340806917796870911557233689087731465724") ) );
+ result = QCA::BigInteger("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095")
+ -= QCA::BigInteger("1");
+ QCOMPARE(result.toString(), QString("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084094"));
+ QCOMPARE(result, QCA::BigInteger("13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084094"));
+
+ result = QCA::BigInteger("89094716573076464980713547115099137014719483620102078148320806773871083148864")
+ -= QCA::BigInteger("49505213825110728957828173754776257356620450607893971553289366249708672306581");
+ QCOMPARE(result.toString(), QString("39589502747965736022885373360322879658099033012208106595031440524162410842283"));
+ QCOMPARE(result, QCA::BigInteger("39589502747965736022885373360322879658099033012208106595031440524162410842283"));
+
+ result = QCA::BigInteger("65894747009896006767807716946835412110318548717263922395390971078905789585431")
+ -= QCA::BigInteger("3884269741925508225990715416862047284194603799902650748631039608684367281358");
+ QCOMPARE(result.toString(), QString("62010477267970498541817001529973364826123944917361271646759931470221422304073"));
+ QCOMPARE(result, QCA::BigInteger("62010477267970498541817001529973364826123944917361271646759931470221422304073"));
+
+ result = QCA::BigInteger("5950196396451977566902121301707054218364717196893101360011491777761952253736964709165962613347710607164178682987783755894811024288429224592316636383")
+ -= QCA::BigInteger("8750653273562160761286422180115618621879821429145276197424652349306577311499807887070429373153777028581165316131683348567");
+ QCOMPARE(result.toString(), QString("5950196396451977566902121292956400944802556435606679179895873155882130824591688511741310264041133295664370795917354382741033995707263908460633287816"));
+ QCOMPARE(result, QCA::BigInteger("5950196396451977566902121292956400944802556435606679179895873155882130824591688511741310264041133295664370795917354382741033995707263908460633287816"));
+
+ result = QCA::BigInteger("9815262808265519920770782360080149146267723690")
+ -= QCA::BigInteger("14067005768891609281364919358115291341352189918255780397560060748765650205261663193732434161580120817");
+ QCOMPARE(result.toString(), QString("-14067005768891609281364919358115291341352189918255780387744797940500130284490880833652285015312397127"));
+ QCOMPARE(result, QCA::BigInteger("-14067005768891609281364919358115291341352189918255780387744797940500130284490880833652285015312397127"));
+
+ result = QCA::BigInteger("-390149102941948621568479722346940666704376013734485343840154221605853412503154993878886490867020934777530894593416337175399865065870417717658815158195790")
+ -= QCA::BigInteger("1456031684988128870809574635750149625240648487837308");
+ QCOMPARE(result.toString(), QString("-390149102941948621568479722346940666704376013734485343840154221605853412503154993878886490867020934778986926278404466046209439701620567342899463646033098"));
+ QCOMPARE(result, QCA::BigInteger("-390149102941948621568479722346940666704376013734485343840154221605853412503154993878886490867020934778986926278404466046209439701620567342899463646033098"));
+
+ result = QCA::BigInteger("7473774301764883450943")
+ -= QCA::BigInteger("-26256369859367890755157372820052387483402723790185562908491933812453");
+ QCOMPARE(result.toString(), QString("26256369859367890755157372820052387483402723797659337210256817263396"));
+ QCOMPARE(result, QCA::BigInteger("26256369859367890755157372820052387483402723797659337210256817263396"));
+
+ result = QCA::BigInteger("36246343251214922024139186757009148849295485593397952003237349660142296147421019916619944353877490544706223768684758263065399016597969")
+ -= QCA::BigInteger("2574427901445527995149185461475228850098549655325125750771680756403104624569522792792597223218143154924988199562355517064962665954307425375180");
+ QCOMPARE(result.toString(), QString("-2574427865199184743934263437336042093089400806029640157373728753165754964427226645371577306598198801047497654856131748380204402888908408777211"));
+ QCOMPARE(result, QCA::BigInteger("-2574427865199184743934263437336042093089400806029640157373728753165754964427226645371577306598198801047497654856131748380204402888908408777211"));
+
+ result = QCA::BigInteger("30129746266682790628283889040897642317014108334116727")
+ -= QCA::BigInteger("-1580480523895398762563721715474380903630073871362143915864398724834897608423");
+ QCOMPARE(result.toString(), QString("1580480523895398762563751845220647586420702155251184813506715738943231725150"));
+ QCOMPARE(result, QCA::BigInteger("1580480523895398762563751845220647586420702155251184813506715738943231725150"));
+
+ result = QCA::BigInteger("-4614735863800137951667138933166372061")
+ -= QCA::BigInteger("87175694379075561307234146162193190462135078700346746992273");
+ QCOMPARE(result.toString(), QString("-87175694379075561307238760898056990600086745839279913364334"));
+ QCOMPARE(result, QCA::BigInteger("-87175694379075561307238760898056990600086745839279913364334"));
+
+ result = QCA::BigInteger("-3753904")
+ -= QCA::BigInteger("-11269137783745339515071988205310702154422777729974");
+ QCOMPARE(result.toString(), QString("11269137783745339515071988205310702154422773976070"));
+ QCOMPARE(result, QCA::BigInteger("11269137783745339515071988205310702154422773976070"));
+
+ result = QCA::BigInteger("592523948495379440082021279738170088402918858455470050140652787171830058864932939900794505955437856926902975870288")
+ -= QCA::BigInteger("-205854658295495452479104108497931263758143158076949293929661651111");
+ QCOMPARE(result.toString(), QString("592523948495379440082021279738170088402918858455675904798948282624309162973430871164552649113514806220832637521399"));
+ QCOMPARE(result, QCA::BigInteger("592523948495379440082021279738170088402918858455675904798948282624309162973430871164552649113514806220832637521399"));
+
+ result = QCA::BigInteger("-33993701617495591491176844355")
+ -= QCA::BigInteger("3438065097398894672826284379125235190693300918673662774192379185002391232383325160416036963599856704698280");
+ QCOMPARE(result.toString(), QString("-3438065097398894672826284379125235190693300918673662774192379185002391232383359154117654459191347881542635"));
+ QCOMPARE(result, QCA::BigInteger("-3438065097398894672826284379125235190693300918673662774192379185002391232383359154117654459191347881542635"));
+
+ result = QCA::BigInteger("26876428790838270949718735111909136008255051776703")
+ -= QCA::BigInteger("-1781128112966810373286192008831149275546995635268767241859967609117529616872536681035700534316457543887601645022");
+ QCOMPARE(result.toString(), QString("1781128112966810373286192008831149275546995635268767241859967635993958407710807630754435646225593552142653421725"));
+ QCOMPARE(result, QCA::BigInteger("1781128112966810373286192008831149275546995635268767241859967635993958407710807630754435646225593552142653421725"));
+
+ result = QCA::BigInteger("2059771092932179758019770618974659367350250375647433386639519387\
+69317693429941871882153770641334267205446421916220398066553188")
+ -= QCA::BigInteger("3342500267594994347156312297990633112620923791590960237694328174171473763026");
+ QCOMPARE(result.toString(), QString("205977109293217975801977061897465936735025037564739996163684343774970537117643881249041149717542676245208727588046226592790162"));
+ QCOMPARE(result, QCA::BigInteger("205977109293217975801977061897465936735025037564739996163684343774970537117643881249041149717542676245208727588046226592790162"));
+
+ result = QCA::BigInteger("5545520403000578843599072515870982842927227412121917598877293331575380404618111609")
+ -= QCA::BigInteger("5991287327241003718821424770352575362437680738923552868139860461945460339860477495902");
+ QCOMPARE(result.toString(), QString("-5985741806838003139977825697836704379594753511511430950540983168613884959455859384293"));
+ QCOMPARE(result, QCA::BigInteger("-5985741806838003139977825697836704379594753511511430950540983168613884959455859384293"));
+
+ result = QCA::BigInteger("248039029608125071340")
+ -= QCA::BigInteger("3664608673");
+ QCOMPARE(result.toString(), QString("248039029604460462667"));
+ QCOMPARE(result, QCA::BigInteger("248039029604460462667"));
+
+ result = QCA::BigInteger("15425705711415937103627")
+ -= QCA::BigInteger("-1435504065517745703440045276868982910754081405474123003767554211132837427846963435621523810229738262235546179779885824");
+ QCOMPARE(result.toString(), QString("1435504065517745703440045276868982910754081405474123003767554211132837427846963435621523810229753687941257595716989451"));
+ QCOMPARE(result, QCA::BigInteger("1435504065517745703440045276868982910754081405474123003767554211132837427846963435621523810229753687941257595716989451"));
+
+ result = QCA::BigInteger("50882847205108645607281568922683652688671738236030732914347600821086")
+ -= QCA::BigInteger("12176160963158");
+ QCOMPARE(result.toString(), QString("50882847205108645607281568922683652688671738236030732902171439857928"));
+ QCOMPARE(result, QCA::BigInteger("50882847205108645607281568922683652688671738236030732902171439857928"));
+
+ result = QCA::BigInteger("-35426518565985818947670047877033022885542172461973566228509771053416312543201815881190953762207629232160412058300173038824256783171761132")
+ -= QCA::BigInteger("-4864862607366468843184694353123830534588538011093812418208808135799");
+ QCOMPARE(result.toString(), QString("-35426518565985818947670047877033022885542172461973566228509771053416307678339208514722110577513276108329877469762161945011838574363625333"));
+ QCOMPARE(result, QCA::BigInteger("-35426518565985818947670047877033022885542172461973566228509771053416307678339208514722110577513276108329877469762161945011838574363625333"));
+
+ result = QCA::BigInteger("-1428596214712268310382144828171384812520179141608121870013556402879770424002218157546599921571184")
+ -= QCA::BigInteger("-4054101");
+ QCOMPARE(result.toString(), QString("-1428596214712268310382144828171384812520179141608121870013556402879770424002218157546599917517083"));
+ QCOMPARE(result, QCA::BigInteger("-1428596214712268310382144828171384812520179141608121870013556402879770424002218157546599917517083"));
+
+ result = QCA::BigInteger("-200931")
+ -= QCA::BigInteger("-44558802460130495759482832913160717791151786725570519475449607659705171682283111490834930835045735142966847483009157514950177565952218520297258834187372");
+ QCOMPARE(result.toString(), QString("44558802460130495759482832913160717791151786725570519475449607659705171682283111490834930835045735142966847483009157514950177565952218520297258833986441"));
+ QCOMPARE(result, QCA::BigInteger("44558802460130495759482832913160717791151786725570519475449607659705171682283111490834930835045735142966847483009157514950177565952218520297258833986441"));
+
+ result = QCA::BigInteger("105704314890799915321259")
+ -= QCA::BigInteger("827923545945076415574912438499169814414563066877494100831657761190490697473854369477784874118787495351405549803329615347120938123226038208");
+ QCOMPARE(result.toString(), QString("-827923545945076415574912438499169814414563066877494100831657761190490697473854369477784874118787495351405549803329509642806047323310716949"));
+ QCOMPARE(result, QCA::BigInteger("-827923545945076415574912438499169814414563066877494100831657761190490697473854369477784874118787495351405549803329509642806047323310716949"));
+
+ result = QCA::BigInteger("1448979433940064018828919290452280235308901982649341")
+ -= QCA::BigInteger("303926827425887072291878308433008512899006711759770318009");
+ QCOMPARE(result.toString(), QString("-303925378446453132227859479513718060618771402857787668668"));
+ QCOMPARE(result, QCA::BigInteger("-303925378446453132227859479513718060618771402857787668668"));
+
+ result = QCA::BigInteger("-243237595290235750457450892290434789864")
+ -= QCA::BigInteger("19817702076334276402981273067417321098467533300947463865383702005126562800253466403934608765512316565811954342319565128573969");
+ QCOMPARE(result.toString(), QString("-19817702076334276402981273067417321098467533300947463865383702005126562800253466403934852003107606801562411793211855563363833"));
+ QCOMPARE(result, QCA::BigInteger("-19817702076334276402981273067417321098467533300947463865383702005126562800253466403934852003107606801562411793211855563363833"));
+
+ result = QCA::BigInteger("294037338365659932242802023634")
+ -= QCA::BigInteger("4401245995535867764294876849802142926077599828776505639975554254356763769548465");
+ QCOMPARE(result.toString(), QString("-4401245995535867764294876849802142926077599828776211602637188594424520967524831"));
+ QCOMPARE(result, QCA::BigInteger("-4401245995535867764294876849802142926077599828776211602637188594424520967524831"));
+
+ result = QCA::BigInteger("7303853946195223307036710881687367004566538357189824031021831088365362")
+ -= QCA::BigInteger("119286025999378935715794641163321741");
+ QCOMPARE(result.toString(), QString("7303853946195223307036710881687366885280512357810888315227189925043621"));
+ QCOMPARE(result, QCA::BigInteger("7303853946195223307036710881687366885280512357810888315227189925043621"));
+
+ result = QCA::BigInteger("571167355343287235687602610714110416067426289363505412908804940696550592413192300554016875")
+ -= QCA::BigInteger("15872188842802631759540597");
+ QCOMPARE(result.toString(), QString("571167355343287235687602610714110416067426289363505412908804940680678403570389668794476278"));
+ QCOMPARE(result, QCA::BigInteger("571167355343287235687602610714110416067426289363505412908804940680678403570389668794476278"));
+
+ result = QCA::BigInteger("1002240129784524388754179399598974973256811336031329881209395070412702275169416754240")
+ -= QCA::BigInteger("59429482478860591343145393540420033516478305952872349006715789477946474753657206800070515207967709079933420746952");
+ QCOMPARE(result.toString(), QString("-59429482478860591343145393539417793386693781564118169607116814504689663417625876918861120137555006804764003992712"));
+ QCOMPARE(result, QCA::BigInteger("-59429482478860591343145393539417793386693781564118169607116814504689663417625876918861120137555006804764003992712"));
+
+ result = QCA::BigInteger("1370431648825444838359719050380239722263203134555431526491525074601463042144798545817957389")
+ -= QCA::BigInteger("3473869878");
+ QCOMPARE(result.toString(), QString("1370431648825444838359719050380239722263203134555431526491525074601463042144798542344087511"));
+ QCOMPARE(result, QCA::BigInteger("1370431648825444838359719050380239722263203134555431526491525074601463042144798542344087511"));
+
+ result = QCA::BigInteger("8548280229254726209")
+ -= QCA::BigInteger("33066125035269904981849320434016892734943145935582141989968280846973981913056248918");
+ QCOMPARE(result.toString(), QString("-33066125035269904981849320434016892734943145935582141989968280838425701683801522709"));
+ QCOMPARE(result, QCA::BigInteger("-33066125035269904981849320434016892734943145935582141989968280838425701683801522709"));
+
+ result = QCA::BigInteger("-19023558832687506489508150795966332175990129963029928958584170111759630293276939647334082100169102538364437859846398095065171936899503")
+ -= QCA::BigInteger("24899271127523545342283468762809653407638631966220124695751976894193103779443050843040771191227522843088079031762445684377195650493065096847292797");
+ QCOMPARE(result.toString(), QString("-24899271127542568901116156269299161558434598298396114825715006823151687949554810473334048130874856925188248134300810122237042048588130268784192300"));
+ QCOMPARE(result, QCA::BigInteger("-24899271127542568901116156269299161558434598298396114825715006823151687949554810473334048130874856925188248134300810122237042048588130268784192300"));
+
+ result = QCA::BigInteger("-1800353575522706389288305623797196690530870204356722928042061228497437075035917720399302198953687023")
+ -= QCA::BigInteger("-11875668261530466053708538730940776412171106483072624532757177471384128016458332544642788404765469924496127460164");
+ QCOMPARE(result.toString(), QString("11875668261528665700133016024551488106547309286382093662552820748456085955229835107567752487045070622297173773141"));
+ QCOMPARE(result, QCA::BigInteger("11875668261528665700133016024551488106547309286382093662552820748456085955229835107567752487045070622297173773141"));
+
+ result = QCA::BigInteger("-29861551039945217879")
+ -= QCA::BigInteger("1113473025916855642353456146647542930581669082348409639697282960877889226500319996380838232582376232872868947624793789212829885934");
+ QCOMPARE(result.toString(), QString("-1113473025916855642353456146647542930581669082348409639697282960877889226500319996380838232582376232872868947654655340252775103813"));
+ QCOMPARE(result, QCA::BigInteger("-1113473025916855642353456146647542930581669082348409639697282960877889226500319996380838232582376232872868947654655340252775103813"));
+
+ result = QCA::BigInteger("565532963656761153838218277564957917658707297649757920676303301655328103665512287797108510139837643506491641987188791892506290")
+ -= QCA::BigInteger("-2188105671531473889939411772533707");
+ QCOMPARE(result.toString(), QString("565532963656761153838218277564957917658707297649757920676303301655328103665512287797108510142025749178023115877128203665039997"));
+ QCOMPARE(result, QCA::BigInteger("565532963656761153838218277564957917658707297649757920676303301655328103665512287797108510142025749178023115877128203665039997"));
+
+ result = QCA::BigInteger("-349535960680522202843083381184496349093812380954435872337802226")
+ -= QCA::BigInteger("-1829600726218222026679938");
+ QCOMPARE(result.toString(), QString("-349535960680522202843083381184496349091982780228217650311122288"));
+ QCOMPARE(result, QCA::BigInteger("-349535960680522202843083381184496349091982780228217650311122288"));
+
+ result = QCA::BigInteger("-1") -= QCA::BigInteger("-6726974989587128275");
+ QCOMPARE(result.toString(), QString("6726974989587128274"));
+ QCOMPARE(result, QCA::BigInteger("6726974989587128274"));
+
+ result = QCA::BigInteger("-107142709838121196902389095205618516687047338619382145236348309762148611647954748824")
+ -= QCA::BigInteger("42484103615491");
+ QCOMPARE(result.toString(), QString("-107142709838121196902389095205618516687047338619382145236348309762148654132058364315"));
+ QCOMPARE(result, QCA::BigInteger("-107142709838121196902389095205618516687047338619382145236348309762148654132058364315"));
+
+ result = QCA::BigInteger("-90546630430085769764839607528116121381848878494574360812027599640018921358040178215575723")
+ -= QCA::BigInteger("-118922408531468986902800063237122125617455464103913195171141030774109638861272017660698580914239435114280434761425243");
+ QCOMPARE(result.toString(), QString("118922408531468986902800063146575495187369694339073587643024909392260760366697656848670981274220513756240256545849520"));
+ QCOMPARE(result, QCA::BigInteger("118922408531468986902800063146575495187369694339073587643024909392260760366697656848670981274220513756240256545849520"));
+
+ result = QCA::BigInteger("-5545044667082427128801726416727657360001588430113578182850657573063241939882570324573086267287272360432363387213743735507218270373633222520429")
+ -= QCA::BigInteger("-151423255459028627628896755237194376177115");
+ QCOMPARE(result.toString(), QString("-5545044667082427128801726416727657360001588430113578182850657573063241939882570324573086267287272360280940131754715107878321515136438846343314"));
+ QCOMPARE(result, QCA::BigInteger("-5545044667082427128801726416727657360001588430113578182850657573063241939882570324573086267287272360280940131754715107878321515136438846343314"));
+
+ result = QCA::BigInteger("-5247636471953421659649611318164848102069")
+ -= QCA::BigInteger("-4024324110573096565232590473170599175885004");
+ QCOMPARE(result.toString(), QString("4019076474101143143572940861852434327782935"));
+ QCOMPARE(result, QCA::BigInteger("4019076474101143143572940861852434327782935"));
+
+ result = QCA::BigInteger("39412892606015043322484854253879371723186457838590224795040178472832")
+ -= QCA::BigInteger("-5038321321957452145034687815432890684825466579123474921848465393400312");
+ QCOMPARE(result.toString(), QString("5077734214563467188357172669686770056548653036962065146643505571873144"));
+ QCOMPARE(result, QCA::BigInteger("5077734214563467188357172669686770056548653036962065146643505571873144"));
+
+ result = QCA::BigInteger("-55979414588009227035683624505208766753187469727799640277204274207843317583292736333912783829528270272642583004969175230274821")
+ -= QCA::BigInteger("-109633110576212669339535976775635762395927171313557427036242111476016398579345366908401334025571265714128108308032073779442181369365924213118258269679");
+ QCOMPARE(result.toString(), QString("109633110576212669339535920796221174386700135629932921827475358288546670779705089704127126182253682421391774395248244251171908726782919243943027994858"));
+ QCOMPARE(result, QCA::BigInteger("109633110576212669339535920796221174386700135629932921827475358288546670779705089704127126182253682421391774395248244251171908726782919243943027994858"));
+
+ result = QCA::BigInteger("-38752353898173389347479216285772999906325286421302866854350737050533204094183249691110")
+ -= QCA::BigInteger("2428819407377764342156426895396654728835493564788997075896393065230009911546390816091652653701035085361");
+ QCOMPARE(result.toString(), QString("-2428819407377764380908780793570044076314709850561996982221679486532876765897127866624856747884284776471"));
+ QCOMPARE(result, QCA::BigInteger("-2428819407377764380908780793570044076314709850561996982221679486532876765897127866624856747884284776471"));
+
+ result = QCA::BigInteger("-2784579005241382005249492720344")
+ -= QCA::BigInteger("-164204542616919252351131740123094674");
+ QCOMPARE(result.toString(), QString("164201758037914010969126490630374330"));
+ QCOMPARE(result, QCA::BigInteger("164201758037914010969126490630374330"));
+
+ result = QCA::BigInteger("200948857420871544747808060972375039052401280822505804851732868100")
+ -= QCA::BigInteger("-795957177479360455258269298038670876462147576765875895105714");
+ QCOMPARE(result.toString(), QString("200949653378049024108263319241673077723277742970082570727627973814"));
+ QCOMPARE(result, QCA::BigInteger("200949653378049024108263319241673077723277742970082570727627973814"));
+
+ result = QCA::BigInteger("217570540819")
+ -= QCA::BigInteger("121955083597720420983384282166693307394185530431368476834980748302158718406063500763434561937200696970170700");
+ QCOMPARE(result.toString(), QString("-121955083597720420983384282166693307394185530431368476834980748302158718406063500763434561937200479399629881"));
+ QCOMPARE(result, QCA::BigInteger(QString("-121955083597720420983384282166693307394185530431368476834980748302158718406063500763434561937200479399629881")));
+
+ result = QCA::BigInteger(QString("2335319252198456765380587281374076367944"))
+ -= QCA::BigInteger(QString("-4500271"));
+ QCOMPARE(result, QCA::BigInteger(QString("2335319252198456765380587281374080868215")));
+
+ result = QCA::BigInteger(QString("-393694614027544181700073367147249369966344727230221941008713805434207925307052598"))
+ -= QCA::BigInteger(QString("-153972676737062409261153899615588515236137907791841623991260363840680295565313157972489168132345521780658007459602823125797806770"));
+ QCOMPARE(result.toString(), QString("153972676737062409261153899615588515236137907791447929377232819658980222198165908602522823405115299839649293654168615200490754172"));
+ QCOMPARE(result, QCA::BigInteger(QString("153972676737062409261153899615588515236137907791447929377232819658980222198165908602522823405115299839649293654168615200490754172")));
+
+ result = QCA::BigInteger(QString("114832549702862263167"))
+ -= QCA::BigInteger(QString("12921864907229959558745276418830287875386673600892281022286597165773569473039953984775959232814911435097412913078625"));
+ QCOMPARE(result.toString(), QString("-12921864907229959558745276418830287875386673600892281022286597165773569473039953984775959232814796602547710050815458"));
+ QCOMPARE(result, QCA::BigInteger(QString("-12921864907229959558745276418830287875386673600892281022286597165773569473039953984775959232814796602547710050815458")));
+
+ result = QCA::BigInteger(QString("6489502346837936889305337487724547956628371915228387374094443896266362105931065153072983425911767580294076594078932835008494777866083"))
+ -= QCA::BigInteger(QString("1099205476533612407829257935144627350486541654788267826664706620630745291371323154513322608446957760026881954001581"));
+ QCOMPARE(result.toString(), QString("6489502346837936888206132011190935548799113980083760023607902241478094279266358532442238134540444425780753985631975074981612823864502"));
+ QCOMPARE(result, QCA::BigInteger(QString("6489502346837936888206132011190935548799113980083760023607902241478094279266358532442238134540444425780753985631975074981612823864502")));
+
+ result = QCA::BigInteger(QString("169991144123958754253801313173662977337850870273358378951640521601077152994474340806917796870911557233689087716056557"))
+ -= QCA::BigInteger(QString("-15409167"));
+ QCOMPARE(result.toString(), QString("169991144123958754253801313173662977337850870273358378951640521601077152994474340806917796870911557233689087731465724"));
+ QCOMPARE(result, QCA::BigInteger(QString("169991144123958754253801313173662977337850870273358378951640521601077152994474340806917796870911557233689087731465724")));
}
QTEST_MAIN(BigIntUnitTest)
#include "bigintunittest.moc"
diff --git a/unittest/certunittest/certunittest.cpp b/unittest/certunittest/certunittest.cpp
index d12b04e6..2a007756 100644
--- a/unittest/certunittest/certunittest.cpp
+++ b/unittest/certunittest/certunittest.cpp
@@ -1,1210 +1,1205 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class CertUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void checkSystemStore();
void nullCert();
void noSuchFile();
void CAcertstest();
void derCAcertstest();
void qualitysslcatest();
void checkExpiredClientCerts();
void checkClientCerts();
void altName();
void extXMPP();
void checkExpiredServerCerts();
void checkServerCerts();
void altNames76();
void sha256cert();
void crl();
void crl2();
void csr();
void csr2();
void cleanupTestCase();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void CertUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void CertUnitTest::cleanupTestCase()
{
delete m_init;
}
void CertUnitTest::nullCert()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate nullCert;
- QVERIFY(nullCert.isNull());
- QCA::Certificate anotherNullCert = nullCert;
- QVERIFY( anotherNullCert.isNull() );
- QCOMPARE( nullCert, anotherNullCert );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate nullCert;
+ QVERIFY(nullCert.isNull());
+ QCA::Certificate anotherNullCert = nullCert;
+ QVERIFY(anotherNullCert.isNull());
+ QCOMPARE(nullCert, anotherNullCert);
+ }
}
}
void CertUnitTest::noSuchFile()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultNoFile;
- QCA::Certificate cert = QCA::Certificate::fromPEMFile( "thisIsJustaFileNameThatWeDontHave", &resultNoFile, provider);
- QCOMPARE( resultNoFile, QCA::ErrorFile );
- QVERIFY( cert.isNull() );
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultNoFile;
+ QCA::Certificate cert = QCA::Certificate::fromPEMFile("thisIsJustaFileNameThatWeDontHave", &resultNoFile, provider);
+ QCOMPARE(resultNoFile, QCA::ErrorFile);
+ QVERIFY(cert.isNull());
}
}
}
void CertUnitTest::CAcertstest()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultca1;
- QCA::Certificate ca1 = QCA::Certificate::fromPEMFile( "certs/RootCAcert.pem", &resultca1, provider);
-
- QCOMPARE( resultca1, QCA::ConvertGood );
- QCOMPARE( ca1.isNull(), false );
- QCOMPARE( ca1.pathLimit(), 0 );
- QCOMPARE( ca1.isCA(), true );
- QCOMPARE( ca1.isSelfSigned(), true );
-
- QCOMPARE( ca1.serialNumber(), QCA::BigInteger(0) );
-
- QCOMPARE( ca1.commonName(), QString("For Tests Only") );
-
- QCOMPARE( ca1.notValidBefore().toString(), QDateTime( QDate( 2001, 8, 17 ), QTime( 8, 30, 39 ), Qt::UTC ).toString() );
- QCOMPARE( ca1.notValidAfter().toString(), QDateTime( QDate( 2011, 8, 15 ), QTime( 8, 30, 39 ), Qt::UTC ).toString() );
-
- QCOMPARE( ca1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::DataEncipherment) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::KeyCertificateSign) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::CRLSign) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::ServerAuth) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::ClientAuth) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::EmailProtection) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( ca1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::OCSPSigning) == true, false );
-
- // no policies on this cert
- QCOMPARE( ca1.policies().count(), 0 );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultca1;
+ QCA::Certificate ca1 = QCA::Certificate::fromPEMFile("certs/RootCAcert.pem", &resultca1, provider);
+
+ QCOMPARE(resultca1, QCA::ConvertGood);
+ QCOMPARE(ca1.isNull(), false);
+ QCOMPARE(ca1.pathLimit(), 0);
+ QCOMPARE(ca1.isCA(), true);
+ QCOMPARE(ca1.isSelfSigned(), true);
+
+ QCOMPARE(ca1.serialNumber(), QCA::BigInteger(0));
+
+ QCOMPARE(ca1.commonName(), QString("For Tests Only"));
+
+ QCOMPARE(ca1.notValidBefore().toString(), QDateTime(QDate(2001, 8, 17), QTime(8, 30, 39), Qt::UTC).toString());
+ QCOMPARE(ca1.notValidAfter().toString(), QDateTime(QDate(2011, 8, 15), QTime(8, 30, 39), Qt::UTC).toString());
+
+ QCOMPARE(ca1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::DataEncipherment) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyCertificateSign) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::CRLSign) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::ServerAuth) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::ClientAuth) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::EmailProtection) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::OCSPSigning) == true, false);
+
+ // no policies on this cert
+ QCOMPARE(ca1.policies().count(), 0);
+ }
}
}
void CertUnitTest::qualitysslcatest()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultca1;
- QCA::Certificate ca1 = QCA::Certificate::fromPEMFile( "certs/QualitySSLIntermediateCA.crt", &resultca1, provider);
-
- QCOMPARE( resultca1, QCA::ConvertGood );
- QCOMPARE( ca1.isNull(), false );
- QCOMPARE( ca1.isCA(), true );
- QCOMPARE( ca1.isSelfSigned(), false );
-
- QCOMPARE( ca1.signatureAlgorithm(), QCA::EMSA3_SHA1 );
-
- QCOMPARE( ca1.serialNumber(), QCA::BigInteger("33555098") );
-
- QCOMPARE( ca1.commonName(), QString("Comodo Class 3 Security Services CA") );
-
- QCOMPARE( ca1.notValidBefore().toString(), QDateTime( QDate( 2002, 8, 27 ), QTime( 19, 02, 00 ), Qt::UTC ).toString() );
- QCOMPARE( ca1.notValidAfter().toString(), QDateTime( QDate( 2012, 8, 27 ), QTime( 23, 59, 00 ), Qt::UTC ).toString() );
-
-
- QCOMPARE( ca1.pathLimit(), 0 );
-
- QCOMPARE( ca1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::DataEncipherment) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::KeyCertificateSign) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::CRLSign) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::ServerAuth) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::ClientAuth) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::EmailProtection) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( ca1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::OCSPSigning) == true, false );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultca1;
+ QCA::Certificate ca1 = QCA::Certificate::fromPEMFile("certs/QualitySSLIntermediateCA.crt", &resultca1, provider);
+
+ QCOMPARE(resultca1, QCA::ConvertGood);
+ QCOMPARE(ca1.isNull(), false);
+ QCOMPARE(ca1.isCA(), true);
+ QCOMPARE(ca1.isSelfSigned(), false);
+
+ QCOMPARE(ca1.signatureAlgorithm(), QCA::EMSA3_SHA1);
+
+ QCOMPARE(ca1.serialNumber(), QCA::BigInteger("33555098"));
+
+ QCOMPARE(ca1.commonName(), QString("Comodo Class 3 Security Services CA"));
+
+ QCOMPARE(ca1.notValidBefore().toString(), QDateTime(QDate(2002, 8, 27), QTime(19, 02, 00), Qt::UTC).toString());
+ QCOMPARE(ca1.notValidAfter().toString(), QDateTime(QDate(2012, 8, 27), QTime(23, 59, 00), Qt::UTC).toString());
+
+ QCOMPARE(ca1.pathLimit(), 0);
+
+ QCOMPARE(ca1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::DataEncipherment) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyCertificateSign) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::CRLSign) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::ServerAuth) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::ClientAuth) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::EmailProtection) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::OCSPSigning) == true, false);
+ }
}
}
void CertUnitTest::checkExpiredClientCerts()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultClient1;
- QCA::Certificate client1 = QCA::Certificate::fromPEMFile( "certs/User.pem", &resultClient1, provider);
- QCOMPARE( resultClient1, QCA::ConvertGood );
- QCOMPARE( client1.isNull(), false );
- QCOMPARE( client1.isCA(), false );
- QCOMPARE( client1.isSelfSigned(), false );
-
- QCOMPARE( client1.serialNumber(), QCA::BigInteger(2) );
-
- QCOMPARE( client1.commonName(), QString("Insecure User Test Cert") );
-
- QCOMPARE( client1.notValidBefore().toString(), QDateTime( QDate( 2001, 8, 17 ), QTime( 8, 32, 38 ), Qt::UTC ).toString() );
- QCOMPARE( client1.notValidAfter().toString(), QDateTime( QDate( 2006, 8, 16 ), QTime( 8, 32, 38 ), Qt::UTC ).toString() );
-
- QCOMPARE( client1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::DataEncipherment) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::KeyCertificateSign) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::CRLSign) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::ServerAuth) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::ClientAuth) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::EmailProtection) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( client1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::OCSPSigning) == true, false );
-
- // no policies on this cert
- QCOMPARE( client1.policies().count(), 0 );
-
- QCA::CertificateInfo subject1 = client1.subjectInfo();
- QCOMPARE( subject1.isEmpty(), false );
- QCOMPARE( subject1.values(QCA::Country).contains("de") == true, true );
- QCOMPARE( subject1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true );
- QCOMPARE( subject1.values(QCA::CommonName).contains("Insecure User Test Cert") == true, true );
-
- QCA::CertificateInfo issuer1 = client1.issuerInfo();
- QCOMPARE( issuer1.isEmpty(), false );
- QCOMPARE( issuer1.values(QCA::Country).contains("de") == true, true );
- QCOMPARE( issuer1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true );
- QCOMPARE( issuer1.values(QCA::CommonName).contains("For Tests Only") == true, true );
-
- QByteArray subjectKeyID = QCA::Hex().stringToArray("889E7EF729719D7B280F361AAE6D00D39DE1AADB").toByteArray();
- QCOMPARE( client1.subjectKeyId(), subjectKeyID );
- QCOMPARE( QCA::Hex().arrayToString(client1.issuerKeyId()), QString("bf53438278d09ec380e51b67ca0500dfb94883a5") );
-
- QCA::PublicKey pubkey1 = client1.subjectPublicKey();
- QCOMPARE( pubkey1.isNull(), false );
- QCOMPARE( pubkey1.isRSA(), true );
- QCOMPARE( pubkey1.isDSA(), false );
- QCOMPARE( pubkey1.isDH(), false );
- QCOMPARE( pubkey1.isPublic(), true );
- QCOMPARE( pubkey1.isPrivate(), false );
- QCOMPARE( pubkey1.bitSize(), 1024 );
-
- QCOMPARE( client1.pathLimit(), 0 );
-
- QCOMPARE( client1.signatureAlgorithm(), QCA::EMSA3_MD5 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( client1.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::ConvertResult resultca1;
- QCA::Certificate ca1 = QCA::Certificate::fromPEMFile( "certs/RootCAcert.pem", &resultca1, provider);
- QCOMPARE( resultca1, QCA::ConvertGood );
- trusted.addCertificate( ca1 );
-
- QCOMPARE( client1.validate( trusted, untrusted ), QCA::ErrorExpired );
- QCOMPARE( client1.validate( trusted, untrusted, QCA::UsageAny ), QCA::ErrorExpired );
- QCOMPARE( client1.validate( trusted, untrusted, QCA::UsageTLSServer ), QCA::ErrorExpired );
- QCOMPARE( client1.validate( trusted, untrusted, QCA::UsageTLSClient ), QCA::ErrorExpired );
- QCOMPARE( client1.validate( trusted, untrusted, QCA::UsageCodeSigning ), QCA::ErrorExpired );
- QCOMPARE( client1.validate( trusted, untrusted, QCA::UsageTimeStamping ), QCA::ErrorExpired );
- QCOMPARE( client1.validate( trusted, untrusted, QCA::UsageEmailProtection ), QCA::ErrorExpired );
- QCOMPARE( client1.validate( trusted, untrusted, QCA::UsageCRLSigning ), QCA::ErrorExpired );
- QByteArray derClient1 = client1.toDER();
- QCOMPARE( derClient1.isEmpty(), false );
- QCA::Certificate fromDer1 = QCA::Certificate::fromDER( derClient1, &resultClient1, provider );
- QCOMPARE( resultClient1, QCA::ConvertGood );
- QVERIFY( fromDer1 == client1 );
-
- QString pemClient1 = client1.toPEM();
- QCOMPARE( pemClient1.isEmpty(), false );
- QCA::Certificate fromPem1 = QCA::Certificate::fromPEM( pemClient1, &resultClient1, provider);
- QCOMPARE( resultClient1, QCA::ConvertGood );
- QVERIFY( fromPem1 == client1);
- QCOMPARE( fromPem1 != fromDer1, false );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultClient1;
+ QCA::Certificate client1 = QCA::Certificate::fromPEMFile("certs/User.pem", &resultClient1, provider);
+ QCOMPARE(resultClient1, QCA::ConvertGood);
+ QCOMPARE(client1.isNull(), false);
+ QCOMPARE(client1.isCA(), false);
+ QCOMPARE(client1.isSelfSigned(), false);
+
+ QCOMPARE(client1.serialNumber(), QCA::BigInteger(2));
+
+ QCOMPARE(client1.commonName(), QString("Insecure User Test Cert"));
+
+ QCOMPARE(client1.notValidBefore().toString(), QDateTime(QDate(2001, 8, 17), QTime(8, 32, 38), Qt::UTC).toString());
+ QCOMPARE(client1.notValidAfter().toString(), QDateTime(QDate(2006, 8, 16), QTime(8, 32, 38), Qt::UTC).toString());
+
+ QCOMPARE(client1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::DataEncipherment) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::KeyCertificateSign) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::CRLSign) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::ServerAuth) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::ClientAuth) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::EmailProtection) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::OCSPSigning) == true, false);
+
+ // no policies on this cert
+ QCOMPARE(client1.policies().count(), 0);
+
+ QCA::CertificateInfo subject1 = client1.subjectInfo();
+ QCOMPARE(subject1.isEmpty(), false);
+ QCOMPARE(subject1.values(QCA::Country).contains("de") == true, true);
+ QCOMPARE(subject1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true);
+ QCOMPARE(subject1.values(QCA::CommonName).contains("Insecure User Test Cert") == true, true);
+
+ QCA::CertificateInfo issuer1 = client1.issuerInfo();
+ QCOMPARE(issuer1.isEmpty(), false);
+ QCOMPARE(issuer1.values(QCA::Country).contains("de") == true, true);
+ QCOMPARE(issuer1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true);
+ QCOMPARE(issuer1.values(QCA::CommonName).contains("For Tests Only") == true, true);
+
+ QByteArray subjectKeyID = QCA::Hex().stringToArray("889E7EF729719D7B280F361AAE6D00D39DE1AADB").toByteArray();
+ QCOMPARE(client1.subjectKeyId(), subjectKeyID);
+ QCOMPARE(QCA::Hex().arrayToString(client1.issuerKeyId()), QString("bf53438278d09ec380e51b67ca0500dfb94883a5"));
+
+ QCA::PublicKey pubkey1 = client1.subjectPublicKey();
+ QCOMPARE(pubkey1.isNull(), false);
+ QCOMPARE(pubkey1.isRSA(), true);
+ QCOMPARE(pubkey1.isDSA(), false);
+ QCOMPARE(pubkey1.isDH(), false);
+ QCOMPARE(pubkey1.isPublic(), true);
+ QCOMPARE(pubkey1.isPrivate(), false);
+ QCOMPARE(pubkey1.bitSize(), 1024);
+
+ QCOMPARE(client1.pathLimit(), 0);
+
+ QCOMPARE(client1.signatureAlgorithm(), QCA::EMSA3_MD5);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(client1.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::ConvertResult resultca1;
+ QCA::Certificate ca1 = QCA::Certificate::fromPEMFile("certs/RootCAcert.pem", &resultca1, provider);
+ QCOMPARE(resultca1, QCA::ConvertGood);
+ trusted.addCertificate(ca1);
+
+ QCOMPARE(client1.validate(trusted, untrusted), QCA::ErrorExpired);
+ QCOMPARE(client1.validate(trusted, untrusted, QCA::UsageAny), QCA::ErrorExpired);
+ QCOMPARE(client1.validate(trusted, untrusted, QCA::UsageTLSServer), QCA::ErrorExpired);
+ QCOMPARE(client1.validate(trusted, untrusted, QCA::UsageTLSClient), QCA::ErrorExpired);
+ QCOMPARE(client1.validate(trusted, untrusted, QCA::UsageCodeSigning), QCA::ErrorExpired);
+ QCOMPARE(client1.validate(trusted, untrusted, QCA::UsageTimeStamping), QCA::ErrorExpired);
+ QCOMPARE(client1.validate(trusted, untrusted, QCA::UsageEmailProtection), QCA::ErrorExpired);
+ QCOMPARE(client1.validate(trusted, untrusted, QCA::UsageCRLSigning), QCA::ErrorExpired);
+ QByteArray derClient1 = client1.toDER();
+ QCOMPARE(derClient1.isEmpty(), false);
+ QCA::Certificate fromDer1 = QCA::Certificate::fromDER(derClient1, &resultClient1, provider);
+ QCOMPARE(resultClient1, QCA::ConvertGood);
+ QVERIFY(fromDer1 == client1);
+
+ QString pemClient1 = client1.toPEM();
+ QCOMPARE(pemClient1.isEmpty(), false);
+ QCA::Certificate fromPem1 = QCA::Certificate::fromPEM(pemClient1, &resultClient1, provider);
+ QCOMPARE(resultClient1, QCA::ConvertGood);
+ QVERIFY(fromPem1 == client1);
+ QCOMPARE(fromPem1 != fromDer1, false);
+ }
}
}
void CertUnitTest::checkClientCerts()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultClient2;
- QCA::Certificate client2 = QCA::Certificate::fromPEMFile( "certs/QcaTestClientCert.pem", &resultClient2, provider);
- QCOMPARE( resultClient2, QCA::ConvertGood );
- QCOMPARE( client2.isNull(), false );
- QCOMPARE( client2.isCA(), false );
- QCOMPARE( client2.isSelfSigned(), false );
-
- QCOMPARE( client2.serialNumber(), QCA::BigInteger("13149359243510447488") );
-
- QCOMPARE( client2.commonName(), QString("Qca Test Client Certificate") );
-
- QCOMPARE( client2.notValidBefore().toString(), QDateTime( QDate( 2013, 7, 31 ), QTime( 15, 14, 28 ), Qt::UTC ).toString() );
- QCOMPARE( client2.notValidAfter().toString(), QDateTime( QDate( 2033, 7, 26 ), QTime( 15, 14, 28 ), Qt::UTC ).toString() );
-
- QCOMPARE( client2.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( client2.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( client2.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( client2.constraints().contains(QCA::DataEncipherment) == true, true );
- QCOMPARE( client2.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::KeyCertificateSign) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::CRLSign) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::ServerAuth) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::ClientAuth) == true, true );
- QCOMPARE( client2.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::EmailProtection) == true, true );
- QCOMPARE( client2.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( client2.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( client2.constraints().contains(QCA::OCSPSigning) == true, false );
-
- // no policies on this cert
- QCOMPARE( client2.policies().count(), 0 );
-
- QCA::CertificateInfo subject2 = client2.subjectInfo();
- QCOMPARE( subject2.isEmpty(), false );
- QVERIFY( subject2.values(QCA::Country).contains("US") );
- QVERIFY( subject2.values(QCA::Organization).contains("Qca Development and Test") );
- QVERIFY( subject2.values(QCA::OrganizationalUnit).contains("Certificate Generation Section") );
- QVERIFY( subject2.values(QCA::CommonName).contains("Qca Test Client Certificate") );
-
- QCA::CertificateInfo issuer2 = client2.issuerInfo();
- QCOMPARE( issuer2.isEmpty(), false );
- QVERIFY( issuer2.values(QCA::Country).contains("AU") );
- QVERIFY( issuer2.values(QCA::Organization).contains("Qca Development and Test") );
- QVERIFY( issuer2.values(QCA::CommonName).contains("Qca Test Root Certificate") );
-
- QByteArray subjectKeyID = QCA::Hex().stringToArray("1e604e03127d287ba40427a961b428a2d09b50d1").toByteArray();
- QCOMPARE( client2.subjectKeyId(), subjectKeyID );
- QCOMPARE( QCA::Hex().arrayToString(client2.issuerKeyId()), QString("f61c451de1b0458138c60568c1a7cb0f7ade0363") );
-
- QCA::PublicKey pubkey2 = client2.subjectPublicKey();
- QCOMPARE( pubkey2.isNull(), false );
- QCOMPARE( pubkey2.isRSA(), true );
- QCOMPARE( pubkey2.isDSA(), false );
- QCOMPARE( pubkey2.isDH(), false );
- QCOMPARE( pubkey2.isPublic(), true );
- QCOMPARE( pubkey2.isPrivate(), false );
- QCOMPARE( pubkey2.bitSize(), 1024 );
-
- QCOMPARE( client2.pathLimit(), 0 );
-
- QCOMPARE( client2.signatureAlgorithm(), QCA::EMSA3_SHA1 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( client2.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::ConvertResult resultca2;
- QCA::Certificate ca2 = QCA::Certificate::fromPEMFile( "certs/QcaTestRootCert.pem", &resultca2, provider);
- QCOMPARE( resultca2, QCA::ConvertGood );
- trusted.addCertificate( ca2 );
-
- QCOMPARE( client2.validate( trusted, untrusted ), QCA::ValidityGood );
- QCOMPARE( client2.validate( trusted, untrusted, QCA::UsageAny ), QCA::ValidityGood );
- QCOMPARE( client2.validate( trusted, untrusted, QCA::UsageTLSServer ), QCA::ErrorInvalidPurpose );
- QCOMPARE( client2.validate( trusted, untrusted, QCA::UsageTLSClient ), QCA::ValidityGood );
- QCOMPARE( client2.validate( trusted, untrusted, QCA::UsageCodeSigning ), QCA::ErrorInvalidPurpose );
- QCOMPARE( client2.validate( trusted, untrusted, QCA::UsageTimeStamping ), QCA::ErrorInvalidPurpose );
- QCOMPARE( client2.validate( trusted, untrusted, QCA::UsageEmailProtection ), QCA::ValidityGood );
- QCOMPARE( client2.validate( trusted, untrusted, QCA::UsageCRLSigning ), QCA::ErrorInvalidPurpose );
- QByteArray derClient2 = client2.toDER();
- QCOMPARE( derClient2.isEmpty(), false );
- QCA::Certificate fromDer2 = QCA::Certificate::fromDER( derClient2, &resultClient2, provider );
- QCOMPARE( resultClient2, QCA::ConvertGood );
- QVERIFY( fromDer2 == client2 );
-
- QString pemClient2 = client2.toPEM();
- QCOMPARE( pemClient2.isEmpty(), false );
- QCA::Certificate fromPem2 = QCA::Certificate::fromPEM( pemClient2, &resultClient2, provider);
- QCOMPARE( resultClient2, QCA::ConvertGood );
- QVERIFY( fromPem2 == client2);
- QCOMPARE( fromPem2 != fromDer2, false );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultClient2;
+ QCA::Certificate client2 = QCA::Certificate::fromPEMFile("certs/QcaTestClientCert.pem", &resultClient2, provider);
+ QCOMPARE(resultClient2, QCA::ConvertGood);
+ QCOMPARE(client2.isNull(), false);
+ QCOMPARE(client2.isCA(), false);
+ QCOMPARE(client2.isSelfSigned(), false);
+
+ QCOMPARE(client2.serialNumber(), QCA::BigInteger("13149359243510447488"));
+
+ QCOMPARE(client2.commonName(), QString("Qca Test Client Certificate"));
+
+ QCOMPARE(client2.notValidBefore().toString(), QDateTime(QDate(2013, 7, 31), QTime(15, 14, 28), Qt::UTC).toString());
+ QCOMPARE(client2.notValidAfter().toString(), QDateTime(QDate(2033, 7, 26), QTime(15, 14, 28), Qt::UTC).toString());
+
+ QCOMPARE(client2.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(client2.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(client2.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(client2.constraints().contains(QCA::DataEncipherment) == true, true);
+ QCOMPARE(client2.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::KeyCertificateSign) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::CRLSign) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::ServerAuth) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::ClientAuth) == true, true);
+ QCOMPARE(client2.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::EmailProtection) == true, true);
+ QCOMPARE(client2.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(client2.constraints().contains(QCA::OCSPSigning) == true, false);
+
+ // no policies on this cert
+ QCOMPARE(client2.policies().count(), 0);
+
+ QCA::CertificateInfo subject2 = client2.subjectInfo();
+ QCOMPARE(subject2.isEmpty(), false);
+ QVERIFY(subject2.values(QCA::Country).contains("US"));
+ QVERIFY(subject2.values(QCA::Organization).contains("Qca Development and Test"));
+ QVERIFY(subject2.values(QCA::OrganizationalUnit).contains("Certificate Generation Section"));
+ QVERIFY(subject2.values(QCA::CommonName).contains("Qca Test Client Certificate"));
+
+ QCA::CertificateInfo issuer2 = client2.issuerInfo();
+ QCOMPARE(issuer2.isEmpty(), false);
+ QVERIFY(issuer2.values(QCA::Country).contains("AU"));
+ QVERIFY(issuer2.values(QCA::Organization).contains("Qca Development and Test"));
+ QVERIFY(issuer2.values(QCA::CommonName).contains("Qca Test Root Certificate"));
+
+ QByteArray subjectKeyID = QCA::Hex().stringToArray("1e604e03127d287ba40427a961b428a2d09b50d1").toByteArray();
+ QCOMPARE(client2.subjectKeyId(), subjectKeyID);
+ QCOMPARE(QCA::Hex().arrayToString(client2.issuerKeyId()), QString("f61c451de1b0458138c60568c1a7cb0f7ade0363"));
+
+ QCA::PublicKey pubkey2 = client2.subjectPublicKey();
+ QCOMPARE(pubkey2.isNull(), false);
+ QCOMPARE(pubkey2.isRSA(), true);
+ QCOMPARE(pubkey2.isDSA(), false);
+ QCOMPARE(pubkey2.isDH(), false);
+ QCOMPARE(pubkey2.isPublic(), true);
+ QCOMPARE(pubkey2.isPrivate(), false);
+ QCOMPARE(pubkey2.bitSize(), 1024);
+
+ QCOMPARE(client2.pathLimit(), 0);
+
+ QCOMPARE(client2.signatureAlgorithm(), QCA::EMSA3_SHA1);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(client2.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::ConvertResult resultca2;
+ QCA::Certificate ca2 = QCA::Certificate::fromPEMFile("certs/QcaTestRootCert.pem", &resultca2, provider);
+ QCOMPARE(resultca2, QCA::ConvertGood);
+ trusted.addCertificate(ca2);
+
+ QCOMPARE(client2.validate(trusted, untrusted), QCA::ValidityGood);
+ QCOMPARE(client2.validate(trusted, untrusted, QCA::UsageAny), QCA::ValidityGood);
+ QCOMPARE(client2.validate(trusted, untrusted, QCA::UsageTLSServer), QCA::ErrorInvalidPurpose);
+ QCOMPARE(client2.validate(trusted, untrusted, QCA::UsageTLSClient), QCA::ValidityGood);
+ QCOMPARE(client2.validate(trusted, untrusted, QCA::UsageCodeSigning), QCA::ErrorInvalidPurpose);
+ QCOMPARE(client2.validate(trusted, untrusted, QCA::UsageTimeStamping), QCA::ErrorInvalidPurpose);
+ QCOMPARE(client2.validate(trusted, untrusted, QCA::UsageEmailProtection), QCA::ValidityGood);
+ QCOMPARE(client2.validate(trusted, untrusted, QCA::UsageCRLSigning), QCA::ErrorInvalidPurpose);
+ QByteArray derClient2 = client2.toDER();
+ QCOMPARE(derClient2.isEmpty(), false);
+ QCA::Certificate fromDer2 = QCA::Certificate::fromDER(derClient2, &resultClient2, provider);
+ QCOMPARE(resultClient2, QCA::ConvertGood);
+ QVERIFY(fromDer2 == client2);
+
+ QString pemClient2 = client2.toPEM();
+ QCOMPARE(pemClient2.isEmpty(), false);
+ QCA::Certificate fromPem2 = QCA::Certificate::fromPEM(pemClient2, &resultClient2, provider);
+ QCOMPARE(resultClient2, QCA::ConvertGood);
+ QVERIFY(fromPem2 == client2);
+ QCOMPARE(fromPem2 != fromDer2, false);
+ }
}
}
-
void CertUnitTest::derCAcertstest()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
QFile f("certs/ov-root-ca-cert.crt");
QVERIFY(f.open(QFile::ReadOnly));
QByteArray der = f.readAll();
QCA::ConvertResult resultca1;
QCA::Certificate ca1 = QCA::Certificate::fromDER(der,
- &resultca1,
- provider);
+ &resultca1,
+ provider);
- QCOMPARE( resultca1, QCA::ConvertGood );
+ QCOMPARE(resultca1, QCA::ConvertGood);
- QCOMPARE( ca1.pathLimit(), 0 );
+ QCOMPARE(ca1.pathLimit(), 0);
- QCOMPARE( ca1.isNull(), false );
- QCOMPARE( ca1.isCA(), true );
+ QCOMPARE(ca1.isNull(), false);
+ QCOMPARE(ca1.isCA(), true);
- QCOMPARE( ca1.isSelfSigned(), true );
+ QCOMPARE(ca1.isSelfSigned(), true);
- QCOMPARE( ca1.serialNumber(), QCA::BigInteger(0) );
+ QCOMPARE(ca1.serialNumber(), QCA::BigInteger(0));
- QCOMPARE( ca1.commonName(), QString("For Tests Only") );
+ QCOMPARE(ca1.commonName(), QString("For Tests Only"));
QCA::CertificateInfo si = ca1.subjectInfo();
- QCOMPARE( si.isEmpty(), false );
- QCOMPARE( si.value(QCA::CommonName), QString("For Tests Only") );
- QCOMPARE( si.value(QCA::Organization), QString("InsecureTestCertificate") );
- QCOMPARE( si.value(QCA::Country), QString("de") );
-
+ QCOMPARE(si.isEmpty(), false);
+ QCOMPARE(si.value(QCA::CommonName), QString("For Tests Only"));
+ QCOMPARE(si.value(QCA::Organization), QString("InsecureTestCertificate"));
+ QCOMPARE(si.value(QCA::Country), QString("de"));
QCA::CertificateInfo ii = ca1.issuerInfo();
- QCOMPARE( ii.isEmpty(), false );
- QCOMPARE( ii.value(QCA::CommonName), QString("For Tests Only") );
- QCOMPARE( ii.value(QCA::Organization), QString("InsecureTestCertificate") );
- QCOMPARE( ii.value(QCA::Country), QString("de") );
-
- QCOMPARE( ca1.notValidBefore().toString(), QDateTime( QDate( 2001, 8, 17 ), QTime( 8, 30, 39 ), Qt::UTC ).toString() );
- QCOMPARE( ca1.notValidAfter().toString(), QDateTime( QDate( 2011, 8, 15 ), QTime( 8, 30, 39 ), Qt::UTC ).toString() );
-
- QCOMPARE( ca1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::DataEncipherment) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::KeyCertificateSign) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::CRLSign) == true, true );
- QCOMPARE( ca1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::ServerAuth) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::ClientAuth) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::EmailProtection) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( ca1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( ca1.constraints().contains(QCA::OCSPSigning) == true, false );
+ QCOMPARE(ii.isEmpty(), false);
+ QCOMPARE(ii.value(QCA::CommonName), QString("For Tests Only"));
+ QCOMPARE(ii.value(QCA::Organization), QString("InsecureTestCertificate"));
+ QCOMPARE(ii.value(QCA::Country), QString("de"));
+
+ QCOMPARE(ca1.notValidBefore().toString(), QDateTime(QDate(2001, 8, 17), QTime(8, 30, 39), Qt::UTC).toString());
+ QCOMPARE(ca1.notValidAfter().toString(), QDateTime(QDate(2011, 8, 15), QTime(8, 30, 39), Qt::UTC).toString());
+
+ QCOMPARE(ca1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::DataEncipherment) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::KeyCertificateSign) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::CRLSign) == true, true);
+ QCOMPARE(ca1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::ServerAuth) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::ClientAuth) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::EmailProtection) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(ca1.constraints().contains(QCA::OCSPSigning) == true, false);
// no policies on this cert
- QCOMPARE( ca1.policies().count(), 0 );
+ QCOMPARE(ca1.policies().count(), 0);
- QCOMPARE( ca1.signatureAlgorithm(), QCA::EMSA3_MD5 );
+ QCOMPARE(ca1.signatureAlgorithm(), QCA::EMSA3_MD5);
}
}
}
void CertUnitTest::altName()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultClient1;
- QCA::Certificate client1 = QCA::Certificate::fromPEMFile( "certs/altname.pem", &resultClient1, provider);
- QCOMPARE( resultClient1, QCA::ConvertGood );
- QCOMPARE( client1.isNull(), false );
- QCOMPARE( client1.isCA(), false );
- QCOMPARE( client1.isSelfSigned(), false );
-
- QCOMPARE( client1.serialNumber(), QCA::BigInteger(1) );
-
- QCOMPARE( client1.commonName(), QString("Valid RFC822 nameConstraints EE Certificate Test21") );
-
- QCOMPARE( client1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::DataEncipherment) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::KeyCertificateSign) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::CRLSign) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::ServerAuth) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::ClientAuth) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::EmailProtection) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( client1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::OCSPSigning) == true, false );
-
- QCOMPARE( client1.policies().count(), 1 );
- QCOMPARE( client1.policies().at(0), QString("2.16.840.1.101.3.2.1.48.1") );
-
- QCA::CertificateInfo subject1 = client1.subjectInfo();
- QCOMPARE( subject1.isEmpty(), false );
- QVERIFY( subject1.values(QCA::Country).contains("US") );
- QVERIFY( subject1.values(QCA::Organization).contains("Test Certificates") );
- QVERIFY( subject1.values(QCA::CommonName).contains("Valid RFC822 nameConstraints EE Certificate Test21") );
- QVERIFY( subject1.values(QCA::Email).contains("Test21EE@mailserver.testcertificates.gov") );
-
- QCA::CertificateInfo issuer1 = client1.issuerInfo();
- QCOMPARE( issuer1.isEmpty(), false );
- QVERIFY( issuer1.values(QCA::Country).contains("US") );
- QVERIFY( issuer1.values(QCA::Organization).contains("Test Certificates") );
- QVERIFY( issuer1.values(QCA::CommonName).contains("nameConstraints RFC822 CA1") );
-
- QByteArray subjectKeyID = QCA::Hex().stringToArray("b4200d42cd95ea87d463d54f0ed6d10fe5b73bfb").toByteArray();
- QCOMPARE( client1.subjectKeyId(), subjectKeyID );
- QCOMPARE( QCA::Hex().arrayToString(client1.issuerKeyId()), QString("e37f857a8ea23b9eeeb8121d7913aac4bd2e59ad") );
-
- QCA::PublicKey pubkey1 = client1.subjectPublicKey();
- QCOMPARE( pubkey1.isNull(), false );
- QCOMPARE( pubkey1.isRSA(), true );
- QCOMPARE( pubkey1.isDSA(), false );
- QCOMPARE( pubkey1.isDH(), false );
- QCOMPARE( pubkey1.isPublic(), true );
- QCOMPARE( pubkey1.isPrivate(), false );
- QCOMPARE( pubkey1.bitSize(), 1024 );
-
- QCOMPARE( client1.pathLimit(), 0 );
-
- QCOMPARE( client1.signatureAlgorithm(), QCA::EMSA3_SHA1 );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultClient1;
+ QCA::Certificate client1 = QCA::Certificate::fromPEMFile("certs/altname.pem", &resultClient1, provider);
+ QCOMPARE(resultClient1, QCA::ConvertGood);
+ QCOMPARE(client1.isNull(), false);
+ QCOMPARE(client1.isCA(), false);
+ QCOMPARE(client1.isSelfSigned(), false);
+
+ QCOMPARE(client1.serialNumber(), QCA::BigInteger(1));
+
+ QCOMPARE(client1.commonName(), QString("Valid RFC822 nameConstraints EE Certificate Test21"));
+
+ QCOMPARE(client1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::DataEncipherment) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::KeyCertificateSign) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::CRLSign) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::ServerAuth) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::ClientAuth) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::EmailProtection) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::OCSPSigning) == true, false);
+
+ QCOMPARE(client1.policies().count(), 1);
+ QCOMPARE(client1.policies().at(0), QString("2.16.840.1.101.3.2.1.48.1"));
+
+ QCA::CertificateInfo subject1 = client1.subjectInfo();
+ QCOMPARE(subject1.isEmpty(), false);
+ QVERIFY(subject1.values(QCA::Country).contains("US"));
+ QVERIFY(subject1.values(QCA::Organization).contains("Test Certificates"));
+ QVERIFY(subject1.values(QCA::CommonName).contains("Valid RFC822 nameConstraints EE Certificate Test21"));
+ QVERIFY(subject1.values(QCA::Email).contains("Test21EE@mailserver.testcertificates.gov"));
+
+ QCA::CertificateInfo issuer1 = client1.issuerInfo();
+ QCOMPARE(issuer1.isEmpty(), false);
+ QVERIFY(issuer1.values(QCA::Country).contains("US"));
+ QVERIFY(issuer1.values(QCA::Organization).contains("Test Certificates"));
+ QVERIFY(issuer1.values(QCA::CommonName).contains("nameConstraints RFC822 CA1"));
+
+ QByteArray subjectKeyID = QCA::Hex().stringToArray("b4200d42cd95ea87d463d54f0ed6d10fe5b73bfb").toByteArray();
+ QCOMPARE(client1.subjectKeyId(), subjectKeyID);
+ QCOMPARE(QCA::Hex().arrayToString(client1.issuerKeyId()), QString("e37f857a8ea23b9eeeb8121d7913aac4bd2e59ad"));
+
+ QCA::PublicKey pubkey1 = client1.subjectPublicKey();
+ QCOMPARE(pubkey1.isNull(), false);
+ QCOMPARE(pubkey1.isRSA(), true);
+ QCOMPARE(pubkey1.isDSA(), false);
+ QCOMPARE(pubkey1.isDH(), false);
+ QCOMPARE(pubkey1.isPublic(), true);
+ QCOMPARE(pubkey1.isPrivate(), false);
+ QCOMPARE(pubkey1.bitSize(), 1024);
+
+ QCOMPARE(client1.pathLimit(), 0);
+
+ QCOMPARE(client1.signatureAlgorithm(), QCA::EMSA3_SHA1);
+ }
}
}
void CertUnitTest::extXMPP()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultClient1;
- QCA::Certificate client1 = QCA::Certificate::fromPEMFile( "certs/xmppcert.pem", &resultClient1, provider);
- QCOMPARE( resultClient1, QCA::ConvertGood );
- QCOMPARE( client1.isNull(), false );
- QCOMPARE( client1.isCA(), false );
- QCOMPARE( client1.isSelfSigned(), true );
-
- QCOMPARE( client1.serialNumber(), QCA::BigInteger("9635301556349760241") );
-
- QCOMPARE( client1.commonName(), QString("demo.jabber.com") );
-
- QCA::CertificateInfo subject1 = client1.subjectInfo();
- QCOMPARE( subject1.isEmpty(), false );
- QVERIFY( subject1.values(QCA::Country).contains("US") );
- QVERIFY( subject1.values(QCA::Organization).contains("Jabber, Inc.") );
- QVERIFY( subject1.values(QCA::Locality).contains("Denver") );
- QVERIFY( subject1.values(QCA::State).contains("Colorado") );
- QVERIFY( subject1.values(QCA::CommonName).contains("demo.jabber.com") );
- QVERIFY( subject1.values(QCA::DNS).contains("demo.jabber.com") );
- QVERIFY( subject1.values(QCA::XMPP).contains("demo.jabber.com") );
-
- QCA::CertificateInfo issuer1 = client1.issuerInfo();
- QCOMPARE( issuer1.isEmpty(), false );
- QVERIFY( issuer1.values(QCA::Country).contains("US") );
- QVERIFY( issuer1.values(QCA::Organization).contains("Jabber, Inc.") );
- QVERIFY( issuer1.values(QCA::Locality).contains("Denver") );
- QVERIFY( issuer1.values(QCA::State).contains("Colorado") );
- QVERIFY( issuer1.values(QCA::CommonName).contains("demo.jabber.com") );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultClient1;
+ QCA::Certificate client1 = QCA::Certificate::fromPEMFile("certs/xmppcert.pem", &resultClient1, provider);
+ QCOMPARE(resultClient1, QCA::ConvertGood);
+ QCOMPARE(client1.isNull(), false);
+ QCOMPARE(client1.isCA(), false);
+ QCOMPARE(client1.isSelfSigned(), true);
+
+ QCOMPARE(client1.serialNumber(), QCA::BigInteger("9635301556349760241"));
+
+ QCOMPARE(client1.commonName(), QString("demo.jabber.com"));
+
+ QCA::CertificateInfo subject1 = client1.subjectInfo();
+ QCOMPARE(subject1.isEmpty(), false);
+ QVERIFY(subject1.values(QCA::Country).contains("US"));
+ QVERIFY(subject1.values(QCA::Organization).contains("Jabber, Inc."));
+ QVERIFY(subject1.values(QCA::Locality).contains("Denver"));
+ QVERIFY(subject1.values(QCA::State).contains("Colorado"));
+ QVERIFY(subject1.values(QCA::CommonName).contains("demo.jabber.com"));
+ QVERIFY(subject1.values(QCA::DNS).contains("demo.jabber.com"));
+ QVERIFY(subject1.values(QCA::XMPP).contains("demo.jabber.com"));
+
+ QCA::CertificateInfo issuer1 = client1.issuerInfo();
+ QCOMPARE(issuer1.isEmpty(), false);
+ QVERIFY(issuer1.values(QCA::Country).contains("US"));
+ QVERIFY(issuer1.values(QCA::Organization).contains("Jabber, Inc."));
+ QVERIFY(issuer1.values(QCA::Locality).contains("Denver"));
+ QVERIFY(issuer1.values(QCA::State).contains("Colorado"));
+ QVERIFY(issuer1.values(QCA::CommonName).contains("demo.jabber.com"));
+ }
}
}
void CertUnitTest::altNames76()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
QCA::ConvertResult resultClient1;
- QCA::Certificate client1 = QCA::Certificate::fromPEMFile( "certs/76.pem", &resultClient1, provider);
- QCOMPARE( resultClient1, QCA::ConvertGood );
- QCOMPARE( client1.isNull(), false );
- QCOMPARE( client1.isCA(), false );
- QCOMPARE( client1.isSelfSigned(), false );
-
- QCOMPARE( client1.serialNumber(), QCA::BigInteger(118) );
-
- QCOMPARE( client1.commonName(), QString("sip1.su.se") );
-
- QCOMPARE( client1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::DataEncipherment) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::KeyCertificateSign) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::CRLSign) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::ServerAuth) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::ClientAuth) == true, true );
- QCOMPARE( client1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::EmailProtection) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( client1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( client1.constraints().contains(QCA::OCSPSigning) == true, false );
-
- QCOMPARE( client1.policies().count(), 1 );
+ QCA::Certificate client1 = QCA::Certificate::fromPEMFile("certs/76.pem", &resultClient1, provider);
+ QCOMPARE(resultClient1, QCA::ConvertGood);
+ QCOMPARE(client1.isNull(), false);
+ QCOMPARE(client1.isCA(), false);
+ QCOMPARE(client1.isSelfSigned(), false);
+
+ QCOMPARE(client1.serialNumber(), QCA::BigInteger(118));
+
+ QCOMPARE(client1.commonName(), QString("sip1.su.se"));
+
+ QCOMPARE(client1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::DataEncipherment) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::KeyCertificateSign) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::CRLSign) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::ServerAuth) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::ClientAuth) == true, true);
+ QCOMPARE(client1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::EmailProtection) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(client1.constraints().contains(QCA::OCSPSigning) == true, false);
+
+ QCOMPARE(client1.policies().count(), 1);
QCA::CertificateInfo subject1 = client1.subjectInfo();
- QCOMPARE( subject1.isEmpty(), false );
- QVERIFY( subject1.values(QCA::Country).contains("SE") );
- QVERIFY( subject1.values(QCA::Organization).contains("Stockholms universitet") );
- QVERIFY( subject1.values(QCA::CommonName).contains("sip1.su.se") );
- QCOMPARE( subject1.values(QCA::Email).count(), 0 );
- QCOMPARE( subject1.values(QCA::DNS).count(), 8 );
- QVERIFY( subject1.values(QCA::DNS).contains("incomingproxy.sip.su.se") );
- QVERIFY( subject1.values(QCA::DNS).contains("incomingproxy1.sip.su.se") );
- QVERIFY( subject1.values(QCA::DNS).contains("outgoingproxy.sip.su.se") );
- QVERIFY( subject1.values(QCA::DNS).contains("outgoingproxy1.sip.su.se") );
- QVERIFY( subject1.values(QCA::DNS).contains("out.sip.su.se") );
- QVERIFY( subject1.values(QCA::DNS).contains("appserver.sip.su.se") );
- QVERIFY( subject1.values(QCA::DNS).contains("appserver1.sip.su.se") );
- QVERIFY( subject1.values(QCA::DNS).contains("sip1.su.se") );
-
- QVERIFY( client1.matchesHostName("incomingproxy.sip.su.se") );
- QVERIFY( client1.matchesHostName("incomingproxy1.sip.su.se") );
- QVERIFY( client1.matchesHostName("outgoingproxy.sip.su.se") );
- QVERIFY( client1.matchesHostName("outgoingproxy1.sip.su.se") );
- QVERIFY( client1.matchesHostName("out.sip.su.se") );
- QVERIFY( client1.matchesHostName("appserver.sip.su.se") );
- QVERIFY( client1.matchesHostName("appserver1.sip.su.se") );
- QVERIFY( client1.matchesHostName("sip1.su.se") );
+ QCOMPARE(subject1.isEmpty(), false);
+ QVERIFY(subject1.values(QCA::Country).contains("SE"));
+ QVERIFY(subject1.values(QCA::Organization).contains("Stockholms universitet"));
+ QVERIFY(subject1.values(QCA::CommonName).contains("sip1.su.se"));
+ QCOMPARE(subject1.values(QCA::Email).count(), 0);
+ QCOMPARE(subject1.values(QCA::DNS).count(), 8);
+ QVERIFY(subject1.values(QCA::DNS).contains("incomingproxy.sip.su.se"));
+ QVERIFY(subject1.values(QCA::DNS).contains("incomingproxy1.sip.su.se"));
+ QVERIFY(subject1.values(QCA::DNS).contains("outgoingproxy.sip.su.se"));
+ QVERIFY(subject1.values(QCA::DNS).contains("outgoingproxy1.sip.su.se"));
+ QVERIFY(subject1.values(QCA::DNS).contains("out.sip.su.se"));
+ QVERIFY(subject1.values(QCA::DNS).contains("appserver.sip.su.se"));
+ QVERIFY(subject1.values(QCA::DNS).contains("appserver1.sip.su.se"));
+ QVERIFY(subject1.values(QCA::DNS).contains("sip1.su.se"));
+
+ QVERIFY(client1.matchesHostName("incomingproxy.sip.su.se"));
+ QVERIFY(client1.matchesHostName("incomingproxy1.sip.su.se"));
+ QVERIFY(client1.matchesHostName("outgoingproxy.sip.su.se"));
+ QVERIFY(client1.matchesHostName("outgoingproxy1.sip.su.se"));
+ QVERIFY(client1.matchesHostName("out.sip.su.se"));
+ QVERIFY(client1.matchesHostName("appserver.sip.su.se"));
+ QVERIFY(client1.matchesHostName("appserver1.sip.su.se"));
+ QVERIFY(client1.matchesHostName("sip1.su.se"));
QCA::CertificateInfo issuer1 = client1.issuerInfo();
- QCOMPARE( issuer1.isEmpty(), false );
- QVERIFY( issuer1.values(QCA::Country).contains("SE") );
- QVERIFY( issuer1.values(QCA::Organization).contains("Stockholms universitet") );
- QVERIFY( issuer1.values(QCA::CommonName).contains("Stockholm University CA") );
- QVERIFY( issuer1.values(QCA::URI).contains("http://ca.su.se") );
- QVERIFY( issuer1.values(QCA::Email).contains("ca@su.se") );
+ QCOMPARE(issuer1.isEmpty(), false);
+ QVERIFY(issuer1.values(QCA::Country).contains("SE"));
+ QVERIFY(issuer1.values(QCA::Organization).contains("Stockholms universitet"));
+ QVERIFY(issuer1.values(QCA::CommonName).contains("Stockholm University CA"));
+ QVERIFY(issuer1.values(QCA::URI).contains("http://ca.su.se"));
+ QVERIFY(issuer1.values(QCA::Email).contains("ca@su.se"));
QByteArray subjectKeyID = QCA::Hex().stringToArray("3a5c5cd1cc2c9edf73f73bd81b59b1eab83035c5").toByteArray();
- QCOMPARE( client1.subjectKeyId(), subjectKeyID );
- QCOMPARE( QCA::Hex().arrayToString(client1.issuerKeyId()), QString("9e2e30ba37d95144c99dbf1821f1bd7eeeb58648") );
+ QCOMPARE(client1.subjectKeyId(), subjectKeyID);
+ QCOMPARE(QCA::Hex().arrayToString(client1.issuerKeyId()), QString("9e2e30ba37d95144c99dbf1821f1bd7eeeb58648"));
QCA::PublicKey pubkey1 = client1.subjectPublicKey();
- QCOMPARE( pubkey1.isNull(), false );
- QCOMPARE( pubkey1.isRSA(), true );
- QCOMPARE( pubkey1.isDSA(), false );
- QCOMPARE( pubkey1.isDH(), false );
- QCOMPARE( pubkey1.isPublic(), true );
- QCOMPARE( pubkey1.isPrivate(), false );
- QCOMPARE( pubkey1.bitSize(), 1024 );
+ QCOMPARE(pubkey1.isNull(), false);
+ QCOMPARE(pubkey1.isRSA(), true);
+ QCOMPARE(pubkey1.isDSA(), false);
+ QCOMPARE(pubkey1.isDH(), false);
+ QCOMPARE(pubkey1.isPublic(), true);
+ QCOMPARE(pubkey1.isPrivate(), false);
+ QCOMPARE(pubkey1.bitSize(), 1024);
- QCOMPARE( client1.pathLimit(), 0 );
+ QCOMPARE(client1.pathLimit(), 0);
- QCOMPARE( client1.signatureAlgorithm(), QCA::EMSA3_SHA1 );
+ QCOMPARE(client1.signatureAlgorithm(), QCA::EMSA3_SHA1);
}
}
}
void CertUnitTest::sha256cert()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
QFile f("certs/RAIZ2007_CERTIFICATE_AND_CRL_SIGNING_SHA256.crt");
QVERIFY(f.open(QFile::ReadOnly));
QByteArray der = f.readAll();
QCA::ConvertResult resultcert;
QCA::Certificate cert = QCA::Certificate::fromDER(der,
- &resultcert,
- provider);
+ &resultcert,
+ provider);
- QCOMPARE( resultcert, QCA::ConvertGood );
- QCOMPARE( cert.isNull(), false );
- QCOMPARE( cert.isCA(), true );
- QCOMPARE( cert.isSelfSigned(), true );
+ QCOMPARE(resultcert, QCA::ConvertGood);
+ QCOMPARE(cert.isNull(), false);
+ QCOMPARE(cert.isCA(), true);
+ QCOMPARE(cert.isSelfSigned(), true);
QCA::PublicKey pubkey = cert.subjectPublicKey();
- QCOMPARE( pubkey.isNull(), false );
- QCOMPARE( pubkey.isRSA(), true );
- QCOMPARE( pubkey.isDSA(), false );
- QCOMPARE( pubkey.isDH(), false );
- QCOMPARE( pubkey.isPublic(), true );
- QCOMPARE( pubkey.isPrivate(), false );
- QCOMPARE( pubkey.bitSize(), 4096 );
+ QCOMPARE(pubkey.isNull(), false);
+ QCOMPARE(pubkey.isRSA(), true);
+ QCOMPARE(pubkey.isDSA(), false);
+ QCOMPARE(pubkey.isDH(), false);
+ QCOMPARE(pubkey.isPublic(), true);
+ QCOMPARE(pubkey.isPrivate(), false);
+ QCOMPARE(pubkey.bitSize(), 4096);
- QCOMPARE( cert.pathLimit(), 0 );
+ QCOMPARE(cert.pathLimit(), 0);
- QCOMPARE( cert.signatureAlgorithm(), QCA::EMSA3_SHA256 );
+ QCOMPARE(cert.signatureAlgorithm(), QCA::EMSA3_SHA256);
}
}
}
void CertUnitTest::checkExpiredServerCerts()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultServer1;
- QCA::Certificate server1 = QCA::Certificate::fromPEMFile( "certs/Server.pem", &resultServer1, provider);
- QCOMPARE( resultServer1, QCA::ConvertGood );
- QCOMPARE( server1.isNull(), false );
- QCOMPARE( server1.isCA(), false );
- QCOMPARE( server1.isSelfSigned(), false );
-
- QCOMPARE( server1.serialNumber(), QCA::BigInteger(4) );
-
- QCOMPARE( server1.commonName(), QString("Insecure Server Cert") );
-
- QCOMPARE( server1.notValidBefore().toString(), QDateTime( QDate( 2001, 8, 17 ), QTime( 8, 46, 24 ), Qt::UTC ).toString() );
- QCOMPARE( server1.notValidAfter().toString(), QDateTime( QDate( 2006, 8, 16 ), QTime( 8, 46, 24 ), Qt::UTC ).toString() );
-
- QCOMPARE( server1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::NonRepudiation) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::DataEncipherment) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::KeyAgreement) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::KeyCertificateSign) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::CRLSign) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::ServerAuth) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::ClientAuth) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::EmailProtection) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( server1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::OCSPSigning) == true, false );
-
- // no policies on this cert
- QCOMPARE( server1.policies().count(), 0 );
-
- QCA::CertificateInfo subject1 = server1.subjectInfo();
- QCOMPARE( subject1.isEmpty(), false );
- QCOMPARE( subject1.values(QCA::Country).contains("de") == true, true );
- QCOMPARE( subject1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true );
- QCOMPARE( subject1.values(QCA::CommonName).contains("Insecure Server Cert") == true, true );
-
- QCA::CertificateInfo issuer1 = server1.issuerInfo();
- QCOMPARE( issuer1.isEmpty(), false );
- QCOMPARE( issuer1.values(QCA::Country).contains("de") == true, true );
- QCOMPARE( issuer1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true );
- QCOMPARE( issuer1.values(QCA::CommonName).contains("For Tests Only") == true, true );
-
- QByteArray subjectKeyID = QCA::Hex().stringToArray("0234E2C906F6E0B44253BE04C0CBA7823A6DB509").toByteArray();
- QCOMPARE( server1.subjectKeyId(), subjectKeyID );
- QByteArray authorityKeyID = QCA::Hex().stringToArray("BF53438278D09EC380E51B67CA0500DFB94883A5").toByteArray();
- QCOMPARE( server1.issuerKeyId(), authorityKeyID );
-
- QCA::PublicKey pubkey1 = server1.subjectPublicKey();
- QCOMPARE( pubkey1.isNull(), false );
- QCOMPARE( pubkey1.isRSA(), true );
- QCOMPARE( pubkey1.isDSA(), false );
- QCOMPARE( pubkey1.isDH(), false );
- QCOMPARE( pubkey1.isPublic(), true );
- QCOMPARE( pubkey1.isPrivate(), false );
- QCOMPARE( pubkey1.bitSize(), 1024 );
-
- QCOMPARE( server1.pathLimit(), 0 );
-
- QCOMPARE( server1.signatureAlgorithm(), QCA::EMSA3_MD5 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( server1.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::ConvertResult resultca1;
- QCA::Certificate ca1 = QCA::Certificate::fromPEMFile( "certs/RootCAcert.pem", &resultca1, provider);
- QCOMPARE( resultca1, QCA::ConvertGood );
- trusted.addCertificate( ca1 );
- QCOMPARE( server1.validate( trusted, untrusted ), QCA::ErrorExpired );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageAny ), QCA::ErrorExpired );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageTLSServer ), QCA::ErrorExpired );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageTLSClient ), QCA::ErrorExpired );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageCodeSigning ), QCA::ErrorExpired );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageTimeStamping ), QCA::ErrorExpired );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageEmailProtection ), QCA::ErrorExpired );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageCRLSigning ), QCA::ErrorExpired );
-
- QByteArray derServer1 = server1.toDER();
- QCOMPARE( derServer1.isEmpty(), false );
- QCA::Certificate fromDer1 = QCA::Certificate::fromDER( derServer1, &resultServer1, provider );
- QCOMPARE( resultServer1, QCA::ConvertGood );
- QCOMPARE( fromDer1 == server1, true );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultServer1;
+ QCA::Certificate server1 = QCA::Certificate::fromPEMFile("certs/Server.pem", &resultServer1, provider);
+ QCOMPARE(resultServer1, QCA::ConvertGood);
+ QCOMPARE(server1.isNull(), false);
+ QCOMPARE(server1.isCA(), false);
+ QCOMPARE(server1.isSelfSigned(), false);
+
+ QCOMPARE(server1.serialNumber(), QCA::BigInteger(4));
+
+ QCOMPARE(server1.commonName(), QString("Insecure Server Cert"));
+
+ QCOMPARE(server1.notValidBefore().toString(), QDateTime(QDate(2001, 8, 17), QTime(8, 46, 24), Qt::UTC).toString());
+ QCOMPARE(server1.notValidAfter().toString(), QDateTime(QDate(2006, 8, 16), QTime(8, 46, 24), Qt::UTC).toString());
+
+ QCOMPARE(server1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::NonRepudiation) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::DataEncipherment) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::KeyAgreement) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::KeyCertificateSign) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::CRLSign) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::ServerAuth) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::ClientAuth) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::EmailProtection) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::OCSPSigning) == true, false);
+
+ // no policies on this cert
+ QCOMPARE(server1.policies().count(), 0);
+
+ QCA::CertificateInfo subject1 = server1.subjectInfo();
+ QCOMPARE(subject1.isEmpty(), false);
+ QCOMPARE(subject1.values(QCA::Country).contains("de") == true, true);
+ QCOMPARE(subject1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true);
+ QCOMPARE(subject1.values(QCA::CommonName).contains("Insecure Server Cert") == true, true);
+
+ QCA::CertificateInfo issuer1 = server1.issuerInfo();
+ QCOMPARE(issuer1.isEmpty(), false);
+ QCOMPARE(issuer1.values(QCA::Country).contains("de") == true, true);
+ QCOMPARE(issuer1.values(QCA::Organization).contains("InsecureTestCertificate") == true, true);
+ QCOMPARE(issuer1.values(QCA::CommonName).contains("For Tests Only") == true, true);
+
+ QByteArray subjectKeyID = QCA::Hex().stringToArray("0234E2C906F6E0B44253BE04C0CBA7823A6DB509").toByteArray();
+ QCOMPARE(server1.subjectKeyId(), subjectKeyID);
+ QByteArray authorityKeyID = QCA::Hex().stringToArray("BF53438278D09EC380E51B67CA0500DFB94883A5").toByteArray();
+ QCOMPARE(server1.issuerKeyId(), authorityKeyID);
+
+ QCA::PublicKey pubkey1 = server1.subjectPublicKey();
+ QCOMPARE(pubkey1.isNull(), false);
+ QCOMPARE(pubkey1.isRSA(), true);
+ QCOMPARE(pubkey1.isDSA(), false);
+ QCOMPARE(pubkey1.isDH(), false);
+ QCOMPARE(pubkey1.isPublic(), true);
+ QCOMPARE(pubkey1.isPrivate(), false);
+ QCOMPARE(pubkey1.bitSize(), 1024);
+
+ QCOMPARE(server1.pathLimit(), 0);
+
+ QCOMPARE(server1.signatureAlgorithm(), QCA::EMSA3_MD5);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(server1.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::ConvertResult resultca1;
+ QCA::Certificate ca1 = QCA::Certificate::fromPEMFile("certs/RootCAcert.pem", &resultca1, provider);
+ QCOMPARE(resultca1, QCA::ConvertGood);
+ trusted.addCertificate(ca1);
+ QCOMPARE(server1.validate(trusted, untrusted), QCA::ErrorExpired);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageAny), QCA::ErrorExpired);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageTLSServer), QCA::ErrorExpired);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageTLSClient), QCA::ErrorExpired);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageCodeSigning), QCA::ErrorExpired);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageTimeStamping), QCA::ErrorExpired);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageEmailProtection), QCA::ErrorExpired);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageCRLSigning), QCA::ErrorExpired);
+
+ QByteArray derServer1 = server1.toDER();
+ QCOMPARE(derServer1.isEmpty(), false);
+ QCA::Certificate fromDer1 = QCA::Certificate::fromDER(derServer1, &resultServer1, provider);
+ QCOMPARE(resultServer1, QCA::ConvertGood);
+ QCOMPARE(fromDer1 == server1, true);
+ }
}
}
-
void CertUnitTest::checkServerCerts()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultServer1;
- QCA::Certificate server1 = QCA::Certificate::fromPEMFile( "certs/QcaTestServerCert.pem", &resultServer1, provider);
- QCOMPARE( resultServer1, QCA::ConvertGood );
- QCOMPARE( server1.isNull(), false );
- QCOMPARE( server1.isCA(), false );
- QCOMPARE( server1.isSelfSigned(), false );
-
- QCOMPARE( server1.serialNumber(), QCA::BigInteger("13149359243510447489") );
-
- QCOMPARE( server1.commonName(), QString("Qca Server Test certificate") );
-
- QCOMPARE( server1.notValidBefore().toString(), QDateTime( QDate( 2013, 7, 31 ), QTime( 15, 23, 25 ), Qt::UTC ).toString() );
- QCOMPARE( server1.notValidAfter().toString(), QDateTime( QDate( 2033, 7, 26 ), QTime( 15, 23, 25 ), Qt::UTC ).toString() );
-
- QCOMPARE( server1.constraints().contains(QCA::DigitalSignature) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::NonRepudiation) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::KeyEncipherment) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::DataEncipherment) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::KeyAgreement) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::KeyCertificateSign) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::CRLSign) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::EncipherOnly) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::DecipherOnly) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::ServerAuth) == true, true );
- QCOMPARE( server1.constraints().contains(QCA::ClientAuth) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::CodeSigning) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::EmailProtection) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::IPSecEndSystem) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::IPSecTunnel) == true, false);
- QCOMPARE( server1.constraints().contains(QCA::IPSecUser) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::TimeStamping) == true, false );
- QCOMPARE( server1.constraints().contains(QCA::OCSPSigning) == true, false );
-
- // no policies on this cert
- QCOMPARE( server1.policies().count(), 0 );
-
- QCA::CertificateInfo subject1 = server1.subjectInfo();
- QCOMPARE( subject1.isEmpty(), false );
- QVERIFY( subject1.values(QCA::Country).contains("IL") );
- QVERIFY( subject1.values(QCA::Organization).contains("Qca Development and Test") );
- QVERIFY( subject1.values(QCA::OrganizationalUnit).contains("Server Management Section") );
- QVERIFY( subject1.values(QCA::CommonName).contains("Qca Server Test certificate") );
-
- QCA::CertificateInfo issuer1 = server1.issuerInfo();
- QCOMPARE( issuer1.isEmpty(), false );
- QVERIFY( issuer1.values(QCA::Country).contains("AU") );
- QVERIFY( issuer1.values(QCA::Organization).contains("Qca Development and Test") );
- QVERIFY( issuer1.values(QCA::OrganizationalUnit).contains("Certificate Generation Section") );
- QVERIFY( issuer1.values(QCA::CommonName).contains("Qca Test Root Certificate") );
-
- QByteArray subjectKeyID = QCA::Hex().stringToArray("819870c8b81eab53e72d0446b65790aa0d3eab1a").toByteArray();
- QCOMPARE( server1.subjectKeyId(), subjectKeyID );
- QByteArray authorityKeyID = QCA::Hex().stringToArray("f61c451de1b0458138c60568c1a7cb0f7ade0363").toByteArray();
- QCOMPARE( server1.issuerKeyId(), authorityKeyID );
-
- QCA::PublicKey pubkey1 = server1.subjectPublicKey();
- QCOMPARE( pubkey1.isNull(), false );
- QCOMPARE( pubkey1.isRSA(), true );
- QCOMPARE( pubkey1.isDSA(), false );
- QCOMPARE( pubkey1.isDH(), false );
- QCOMPARE( pubkey1.isPublic(), true );
- QCOMPARE( pubkey1.isPrivate(), false );
- QCOMPARE( pubkey1.bitSize(), 1024 );
-
- QCOMPARE( server1.pathLimit(), 0 );
-
- QCOMPARE( server1.signatureAlgorithm(), QCA::EMSA3_SHA1 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( server1.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::ConvertResult resultca1;
- QCA::Certificate ca1 = QCA::Certificate::fromPEMFile( "certs/QcaTestRootCert.pem", &resultca1, provider);
- QCOMPARE( resultca1, QCA::ConvertGood );
- trusted.addCertificate( ca1 );
- QCOMPARE( server1.validate( trusted, untrusted ), QCA::ValidityGood );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageAny ), QCA::ValidityGood );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageTLSServer ), QCA::ValidityGood );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageTLSClient ), QCA::ErrorInvalidPurpose );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageCodeSigning ), QCA::ErrorInvalidPurpose );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageTimeStamping ), QCA::ErrorInvalidPurpose );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageEmailProtection ), QCA::ErrorInvalidPurpose );
- QCOMPARE( server1.validate( trusted, untrusted, QCA::UsageCRLSigning ), QCA::ErrorInvalidPurpose );
-
- QByteArray derServer1 = server1.toDER();
- QCOMPARE( derServer1.isEmpty(), false );
- QCA::Certificate fromDer1 = QCA::Certificate::fromDER( derServer1, &resultServer1, provider );
- QCOMPARE( resultServer1, QCA::ConvertGood );
- QCOMPARE( fromDer1 == server1, true );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultServer1;
+ QCA::Certificate server1 = QCA::Certificate::fromPEMFile("certs/QcaTestServerCert.pem", &resultServer1, provider);
+ QCOMPARE(resultServer1, QCA::ConvertGood);
+ QCOMPARE(server1.isNull(), false);
+ QCOMPARE(server1.isCA(), false);
+ QCOMPARE(server1.isSelfSigned(), false);
+
+ QCOMPARE(server1.serialNumber(), QCA::BigInteger("13149359243510447489"));
+
+ QCOMPARE(server1.commonName(), QString("Qca Server Test certificate"));
+
+ QCOMPARE(server1.notValidBefore().toString(), QDateTime(QDate(2013, 7, 31), QTime(15, 23, 25), Qt::UTC).toString());
+ QCOMPARE(server1.notValidAfter().toString(), QDateTime(QDate(2033, 7, 26), QTime(15, 23, 25), Qt::UTC).toString());
+
+ QCOMPARE(server1.constraints().contains(QCA::DigitalSignature) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::NonRepudiation) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::KeyEncipherment) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::DataEncipherment) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::KeyAgreement) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::KeyCertificateSign) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::CRLSign) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::EncipherOnly) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::DecipherOnly) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::ServerAuth) == true, true);
+ QCOMPARE(server1.constraints().contains(QCA::ClientAuth) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::CodeSigning) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::EmailProtection) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::IPSecEndSystem) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::IPSecTunnel) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::IPSecUser) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::TimeStamping) == true, false);
+ QCOMPARE(server1.constraints().contains(QCA::OCSPSigning) == true, false);
+
+ // no policies on this cert
+ QCOMPARE(server1.policies().count(), 0);
+
+ QCA::CertificateInfo subject1 = server1.subjectInfo();
+ QCOMPARE(subject1.isEmpty(), false);
+ QVERIFY(subject1.values(QCA::Country).contains("IL"));
+ QVERIFY(subject1.values(QCA::Organization).contains("Qca Development and Test"));
+ QVERIFY(subject1.values(QCA::OrganizationalUnit).contains("Server Management Section"));
+ QVERIFY(subject1.values(QCA::CommonName).contains("Qca Server Test certificate"));
+
+ QCA::CertificateInfo issuer1 = server1.issuerInfo();
+ QCOMPARE(issuer1.isEmpty(), false);
+ QVERIFY(issuer1.values(QCA::Country).contains("AU"));
+ QVERIFY(issuer1.values(QCA::Organization).contains("Qca Development and Test"));
+ QVERIFY(issuer1.values(QCA::OrganizationalUnit).contains("Certificate Generation Section"));
+ QVERIFY(issuer1.values(QCA::CommonName).contains("Qca Test Root Certificate"));
+
+ QByteArray subjectKeyID = QCA::Hex().stringToArray("819870c8b81eab53e72d0446b65790aa0d3eab1a").toByteArray();
+ QCOMPARE(server1.subjectKeyId(), subjectKeyID);
+ QByteArray authorityKeyID = QCA::Hex().stringToArray("f61c451de1b0458138c60568c1a7cb0f7ade0363").toByteArray();
+ QCOMPARE(server1.issuerKeyId(), authorityKeyID);
+
+ QCA::PublicKey pubkey1 = server1.subjectPublicKey();
+ QCOMPARE(pubkey1.isNull(), false);
+ QCOMPARE(pubkey1.isRSA(), true);
+ QCOMPARE(pubkey1.isDSA(), false);
+ QCOMPARE(pubkey1.isDH(), false);
+ QCOMPARE(pubkey1.isPublic(), true);
+ QCOMPARE(pubkey1.isPrivate(), false);
+ QCOMPARE(pubkey1.bitSize(), 1024);
+
+ QCOMPARE(server1.pathLimit(), 0);
+
+ QCOMPARE(server1.signatureAlgorithm(), QCA::EMSA3_SHA1);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(server1.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::ConvertResult resultca1;
+ QCA::Certificate ca1 = QCA::Certificate::fromPEMFile("certs/QcaTestRootCert.pem", &resultca1, provider);
+ QCOMPARE(resultca1, QCA::ConvertGood);
+ trusted.addCertificate(ca1);
+ QCOMPARE(server1.validate(trusted, untrusted), QCA::ValidityGood);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageAny), QCA::ValidityGood);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageTLSServer), QCA::ValidityGood);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageTLSClient), QCA::ErrorInvalidPurpose);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageCodeSigning), QCA::ErrorInvalidPurpose);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageTimeStamping), QCA::ErrorInvalidPurpose);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageEmailProtection), QCA::ErrorInvalidPurpose);
+ QCOMPARE(server1.validate(trusted, untrusted, QCA::UsageCRLSigning), QCA::ErrorInvalidPurpose);
+
+ QByteArray derServer1 = server1.toDER();
+ QCOMPARE(derServer1.isEmpty(), false);
+ QCA::Certificate fromDer1 = QCA::Certificate::fromDER(derServer1, &resultServer1, provider);
+ QCOMPARE(resultServer1, QCA::ConvertGood);
+ QCOMPARE(fromDer1 == server1, true);
+ }
}
}
-
void CertUnitTest::checkSystemStore()
{
- if ( QCA::isSupported("cert") && QCA::isSupported("crl") ) {
- QCOMPARE( QCA::haveSystemStore(), true );
+ if (QCA::isSupported("cert") && QCA::isSupported("crl")) {
+ QCOMPARE(QCA::haveSystemStore(), true);
- QCA::CertificateCollection collection1;
- collection1 = QCA::systemStore();
- // Do we have any certs?
- QVERIFY( collection1.certificates().count() > 0);
+ QCA::CertificateCollection collection1;
+ collection1 = QCA::systemStore();
+ // Do we have any certs?
+ QVERIFY(collection1.certificates().count() > 0);
} else {
- QCOMPARE( QCA::haveSystemStore(), false );
+ QCOMPARE(QCA::haveSystemStore(), false);
}
}
void CertUnitTest::crl()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "crl", provider ) )
- QWARN( QString( "Certificate revocation not supported for "+provider).toLocal8Bit() );
- else {
- QCA::CRL emptyCRL;
- QVERIFY( emptyCRL.isNull() );
-
- QCA::ConvertResult resultCrl;
- QCA::CRL crl1 = QCA::CRL::fromPEMFile( "certs/Test_CRL.crl", &resultCrl, provider);
- QCOMPARE( resultCrl, QCA::ConvertGood );
- QCOMPARE( crl1.isNull(), false );
-
- QCA::CertificateInfo issuer = crl1.issuerInfo();
- QCOMPARE( issuer.isEmpty(), false );
- QVERIFY( issuer.values(QCA::Country).contains("de") );
- QVERIFY( issuer.values(QCA::Organization).contains("InsecureTestCertificate") );
- QVERIFY( issuer.values(QCA::CommonName).contains("For Tests Only") );
-
- // No keyid extension on this crl
- QCOMPARE( QCA::arrayToHex( crl1.issuerKeyId() ), QString("") );
-
- QCOMPARE( crl1.thisUpdate(), QDateTime(QDate(2001, 8, 17), QTime(11, 12, 03), Qt::UTC) );
- QCOMPARE( crl1.nextUpdate(), QDateTime(QDate(2006, 8, 16), QTime(11, 12, 03), Qt::UTC) );
-
- QCOMPARE( crl1.signatureAlgorithm(), QCA::EMSA3_MD5 );
-
- QCOMPARE( crl1.issuerKeyId(), QByteArray("") );
- QCOMPARE( crl1, QCA::CRL(crl1) );
- QCOMPARE( crl1 == QCA::CRL(), false );
- QCOMPARE( crl1.number(), -1 );
-
- QList<QCA::CRLEntry> revokedList = crl1.revoked();
- QCOMPARE( revokedList.size(), 2 );
- qSort(revokedList);
- QCOMPARE( revokedList[0].serialNumber(), QCA::BigInteger("3") );
- QCOMPARE( revokedList[1].serialNumber(), QCA::BigInteger("5") );
- QCOMPARE( revokedList[0].reason(), QCA::CRLEntry::Unspecified );
- QCOMPARE( revokedList[1].reason(), QCA::CRLEntry::Unspecified );
- QCOMPARE( revokedList[0].time(), QDateTime(QDate(2001, 8, 17), QTime(11, 10, 39), Qt::UTC) );
- QCOMPARE( revokedList[1].time(), QDateTime(QDate(2001, 8, 17), QTime(11, 11, 59), Qt::UTC) );
-
- // convert to DER
- QByteArray derCRL1 = crl1.toDER();
- // check we got something, at least
- QCOMPARE( derCRL1.isEmpty(), false );
- // convert back from DER
- QCA::CRL fromDer1 = QCA::CRL::fromDER( derCRL1, &resultCrl, provider );
- // check the conversion at least appeared to work
- QCOMPARE( resultCrl, QCA::ConvertGood );
- // check the result is the same as what we started with
- QCOMPARE( fromDer1, crl1 );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("crl", provider)) {
+ QWARN(QString("Certificate revocation not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::CRL emptyCRL;
+ QVERIFY(emptyCRL.isNull());
+
+ QCA::ConvertResult resultCrl;
+ QCA::CRL crl1 = QCA::CRL::fromPEMFile("certs/Test_CRL.crl", &resultCrl, provider);
+ QCOMPARE(resultCrl, QCA::ConvertGood);
+ QCOMPARE(crl1.isNull(), false);
+
+ QCA::CertificateInfo issuer = crl1.issuerInfo();
+ QCOMPARE(issuer.isEmpty(), false);
+ QVERIFY(issuer.values(QCA::Country).contains("de"));
+ QVERIFY(issuer.values(QCA::Organization).contains("InsecureTestCertificate"));
+ QVERIFY(issuer.values(QCA::CommonName).contains("For Tests Only"));
+
+ // No keyid extension on this crl
+ QCOMPARE(QCA::arrayToHex(crl1.issuerKeyId()), QString(""));
+
+ QCOMPARE(crl1.thisUpdate(), QDateTime(QDate(2001, 8, 17), QTime(11, 12, 03), Qt::UTC));
+ QCOMPARE(crl1.nextUpdate(), QDateTime(QDate(2006, 8, 16), QTime(11, 12, 03), Qt::UTC));
+
+ QCOMPARE(crl1.signatureAlgorithm(), QCA::EMSA3_MD5);
+
+ QCOMPARE(crl1.issuerKeyId(), QByteArray(""));
+ QCOMPARE(crl1, QCA::CRL(crl1));
+ QCOMPARE(crl1 == QCA::CRL(), false);
+ QCOMPARE(crl1.number(), -1);
+
+ QList<QCA::CRLEntry> revokedList = crl1.revoked();
+ QCOMPARE(revokedList.size(), 2);
+ qSort(revokedList);
+ QCOMPARE(revokedList[0].serialNumber(), QCA::BigInteger("3"));
+ QCOMPARE(revokedList[1].serialNumber(), QCA::BigInteger("5"));
+ QCOMPARE(revokedList[0].reason(), QCA::CRLEntry::Unspecified);
+ QCOMPARE(revokedList[1].reason(), QCA::CRLEntry::Unspecified);
+ QCOMPARE(revokedList[0].time(), QDateTime(QDate(2001, 8, 17), QTime(11, 10, 39), Qt::UTC));
+ QCOMPARE(revokedList[1].time(), QDateTime(QDate(2001, 8, 17), QTime(11, 11, 59), Qt::UTC));
+
+ // convert to DER
+ QByteArray derCRL1 = crl1.toDER();
+ // check we got something, at least
+ QCOMPARE(derCRL1.isEmpty(), false);
+ // convert back from DER
+ QCA::CRL fromDer1 = QCA::CRL::fromDER(derCRL1, &resultCrl, provider);
+ // check the conversion at least appeared to work
+ QCOMPARE(resultCrl, QCA::ConvertGood);
+ // check the result is the same as what we started with
+ QCOMPARE(fromDer1, crl1);
+ }
}
}
void CertUnitTest::crl2()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "crl", provider ) )
- QWARN( QString( "Certificate revocation not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultCrl;
- QCA::CRL crl1 = QCA::CRL::fromPEMFile( "certs/GoodCACRL.pem", &resultCrl, provider);
- QCOMPARE( resultCrl, QCA::ConvertGood );
- QCOMPARE( crl1.isNull(), false );
- QCOMPARE( crl1.provider()->name(), provider );
-
- QCA::CertificateInfo issuer = crl1.issuerInfo();
- QCOMPARE( issuer.isEmpty(), false );
- QVERIFY( issuer.values(QCA::Country).contains("US") );
- QVERIFY( issuer.values(QCA::Organization).contains("Test Certificates") );
- QVERIFY( issuer.values(QCA::CommonName).contains("Good CA") );
-
- QCOMPARE( crl1.thisUpdate(), QDateTime(QDate(2001, 4, 19), QTime(14, 57, 20), Qt::UTC) );
- QCOMPARE( crl1.nextUpdate(), QDateTime(QDate(2011, 4, 19), QTime(14, 57, 20), Qt::UTC) );
-
- QCOMPARE( crl1.signatureAlgorithm(), QCA::EMSA3_SHA1 );
-
- QCOMPARE( QCA::arrayToHex( crl1.issuerKeyId() ), QString("b72ea682cbc2c8bca87b2744d73533df9a1594c7") );
- QCOMPARE( crl1.number(), 1 );
- QCOMPARE( crl1, QCA::CRL(crl1) );
- QCOMPARE( crl1 == QCA::CRL(), false );
-
- QList<QCA::CRLEntry> revokedList = crl1.revoked();
- QCOMPARE( revokedList.size(), 2 );
- qSort(revokedList);
- QCOMPARE( revokedList[0].serialNumber(), QCA::BigInteger("14") );
- QCOMPARE( revokedList[1].serialNumber(), QCA::BigInteger("15") );
- QCOMPARE( revokedList[0].reason(), QCA::CRLEntry::KeyCompromise );
- QCOMPARE( revokedList[1].reason(), QCA::CRLEntry::KeyCompromise );
- QCOMPARE( revokedList[0].time(), QDateTime(QDate(2001, 4, 19), QTime(14, 57, 20), Qt::UTC) );
- QCOMPARE( revokedList[1].time(), QDateTime(QDate(2001, 4, 19), QTime(14, 57, 20), Qt::UTC) );
-
- // convert to DER
- QByteArray derCRL1 = crl1.toDER();
- // check we got something, at least
- QCOMPARE( derCRL1.isEmpty(), false );
- // convert back from DER
- QCA::CRL fromDer1 = QCA::CRL::fromDER( derCRL1, &resultCrl, provider );
- // check the conversion at least appeared to work
- QCOMPARE( resultCrl, QCA::ConvertGood );
- // check the result is the same as what we started with
- QCOMPARE( fromDer1, crl1 );
-
- // convert to PEM
- QString pemCRL1 = crl1.toPEM();
- // check we got something, at least
- QCOMPARE( pemCRL1.isEmpty(), false );
- // convert back from PEM
- QCA::CRL fromPEM1 = QCA::CRL::fromPEM( pemCRL1, &resultCrl, provider );
- // check the conversion at least appeared to work
- QCOMPARE( resultCrl, QCA::ConvertGood );
- // check the result is the same as what we started with
- QCOMPARE( fromPEM1, crl1 );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("crl", provider)) {
+ QWARN(QString("Certificate revocation not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultCrl;
+ QCA::CRL crl1 = QCA::CRL::fromPEMFile("certs/GoodCACRL.pem", &resultCrl, provider);
+ QCOMPARE(resultCrl, QCA::ConvertGood);
+ QCOMPARE(crl1.isNull(), false);
+ QCOMPARE(crl1.provider()->name(), provider);
+
+ QCA::CertificateInfo issuer = crl1.issuerInfo();
+ QCOMPARE(issuer.isEmpty(), false);
+ QVERIFY(issuer.values(QCA::Country).contains("US"));
+ QVERIFY(issuer.values(QCA::Organization).contains("Test Certificates"));
+ QVERIFY(issuer.values(QCA::CommonName).contains("Good CA"));
+
+ QCOMPARE(crl1.thisUpdate(), QDateTime(QDate(2001, 4, 19), QTime(14, 57, 20), Qt::UTC));
+ QCOMPARE(crl1.nextUpdate(), QDateTime(QDate(2011, 4, 19), QTime(14, 57, 20), Qt::UTC));
+
+ QCOMPARE(crl1.signatureAlgorithm(), QCA::EMSA3_SHA1);
+
+ QCOMPARE(QCA::arrayToHex(crl1.issuerKeyId()), QString("b72ea682cbc2c8bca87b2744d73533df9a1594c7"));
+ QCOMPARE(crl1.number(), 1);
+ QCOMPARE(crl1, QCA::CRL(crl1));
+ QCOMPARE(crl1 == QCA::CRL(), false);
+
+ QList<QCA::CRLEntry> revokedList = crl1.revoked();
+ QCOMPARE(revokedList.size(), 2);
+ qSort(revokedList);
+ QCOMPARE(revokedList[0].serialNumber(), QCA::BigInteger("14"));
+ QCOMPARE(revokedList[1].serialNumber(), QCA::BigInteger("15"));
+ QCOMPARE(revokedList[0].reason(), QCA::CRLEntry::KeyCompromise);
+ QCOMPARE(revokedList[1].reason(), QCA::CRLEntry::KeyCompromise);
+ QCOMPARE(revokedList[0].time(), QDateTime(QDate(2001, 4, 19), QTime(14, 57, 20), Qt::UTC));
+ QCOMPARE(revokedList[1].time(), QDateTime(QDate(2001, 4, 19), QTime(14, 57, 20), Qt::UTC));
+
+ // convert to DER
+ QByteArray derCRL1 = crl1.toDER();
+ // check we got something, at least
+ QCOMPARE(derCRL1.isEmpty(), false);
+ // convert back from DER
+ QCA::CRL fromDer1 = QCA::CRL::fromDER(derCRL1, &resultCrl, provider);
+ // check the conversion at least appeared to work
+ QCOMPARE(resultCrl, QCA::ConvertGood);
+ // check the result is the same as what we started with
+ QCOMPARE(fromDer1, crl1);
+
+ // convert to PEM
+ QString pemCRL1 = crl1.toPEM();
+ // check we got something, at least
+ QCOMPARE(pemCRL1.isEmpty(), false);
+ // convert back from PEM
+ QCA::CRL fromPEM1 = QCA::CRL::fromPEM(pemCRL1, &resultCrl, provider);
+ // check the conversion at least appeared to work
+ QCOMPARE(resultCrl, QCA::ConvertGood);
+ // check the result is the same as what we started with
+ QCOMPARE(fromPEM1, crl1);
+ }
}
}
void CertUnitTest::csr()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "csr", provider ) )
- QWARN( QString( "Certificate signing requests not supported for "+provider).toLocal8Bit() );
- else {
- QCA::CertificateRequest nullCSR;
- QVERIFY( nullCSR.isNull() );
- QCA::CertificateRequest anotherNullCSR = nullCSR;
- QVERIFY( anotherNullCSR.isNull() );
- QCOMPARE( nullCSR, anotherNullCSR);
-
- QCA::ConvertResult resultCsr;
- QCA::CertificateRequest csr1 = QCA::CertificateRequest::fromPEMFile( "certs/csr1.pem", &resultCsr, provider);
- QCOMPARE( resultCsr, QCA::ConvertGood );
- QCOMPARE( csr1.isNull(), false );
- QCOMPARE( csr1.provider()->name(), provider );
- QCA::CertificateInfo subject = csr1.subjectInfo();
- QCOMPARE( subject.isEmpty(), false );
- QVERIFY( subject.values(QCA::Country).contains("AU") );
- QVERIFY( subject.values(QCA::State).contains("Victoria") );
- QVERIFY( subject.values(QCA::Locality).contains("Mitcham") );
- QVERIFY( subject.values(QCA::Organization).contains("GE Interlogix") );
- QVERIFY( subject.values(QCA::OrganizationalUnit).contains("Engineering") );
- QVERIFY( subject.values(QCA::CommonName).contains("coldfire") );
-
- QCA::PublicKey pkey = csr1.subjectPublicKey();
- QCOMPARE( pkey.isNull(), false );
- QVERIFY( pkey.isRSA() );
-
- QCA::RSAPublicKey rsaPkey = pkey.toRSA();
- QCOMPARE( rsaPkey.isNull(), false );
- QCOMPARE( rsaPkey.e(), QCA::BigInteger(65537) );
- QCOMPARE( rsaPkey.n(), QCA::BigInteger("104853561647822232509211983664549572246855698961210758585652966258891659217901732470712446421431206166165309547771124747713609923038218156616083520796442797276676074122658684367500665423564881889504308700315044585826841844654287577169905826705891670004942854611681809539126326134927995969418712881512819058439") );
-
- QCOMPARE( csr1.signatureAlgorithm(), QCA::EMSA3_MD5 );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("csr", provider)) {
+ QWARN(QString("Certificate signing requests not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::CertificateRequest nullCSR;
+ QVERIFY(nullCSR.isNull());
+ QCA::CertificateRequest anotherNullCSR = nullCSR;
+ QVERIFY(anotherNullCSR.isNull());
+ QCOMPARE(nullCSR, anotherNullCSR);
+
+ QCA::ConvertResult resultCsr;
+ QCA::CertificateRequest csr1 = QCA::CertificateRequest::fromPEMFile("certs/csr1.pem", &resultCsr, provider);
+ QCOMPARE(resultCsr, QCA::ConvertGood);
+ QCOMPARE(csr1.isNull(), false);
+ QCOMPARE(csr1.provider()->name(), provider);
+ QCA::CertificateInfo subject = csr1.subjectInfo();
+ QCOMPARE(subject.isEmpty(), false);
+ QVERIFY(subject.values(QCA::Country).contains("AU"));
+ QVERIFY(subject.values(QCA::State).contains("Victoria"));
+ QVERIFY(subject.values(QCA::Locality).contains("Mitcham"));
+ QVERIFY(subject.values(QCA::Organization).contains("GE Interlogix"));
+ QVERIFY(subject.values(QCA::OrganizationalUnit).contains("Engineering"));
+ QVERIFY(subject.values(QCA::CommonName).contains("coldfire"));
+
+ QCA::PublicKey pkey = csr1.subjectPublicKey();
+ QCOMPARE(pkey.isNull(), false);
+ QVERIFY(pkey.isRSA());
+
+ QCA::RSAPublicKey rsaPkey = pkey.toRSA();
+ QCOMPARE(rsaPkey.isNull(), false);
+ QCOMPARE(rsaPkey.e(), QCA::BigInteger(65537));
+ QCOMPARE(rsaPkey.n(), QCA::BigInteger("104853561647822232509211983664549572246855698961210758585652966258891659217901732470712446421431206166165309547771124747713609923038218156616083520796442797276676074122658684367500665423564881889504308700315044585826841844654287577169905826705891670004942854611681809539126326134927995969418712881512819058439"));
+
+ QCOMPARE(csr1.signatureAlgorithm(), QCA::EMSA3_MD5);
+ }
}
}
void CertUnitTest::csr2()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "csr", provider ) )
- QWARN( QString( "Certificate signing requests not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult resultCsr;
- QCA::CertificateRequest csr1 = QCA::CertificateRequest::fromPEMFile( "certs/newreq.pem", &resultCsr, provider);
- QCOMPARE( resultCsr, QCA::ConvertGood );
- QCOMPARE( csr1.isNull(), false );
- QCOMPARE( csr1.provider()->name(), provider );
- QCA::CertificateInfo subject = csr1.subjectInfo();
- QCOMPARE( subject.isEmpty(), false );
- QVERIFY( subject.values(QCA::Country).contains("AI") );
- QVERIFY( subject.values(QCA::State).contains("Hutt River Province") );
- QVERIFY( subject.values(QCA::Locality).contains("Lesser Internet") );
- QVERIFY( subject.values(QCA::Organization).contains("My Company Ltd") );
- QVERIFY( subject.values(QCA::OrganizationalUnit).contains("Backwater Branch Office") );
- QVERIFY( subject.values(QCA::CommonName).contains("FirstName Surname") );
-
- QCA::PublicKey pkey = csr1.subjectPublicKey();
- QCOMPARE( pkey.isNull(), false );
- QVERIFY( pkey.isRSA() );
-
- QCA::RSAPublicKey rsaPkey = pkey.toRSA();
- QCOMPARE( rsaPkey.isNull(), false );
- QCOMPARE( rsaPkey.e(), QCA::BigInteger(65537) );
- QCOMPARE( rsaPkey.n(), QCA::BigInteger("151872780463004414908584891835397365176526767139347372444365914360701714510188717169754430290680734981291754624394094502297070722505032645306680495915914243593438796635264236530526146243919417744996366836534380790370421346490191416041004278161146551997010463199760480957900518811859984176646089981367745961681" ) );
-
- QCOMPARE( csr1.signatureAlgorithm(), QCA::EMSA3_MD5 );
-
- // convert to DER
- QByteArray derCSR1 = csr1.toDER();
- // check we got something, at least
- QCOMPARE( derCSR1.isEmpty(), false );
- // convert back from DER
- QCA::CertificateRequest fromDer1 = QCA::CertificateRequest::fromDER( derCSR1, &resultCsr, provider );
- // check the conversion at least appeared to work
- QCOMPARE( resultCsr, QCA::ConvertGood );
- // check the result is the same as what we started with
- QCOMPARE( fromDer1, csr1 );
-
- // convert to PEM
- QString pemCSR1 = csr1.toPEM();
- // check we got something, at least
- QCOMPARE( pemCSR1.isEmpty(), false );
- // convert back from PEM
- QCA::CertificateRequest fromPEM1 = QCA::CertificateRequest::fromPEM( pemCSR1, &resultCsr, provider );
- // check the conversion at least appeared to work
- QCOMPARE( resultCsr, QCA::ConvertGood );
- // check the result is the same as what we started with
- QCOMPARE( fromPEM1, csr1 );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("csr", provider)) {
+ QWARN(QString("Certificate signing requests not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult resultCsr;
+ QCA::CertificateRequest csr1 = QCA::CertificateRequest::fromPEMFile("certs/newreq.pem", &resultCsr, provider);
+ QCOMPARE(resultCsr, QCA::ConvertGood);
+ QCOMPARE(csr1.isNull(), false);
+ QCOMPARE(csr1.provider()->name(), provider);
+ QCA::CertificateInfo subject = csr1.subjectInfo();
+ QCOMPARE(subject.isEmpty(), false);
+ QVERIFY(subject.values(QCA::Country).contains("AI"));
+ QVERIFY(subject.values(QCA::State).contains("Hutt River Province"));
+ QVERIFY(subject.values(QCA::Locality).contains("Lesser Internet"));
+ QVERIFY(subject.values(QCA::Organization).contains("My Company Ltd"));
+ QVERIFY(subject.values(QCA::OrganizationalUnit).contains("Backwater Branch Office"));
+ QVERIFY(subject.values(QCA::CommonName).contains("FirstName Surname"));
+
+ QCA::PublicKey pkey = csr1.subjectPublicKey();
+ QCOMPARE(pkey.isNull(), false);
+ QVERIFY(pkey.isRSA());
+
+ QCA::RSAPublicKey rsaPkey = pkey.toRSA();
+ QCOMPARE(rsaPkey.isNull(), false);
+ QCOMPARE(rsaPkey.e(), QCA::BigInteger(65537));
+ QCOMPARE(rsaPkey.n(), QCA::BigInteger("151872780463004414908584891835397365176526767139347372444365914360701714510188717169754430290680734981291754624394094502297070722505032645306680495915914243593438796635264236530526146243919417744996366836534380790370421346490191416041004278161146551997010463199760480957900518811859984176646089981367745961681"));
+
+ QCOMPARE(csr1.signatureAlgorithm(), QCA::EMSA3_MD5);
+
+ // convert to DER
+ QByteArray derCSR1 = csr1.toDER();
+ // check we got something, at least
+ QCOMPARE(derCSR1.isEmpty(), false);
+ // convert back from DER
+ QCA::CertificateRequest fromDer1 = QCA::CertificateRequest::fromDER(derCSR1, &resultCsr, provider);
+ // check the conversion at least appeared to work
+ QCOMPARE(resultCsr, QCA::ConvertGood);
+ // check the result is the same as what we started with
+ QCOMPARE(fromDer1, csr1);
+
+ // convert to PEM
+ QString pemCSR1 = csr1.toPEM();
+ // check we got something, at least
+ QCOMPARE(pemCSR1.isEmpty(), false);
+ // convert back from PEM
+ QCA::CertificateRequest fromPEM1 = QCA::CertificateRequest::fromPEM(pemCSR1, &resultCsr, provider);
+ // check the conversion at least appeared to work
+ QCOMPARE(resultCsr, QCA::ConvertGood);
+ // check the result is the same as what we started with
+ QCOMPARE(fromPEM1, csr1);
+ }
}
}
QTEST_MAIN(CertUnitTest)
#include "certunittest.moc"
diff --git a/unittest/cipherunittest/cipherunittest.cpp b/unittest/cipherunittest/cipherunittest.cpp
index 2f321faa..4bc3d936 100644
--- a/unittest/cipherunittest/cipherunittest.cpp
+++ b/unittest/cipherunittest/cipherunittest.cpp
@@ -1,3195 +1,3168 @@
/**
* Copyright (C) 2004-2007 Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2013-2016 Ivan Romanov <drizt@land.ru>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "cipherunittest.h"
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
void CipherUnitTest::initTestCase()
{
- m_init = new QCA::Initializer;
+ m_init = new QCA::Initializer;
}
void CipherUnitTest::cleanupTestCase()
{
- delete m_init;
+ delete m_init;
}
void CipherUnitTest::aes128_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
-
- // Not sure where this came from...
- QTest::newRow("mystery") << QString("506812a45f08c889b97f5980038b8359")
- << QString("d8f532538289ef7d06b506a4fd5be9c9")
- << QString("00010203050607080a0b0c0d0f101112");
-
- // From FIPS 197 Appendix C.1
- QTest::newRow("FIPS197 App C.1") << QString("00112233445566778899aabbccddeeff")
- << QString("69c4e0d86a7b0430d8cdb78070b4c55a")
- << QString("000102030405060708090a0b0c0d0e0f");
-
- // These are from the Botan test suite
- QTest::newRow("1") << QString("506812a45f08c889b97f5980038b8359")
- << QString("d8f532538289ef7d06b506a4fd5be9c9")
- << QString("00010203050607080a0b0c0d0f101112");
- QTest::newRow("2") << QString("5c6d71ca30de8b8b00549984d2ec7d4b")
- << QString("59ab30f4d4ee6e4ff9907ef65b1fb68c")
- << QString("14151617191a1b1c1e1f202123242526");
- QTest::newRow("3") << QString("53f3f4c64f8616e4e7c56199f48f21f6")
- << QString("bf1ed2fcb2af3fd41443b56d85025cb1")
- << QString("28292a2b2d2e2f30323334353738393a");
- QTest::newRow("4") << QString("a1eb65a3487165fb0f1c27ff9959f703")
- << QString("7316632d5c32233edcb0780560eae8b2")
- << QString("3c3d3e3f41424344464748494b4c4d4e");
- QTest::newRow("5") << QString("3553ecf0b1739558b08e350a98a39bfa")
- << QString("408c073e3e2538072b72625e68b8364b")
- << QString("50515253555657585a5b5c5d5f606162");
- QTest::newRow("6") << QString("67429969490b9711ae2b01dc497afde8")
- << QString("e1f94dfa776597beaca262f2f6366fea")
- << QString("64656667696a6b6c6e6f707173747576");
- QTest::newRow("7") << QString("93385c1f2aec8bed192f5a8e161dd508")
- << QString("f29e986c6a1c27d7b29ffd7ee92b75f1")
- << QString("78797a7b7d7e7f80828384858788898a");
- QTest::newRow("8") << QString("3e23b3bc065bcc152407e23896d77783")
- << QString("1959338344e945670678a5d432c90b93")
- << QString("54555657595a5b5c5e5f606163646566");
- QTest::newRow("9") << QString("79f0fba002be1744670e7e99290d8f52")
- << QString("e49bddd2369b83ee66e6c75a1161b394")
- << QString("68696a6b6d6e6f70727374757778797a");
- QTest::newRow("10") << QString("da23fe9d5bd63e1d72e3dafbe21a6c2a")
- << QString("d3388f19057ff704b70784164a74867d")
- << QString("7c7d7e7f81828384868788898b8c8d8e");
- QTest::newRow("11") << QString("e3f5698ba90b6a022efd7db2c7e6c823")
- << QString("23aa03e2d5e4cd24f3217e596480d1e1")
- << QString("a4a5a6a7a9aaabacaeafb0b1b3b4b5b6");
- QTest::newRow("12") << QString("bdc2691d4f1b73d2700679c3bcbf9c6e")
- << QString("c84113d68b666ab2a50a8bdb222e91b9")
- << QString("e0e1e2e3e5e6e7e8eaebecedeff0f1f2");
- QTest::newRow("13") << QString("ba74e02093217ee1ba1b42bd5624349a")
- << QString("ac02403981cd4340b507963db65cb7b6")
- << QString("08090a0b0d0e0f10121314151718191a");
- QTest::newRow("14") << QString("b5c593b5851c57fbf8b3f57715e8f680")
- << QString("8d1299236223359474011f6bf5088414")
- << QString("6c6d6e6f71727374767778797b7c7d7e");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+
+ // Not sure where this came from...
+ QTest::newRow("mystery") << QString("506812a45f08c889b97f5980038b8359")
+ << QString("d8f532538289ef7d06b506a4fd5be9c9")
+ << QString("00010203050607080a0b0c0d0f101112");
+
+ // From FIPS 197 Appendix C.1
+ QTest::newRow("FIPS197 App C.1") << QString("00112233445566778899aabbccddeeff")
+ << QString("69c4e0d86a7b0430d8cdb78070b4c55a")
+ << QString("000102030405060708090a0b0c0d0e0f");
+
+ // These are from the Botan test suite
+ QTest::newRow("1") << QString("506812a45f08c889b97f5980038b8359")
+ << QString("d8f532538289ef7d06b506a4fd5be9c9")
+ << QString("00010203050607080a0b0c0d0f101112");
+ QTest::newRow("2") << QString("5c6d71ca30de8b8b00549984d2ec7d4b")
+ << QString("59ab30f4d4ee6e4ff9907ef65b1fb68c")
+ << QString("14151617191a1b1c1e1f202123242526");
+ QTest::newRow("3") << QString("53f3f4c64f8616e4e7c56199f48f21f6")
+ << QString("bf1ed2fcb2af3fd41443b56d85025cb1")
+ << QString("28292a2b2d2e2f30323334353738393a");
+ QTest::newRow("4") << QString("a1eb65a3487165fb0f1c27ff9959f703")
+ << QString("7316632d5c32233edcb0780560eae8b2")
+ << QString("3c3d3e3f41424344464748494b4c4d4e");
+ QTest::newRow("5") << QString("3553ecf0b1739558b08e350a98a39bfa")
+ << QString("408c073e3e2538072b72625e68b8364b")
+ << QString("50515253555657585a5b5c5d5f606162");
+ QTest::newRow("6") << QString("67429969490b9711ae2b01dc497afde8")
+ << QString("e1f94dfa776597beaca262f2f6366fea")
+ << QString("64656667696a6b6c6e6f707173747576");
+ QTest::newRow("7") << QString("93385c1f2aec8bed192f5a8e161dd508")
+ << QString("f29e986c6a1c27d7b29ffd7ee92b75f1")
+ << QString("78797a7b7d7e7f80828384858788898a");
+ QTest::newRow("8") << QString("3e23b3bc065bcc152407e23896d77783")
+ << QString("1959338344e945670678a5d432c90b93")
+ << QString("54555657595a5b5c5e5f606163646566");
+ QTest::newRow("9") << QString("79f0fba002be1744670e7e99290d8f52")
+ << QString("e49bddd2369b83ee66e6c75a1161b394")
+ << QString("68696a6b6d6e6f70727374757778797a");
+ QTest::newRow("10") << QString("da23fe9d5bd63e1d72e3dafbe21a6c2a")
+ << QString("d3388f19057ff704b70784164a74867d")
+ << QString("7c7d7e7f81828384868788898b8c8d8e");
+ QTest::newRow("11") << QString("e3f5698ba90b6a022efd7db2c7e6c823")
+ << QString("23aa03e2d5e4cd24f3217e596480d1e1")
+ << QString("a4a5a6a7a9aaabacaeafb0b1b3b4b5b6");
+ QTest::newRow("12") << QString("bdc2691d4f1b73d2700679c3bcbf9c6e")
+ << QString("c84113d68b666ab2a50a8bdb222e91b9")
+ << QString("e0e1e2e3e5e6e7e8eaebecedeff0f1f2");
+ QTest::newRow("13") << QString("ba74e02093217ee1ba1b42bd5624349a")
+ << QString("ac02403981cd4340b507963db65cb7b6")
+ << QString("08090a0b0d0e0f10121314151718191a");
+ QTest::newRow("14") << QString("b5c593b5851c57fbf8b3f57715e8f680")
+ << QString("8d1299236223359474011f6bf5088414")
+ << QString("6c6d6e6f71727374767778797b7c7d7e");
}
-
void CipherUnitTest::aes128()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- // providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ // providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes128-ecb", provider ) )
- QWARN( QString( "AES128 ECB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes128-ecb", provider)) {
+ QWARN(QString("AES128 ECB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::Cipher forwardCipher( QString( "aes128" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::Cipher forwardCipher(QString("aes128"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( forwardCipher.blockSize(), 16 );
- QCOMPARE( forwardCipher.keyLength().minimum(), 16 );
- QCOMPARE( forwardCipher.keyLength().maximum(), 16 );
+ QCOMPARE(forwardCipher.blockSize(), 16);
+ QCOMPARE(forwardCipher.keyLength().minimum(), 16);
+ QCOMPARE(forwardCipher.keyLength().maximum(), 16);
- QString afterEncodeText = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ QString afterEncodeText = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
- afterEncodeText += QCA::arrayToHex( forwardCipher.final().toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ afterEncodeText += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ QVERIFY(forwardCipher.ok());
- QCOMPARE( afterEncodeText, cipherText );
+ QCOMPARE(afterEncodeText, cipherText);
- QCA::Cipher reverseCipher( QString( "aes128" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::Cipher reverseCipher(QString("aes128"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( reverseCipher.blockSize(), 16 );
- QCOMPARE( reverseCipher.keyLength().minimum(), 16 );
- QCOMPARE( reverseCipher.keyLength().maximum(), 16 );
+ QCOMPARE(reverseCipher.blockSize(), 16);
+ QCOMPARE(reverseCipher.keyLength().minimum(), 16);
+ QCOMPARE(reverseCipher.keyLength().maximum(), 16);
- QString afterDecodeText = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ QString afterDecodeText = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
- afterDecodeText += QCA::arrayToHex( reverseCipher.final().toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ afterDecodeText += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QVERIFY(reverseCipher.ok());
- QCOMPARE( afterDecodeText, plainText );
- }
- }
+ QCOMPARE(afterDecodeText, plainText);
+ }
+ }
}
-
// This is from the Botan test suite
void CipherUnitTest::aes128_cbc_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("7649abac8119b246cee98e9b12e9197d5086cb9b507219ee95db113a917678b273bed6b8e3c1743b7116e69e222295163ff1caa1681fac09120eca307586e1a7")
- << QString("2b7e151628aed2a6abf7158809cf4f3c")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("7649abac8119b246cee98e9b12e9197d5086cb9b507219ee95db113a917678b273bed6b8e3c1743b7116e69e222295163ff1caa1681fac09120eca307586e1a7")
+ << QString("2b7e151628aed2a6abf7158809cf4f3c")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes128_cbc()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes128-cbc", provider ) )
- QWARN( QString( "AES128 CBC not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes128" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes128" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes128-cbc", provider)) {
+ QWARN(QString("AES128 CBC not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes128"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes128"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// These were generated using OpenSSL's enc command
void CipherUnitTest::aes128_cbc_pkcs7_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("")
- << QString("18fe62efa4dc4b21a4127b225855b475")
- << QString("0123456789ABCDEF0123456789ABCDEF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("1") << QString("")
+ << QString("18fe62efa4dc4b21a4127b225855b475")
+ << QString("0123456789ABCDEF0123456789ABCDEF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("2") << QString("610a")
- << QString("92823eab12924cd168f54d3f4baa9a4d")
- << QString("0123456789ABCDEF0123456789ABCDEF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("2") << QString("610a")
+ << QString("92823eab12924cd168f54d3f4baa9a4d")
+ << QString("0123456789ABCDEF0123456789ABCDEF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("3") << QString("6162636465666768696a0a")
- << QString("9d41b355abd61e3dfa482f3c1aeaae49")
- << QString("0123456789ABCDEF0123456789ABCDEF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("3") << QString("6162636465666768696a0a")
+ << QString("9d41b355abd61e3dfa482f3c1aeaae49")
+ << QString("0123456789ABCDEF0123456789ABCDEF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size - 1") << QString("6162636465666768696a6b6c6d6e0a")
- << QString("c86b53850815cae7ae4a6e7529a87587")
- << QString("0123456789ABCDEF0123456789ABCDEF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size - 1") << QString("6162636465666768696a6b6c6d6e0a")
+ << QString("c86b53850815cae7ae4a6e7529a87587")
+ << QString("0123456789ABCDEF0123456789ABCDEF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size") << QString("6162636465666768696a6b6c6d6e310a")
- << QString("26fb0474b70d118f2b1d5b74e58c97bf3bb81bece1250509c5c68771ae23ceac")
- << QString("0123456789ABCDEF0123456789ABCDEF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size") << QString("6162636465666768696a6b6c6d6e310a")
+ << QString("26fb0474b70d118f2b1d5b74e58c97bf3bb81bece1250509c5c68771ae23ceac")
+ << QString("0123456789ABCDEF0123456789ABCDEF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size+1") << QString("6162636465666768696a6b6c6d6e6f310a")
- << QString("656f5c5693741967e059149e9239452fa286ac7c86ef653182d226d543d53013")
- << QString("0123456789ABCDEF0123456789ABCDEF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size+1") << QString("6162636465666768696a6b6c6d6e6f310a")
+ << QString("656f5c5693741967e059149e9239452fa286ac7c86ef653182d226d543d53013")
+ << QString("0123456789ABCDEF0123456789ABCDEF")
+ << QString("00001111222233334444555566667777");
}
void CipherUnitTest::aes128_cbc_pkcs7()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes128-cbc-pkcs7", provider ) )
- QWARN( QString( "AES128 CBC with PKCS7 padding not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes128" ),
- QCA::Cipher::CBC,
- QCA::Cipher::DefaultPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes128" ),
- QCA::Cipher::CBC,
- QCA::Cipher::DefaultPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes128-cbc-pkcs7", provider)) {
+ QWARN(QString("AES128 CBC with PKCS7 padding not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes128"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::DefaultPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes128"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::DefaultPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// This is from the Botan test suite
void CipherUnitTest::aes128_cfb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("3b3fd92eb72dad20333449f8e83cfb4ac8a64537a0b3a93fcde3cdad9f1ce58b26751f67a3cbb140b1808cf187a4f4dfc04b05357c5d1c0eeac4c66f9ff7f2e6")
- << QString("2b7e151628aed2a6abf7158809cf4f3c")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("3b3fd92eb72dad20333449f8e83cfb4ac8a64537a0b3a93fcde3cdad9f1ce58b26751f67a3cbb140b1808cf187a4f4dfc04b05357c5d1c0eeac4c66f9ff7f2e6")
+ << QString("2b7e151628aed2a6abf7158809cf4f3c")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes128_cfb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes128-cfb", provider ) )
- QWARN( QString( "AES128 CFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes128" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes128" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes128-cfb", provider)) {
+ QWARN(QString("AES128 CFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes128"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes128"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// This is from the Botan test suite
void CipherUnitTest::aes128_ofb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("3b3fd92eb72dad20333449f8e83cfb4a7789508d16918f03f53c52dac54ed8259740051e9c5fecf64344f7a82260edcc304c6528f659c77866a510d9c1d6ae5e")
- << QString("2b7e151628aed2a6abf7158809cf4f3c")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("3b3fd92eb72dad20333449f8e83cfb4a7789508d16918f03f53c52dac54ed8259740051e9c5fecf64344f7a82260edcc304c6528f659c77866a510d9c1d6ae5e")
+ << QString("2b7e151628aed2a6abf7158809cf4f3c")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes128_ofb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes128-ofb", provider ) )
- QWARN( QString( "AES128 OFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes128" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes128" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes128-ofb", provider)) {
+ QWARN(QString("AES128 OFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes128"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes128"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes128_ctr_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("3b3fd92eb72dad20333449f8e83cfb4a010c041999e03f36448624483e582d0ea62293cfa6df74535c354181168774df2d55a54706273c50d7b4f8a8cddc6ed7")
- << QString("2b7e151628aed2a6abf7158809cf4f3c")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("3b3fd92eb72dad20333449f8e83cfb4a010c041999e03f36448624483e582d0ea62293cfa6df74535c354181168774df2d55a54706273c50d7b4f8a8cddc6ed7")
+ << QString("2b7e151628aed2a6abf7158809cf4f3c")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes128_ctr()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes128-ctr", provider ) )
- QWARN( QString( "AES128 CTR not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes128" ),
- QCA::Cipher::CTR,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes128" ),
- QCA::Cipher::CTR,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes128-ctr", provider)) {
+ QWARN(QString("AES128 CTR not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes128"),
+ QCA::Cipher::CTR,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes128"),
+ QCA::Cipher::CTR,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes128_gcm_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("payload");
- QTest::addColumn<QString>("tag");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("payload");
+ QTest::addColumn<QString>("tag");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("short") << QString("6f6820526f6d656d6f21")
- << QString("a9f2558b9a74e6fc551f")
- << QString("f8ebf75f108c6f74e6fe49035d268d43")
- << QString("1f491f8ddf4856ae4bff9039d418175a")
- << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
+ QTest::newRow("short") << QString("6f6820526f6d656d6f21")
+ << QString("a9f2558b9a74e6fc551f")
+ << QString("f8ebf75f108c6f74e6fe49035d268d43")
+ << QString("1f491f8ddf4856ae4bff9039d418175a")
+ << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
- QTest::newRow("long") << QString("54484520515549434b2042524f574e20464f58204a554d504544204f56455220544845204c415a5920444f472753204241434b2031323334353637383930")
- << QString("04e321a8870b6b9cd6846239c27a63fb41d0a7b8994f1514c066f0427fa9ed6707ea6e3b4f161fdff0eb5fc087ed3827b569cd72456c697b5a3a62c9e767")
- << QString("b0ad4aa545ea25fc3117cbed955ff155")
- << QString("56341f2b431d3b0dbad787db003f2215")
- << QString("bfcd3a7252f7f199bf788df8cf61032a");
+ QTest::newRow("long") << QString("54484520515549434b2042524f574e20464f58204a554d504544204f56455220544845204c415a5920444f472753204241434b2031323334353637383930")
+ << QString("04e321a8870b6b9cd6846239c27a63fb41d0a7b8994f1514c066f0427fa9ed6707ea6e3b4f161fdff0eb5fc087ed3827b569cd72456c697b5a3a62c9e767")
+ << QString("b0ad4aa545ea25fc3117cbed955ff155")
+ << QString("56341f2b431d3b0dbad787db003f2215")
+ << QString("bfcd3a7252f7f199bf788df8cf61032a");
-
- QTest::newRow("wrongtag") << QString("6f6820526f6d656d6f21")
- << QString("a9f2558b9a74e6fc551f")
- << QString("f8ebf75f108c6f74e6fe49035d268d44")
- << QString("1f491f8ddf4856ae4bff9039d418175a")
- << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
+ QTest::newRow("wrongtag") << QString("6f6820526f6d656d6f21")
+ << QString("a9f2558b9a74e6fc551f")
+ << QString("f8ebf75f108c6f74e6fe49035d268d44")
+ << QString("1f491f8ddf4856ae4bff9039d418175a")
+ << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
}
void CipherUnitTest::aes128_gcm()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach (const QString &provider, providersToTest) {
- if (!QCA::isSupported( "aes128-gcm", provider))
- QWARN(QString("AES128 GCM not supported for " + provider).toLocal8Bit());
- else {
- QFETCH(QString, plainText);
- QFETCH(QString, payload);
- QFETCH(QString, tag);
- QFETCH(QString, keyText);
- QFETCH(QString, ivText);
-
- QCA::SymmetricKey key(QCA::hexToArray(keyText));
- QCA::InitializationVector iv(QCA::hexToArray(ivText));
- QCA::AuthTag authTag(16);
- QCA::Cipher forwardCipher(QString("aes128"),
- QCA::Cipher::GCM,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- authTag,
- provider);
- QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
- QVERIFY(forwardCipher.ok());
- update += QCA::arrayToHex(forwardCipher.final().toByteArray());
- authTag = forwardCipher.tag();
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QCOMPARE(QCA::arrayToHex(authTag.toByteArray()), tag);
- QCOMPARE(update, payload);
- QVERIFY(forwardCipher.ok());
-
- QCA::Cipher reverseCipher(QString( "aes128"),
- QCA::Cipher::GCM,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- QCA::AuthTag(QCA::hexToArray(tag)),
- provider);
-
- update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(payload)).toByteArray());
- QVERIFY(reverseCipher.ok());
- QCOMPARE(update, plainText.left(update.size()));
- update += QCA::arrayToHex(reverseCipher.final().toByteArray());
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QCOMPARE(update, plainText);
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QVERIFY(reverseCipher.ok());
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString &provider, providersToTest) {
+ if (!QCA::isSupported("aes128-gcm", provider)) {
+ QWARN(QString("AES128 GCM not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, payload);
+ QFETCH(QString, tag);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::AuthTag authTag(16);
+ QCA::Cipher forwardCipher(QString("aes128"),
+ QCA::Cipher::GCM,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ authTag,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ update += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ authTag = forwardCipher.tag();
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QCOMPARE(QCA::arrayToHex(authTag.toByteArray()), tag);
+ QCOMPARE(update, payload);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes128"),
+ QCA::Cipher::GCM,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ QCA::AuthTag(QCA::hexToArray(tag)),
+ provider);
+
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(payload)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ update += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QCOMPARE(update, plainText);
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes128_ccm_data()
{
}
void CipherUnitTest::aes128_ccm()
{
- // For future implementation
+ // For future implementation
}
void CipherUnitTest::aes192_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
-
-
- // From FIPS 197 Appendix C.2
- QTest::newRow("FIPS197 App C.2") << QString("00112233445566778899aabbccddeeff")
- << QString("dda97ca4864cdfe06eaf70a0ec0d7191")
- << QString("000102030405060708090A0B0C0D0E0F1011121314151617");
-
- // These are from the Botan test suite
- QTest::newRow("1") << QString("fec1c04f529bbd17d8cecfcc4718b17f")
- << QString("62564c738f3efe186e1a127a0c4d3c61")
- << QString("4a4b4c4d4f50515254555657595a5b5c5e5f606163646566");
- QTest::newRow("2") << QString("32df99b431ed5dc5acf8caf6dc6ce475")
- << QString("07805aa043986eb23693e23bef8f3438")
- << QString("68696a6b6d6e6f70727374757778797a7c7d7e7f81828384");
- QTest::newRow("3") << QString("7fdc2b746f3f665296943b83710d1f82")
- << QString("df0b4931038bade848dee3b4b85aa44b")
- << QString("868788898b8c8d8e90919293959697989a9b9c9d9fa0a1a2");
- QTest::newRow("4") << QString("8fba1510a3c5b87e2eaa3f7a91455ca2")
- << QString("592d5fded76582e4143c65099309477c")
- << QString("a4a5a6a7a9aaabacaeafb0b1b3b4b5b6b8b9babbbdbebfc0");
- QTest::newRow("5") << QString("2c9b468b1c2eed92578d41b0716b223b")
- << QString("c9b8d6545580d3dfbcdd09b954ed4e92")
- << QString("c2c3c4c5c7c8c9cacccdcecfd1d2d3d4d6d7d8d9dbdcddde");
- QTest::newRow("6") << QString("0a2bbf0efc6bc0034f8a03433fca1b1a")
- << QString("5dccd5d6eb7c1b42acb008201df707a0")
- << QString("e0e1e2e3e5e6e7e8eaebecedeff0f1f2f4f5f6f7f9fafbfc");
- QTest::newRow("7") << QString("25260e1f31f4104d387222e70632504b")
- << QString("a2a91682ffeb6ed1d34340946829e6f9")
- << QString("fefe01010304050608090a0b0d0e0f10121314151718191a");
- QTest::newRow("8") << QString("c527d25a49f08a5228d338642ae65137")
- << QString("e45d185b797000348d9267960a68435d")
- << QString("1c1d1e1f21222324262728292b2c2d2e3031323335363738");
- QTest::newRow("9") << QString("3b49fc081432f5890d0e3d87e884a69e")
- << QString("45e060dae5901cda8089e10d4f4c246b")
- << QString("3a3b3c3d3f40414244454647494a4b4c4e4f505153545556");
- QTest::newRow("10") << QString("d173f9ed1e57597e166931df2754a083")
- << QString("f6951afacc0079a369c71fdcff45df50")
- << QString("58595a5b5d5e5f60626364656768696a6c6d6e6f71727374");
- QTest::newRow("11") << QString("8c2b7cafa5afe7f13562daeae1adede0")
- << QString("9e95e00f351d5b3ac3d0e22e626ddad6")
- << QString("767778797b7c7d7e80818283858687888a8b8c8d8f909192");
- QTest::newRow("12") << QString("aaf4ec8c1a815aeb826cab741339532c")
- << QString("9cb566ff26d92dad083b51fdc18c173c")
- << QString("94959697999a9b9c9e9fa0a1a3a4a5a6a8a9aaabadaeafb0");
- QTest::newRow("13") << QString("40be8c5d9108e663f38f1a2395279ecf")
- << QString("c9c82766176a9b228eb9a974a010b4fb")
- << QString("d0d1d2d3d5d6d7d8dadbdcdddfe0e1e2e4e5e6e7e9eaebec");
- QTest::newRow("14") << QString("0c8ad9bc32d43e04716753aa4cfbe351")
- << QString("d8e26aa02945881d5137f1c1e1386e88")
- << QString("2a2b2c2d2f30313234353637393a3b3c3e3f404143444546");
- QTest::newRow("15") << QString("1407b1d5f87d63357c8dc7ebbaebbfee")
- << QString("c0e024ccd68ff5ffa4d139c355a77c55")
- << QString("48494a4b4d4e4f50525354555758595a5c5d5e5f61626364");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+
+ // From FIPS 197 Appendix C.2
+ QTest::newRow("FIPS197 App C.2") << QString("00112233445566778899aabbccddeeff")
+ << QString("dda97ca4864cdfe06eaf70a0ec0d7191")
+ << QString("000102030405060708090A0B0C0D0E0F1011121314151617");
+
+ // These are from the Botan test suite
+ QTest::newRow("1") << QString("fec1c04f529bbd17d8cecfcc4718b17f")
+ << QString("62564c738f3efe186e1a127a0c4d3c61")
+ << QString("4a4b4c4d4f50515254555657595a5b5c5e5f606163646566");
+ QTest::newRow("2") << QString("32df99b431ed5dc5acf8caf6dc6ce475")
+ << QString("07805aa043986eb23693e23bef8f3438")
+ << QString("68696a6b6d6e6f70727374757778797a7c7d7e7f81828384");
+ QTest::newRow("3") << QString("7fdc2b746f3f665296943b83710d1f82")
+ << QString("df0b4931038bade848dee3b4b85aa44b")
+ << QString("868788898b8c8d8e90919293959697989a9b9c9d9fa0a1a2");
+ QTest::newRow("4") << QString("8fba1510a3c5b87e2eaa3f7a91455ca2")
+ << QString("592d5fded76582e4143c65099309477c")
+ << QString("a4a5a6a7a9aaabacaeafb0b1b3b4b5b6b8b9babbbdbebfc0");
+ QTest::newRow("5") << QString("2c9b468b1c2eed92578d41b0716b223b")
+ << QString("c9b8d6545580d3dfbcdd09b954ed4e92")
+ << QString("c2c3c4c5c7c8c9cacccdcecfd1d2d3d4d6d7d8d9dbdcddde");
+ QTest::newRow("6") << QString("0a2bbf0efc6bc0034f8a03433fca1b1a")
+ << QString("5dccd5d6eb7c1b42acb008201df707a0")
+ << QString("e0e1e2e3e5e6e7e8eaebecedeff0f1f2f4f5f6f7f9fafbfc");
+ QTest::newRow("7") << QString("25260e1f31f4104d387222e70632504b")
+ << QString("a2a91682ffeb6ed1d34340946829e6f9")
+ << QString("fefe01010304050608090a0b0d0e0f10121314151718191a");
+ QTest::newRow("8") << QString("c527d25a49f08a5228d338642ae65137")
+ << QString("e45d185b797000348d9267960a68435d")
+ << QString("1c1d1e1f21222324262728292b2c2d2e3031323335363738");
+ QTest::newRow("9") << QString("3b49fc081432f5890d0e3d87e884a69e")
+ << QString("45e060dae5901cda8089e10d4f4c246b")
+ << QString("3a3b3c3d3f40414244454647494a4b4c4e4f505153545556");
+ QTest::newRow("10") << QString("d173f9ed1e57597e166931df2754a083")
+ << QString("f6951afacc0079a369c71fdcff45df50")
+ << QString("58595a5b5d5e5f60626364656768696a6c6d6e6f71727374");
+ QTest::newRow("11") << QString("8c2b7cafa5afe7f13562daeae1adede0")
+ << QString("9e95e00f351d5b3ac3d0e22e626ddad6")
+ << QString("767778797b7c7d7e80818283858687888a8b8c8d8f909192");
+ QTest::newRow("12") << QString("aaf4ec8c1a815aeb826cab741339532c")
+ << QString("9cb566ff26d92dad083b51fdc18c173c")
+ << QString("94959697999a9b9c9e9fa0a1a3a4a5a6a8a9aaabadaeafb0");
+ QTest::newRow("13") << QString("40be8c5d9108e663f38f1a2395279ecf")
+ << QString("c9c82766176a9b228eb9a974a010b4fb")
+ << QString("d0d1d2d3d5d6d7d8dadbdcdddfe0e1e2e4e5e6e7e9eaebec");
+ QTest::newRow("14") << QString("0c8ad9bc32d43e04716753aa4cfbe351")
+ << QString("d8e26aa02945881d5137f1c1e1386e88")
+ << QString("2a2b2c2d2f30313234353637393a3b3c3e3f404143444546");
+ QTest::newRow("15") << QString("1407b1d5f87d63357c8dc7ebbaebbfee")
+ << QString("c0e024ccd68ff5ffa4d139c355a77c55")
+ << QString("48494a4b4d4e4f50525354555758595a5c5d5e5f61626364");
}
-
void CipherUnitTest::aes192()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- // providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ // providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes192-ecb", provider ) )
- QWARN( QString( "AES192 ECB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes192-ecb", provider)) {
+ QWARN(QString("AES192 ECB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::Cipher forwardCipher( QString( "aes192" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::Cipher forwardCipher(QString("aes192"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( forwardCipher.blockSize(), 16 );
- QCOMPARE( forwardCipher.keyLength().minimum(), 24 );
- QCOMPARE( forwardCipher.keyLength().maximum(), 24 );
+ QCOMPARE(forwardCipher.blockSize(), 16);
+ QCOMPARE(forwardCipher.keyLength().minimum(), 24);
+ QCOMPARE(forwardCipher.keyLength().maximum(), 24);
- QString afterEncodeText = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ QString afterEncodeText = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
- afterEncodeText += QCA::arrayToHex( forwardCipher.final().toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ afterEncodeText += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ QVERIFY(forwardCipher.ok());
- QCOMPARE( afterEncodeText, cipherText );
+ QCOMPARE(afterEncodeText, cipherText);
- QCA::Cipher reverseCipher( QString( "aes192" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::Cipher reverseCipher(QString("aes192"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( reverseCipher.blockSize(), 16 );
- QCOMPARE( reverseCipher.keyLength().minimum(), 24 );
- QCOMPARE( reverseCipher.keyLength().maximum(), 24 );
+ QCOMPARE(reverseCipher.blockSize(), 16);
+ QCOMPARE(reverseCipher.keyLength().minimum(), 24);
+ QCOMPARE(reverseCipher.keyLength().maximum(), 24);
- QString afterDecodeText = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ QString afterDecodeText = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
- afterDecodeText += QCA::arrayToHex( reverseCipher.final().toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ afterDecodeText += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QVERIFY(reverseCipher.ok());
- QCOMPARE( afterDecodeText, plainText );
- }
- }
+ QCOMPARE(afterDecodeText, plainText);
+ }
+ }
}
-
// This is from the Botan test suite
void CipherUnitTest::aes192_cbc_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("4f021db243bc633d7178183a9fa071e8b4d9ada9ad7dedf4e5e738763f69145a571b242012fb7ae07fa9baac3df102e008b0e27988598881d920a9e64f5615cd")
- << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("4f021db243bc633d7178183a9fa071e8b4d9ada9ad7dedf4e5e738763f69145a571b242012fb7ae07fa9baac3df102e008b0e27988598881d920a9e64f5615cd")
+ << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
-
void CipherUnitTest::aes192_cbc()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes192-cbc", provider ) )
- QWARN( QString( "AES192 CBC not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes192" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes192" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes192-cbc", provider)) {
+ QWARN(QString("AES192 CBC not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes192"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes192"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// These were generated using OpenSSL's enc command
void CipherUnitTest::aes192_cbc_pkcs7_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("")
- << QString("49c1da70f461d1bb5147ded60f0f01ef")
- << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("1") << QString("")
+ << QString("49c1da70f461d1bb5147ded60f0f01ef")
+ << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("2") << QString("610a")
- << QString("42e5a030df8b6bf896899853744e480c")
- << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("2") << QString("610a")
+ << QString("42e5a030df8b6bf896899853744e480c")
+ << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("3") << QString("6162636465666768696a0a")
- << QString("160a3b6ff48d6850906ffa6b8291f511")
- << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("3") << QString("6162636465666768696a0a")
+ << QString("160a3b6ff48d6850906ffa6b8291f511")
+ << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size - 1") << QString("6162636465666768696a6b6c6d6e0a")
- << QString("b113c5aec849e49dc8487f66ce29bab0")
- << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size - 1") << QString("6162636465666768696a6b6c6d6e0a")
+ << QString("b113c5aec849e49dc8487f66ce29bab0")
+ << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size") << QString("6162636465666768696a6b6c6d6e310a")
- << QString("80c4a001f93c468b7dd3525cc46020b470e3ac39a13be57ab18c7903d121a266")
- << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size") << QString("6162636465666768696a6b6c6d6e310a")
+ << QString("80c4a001f93c468b7dd3525cc46020b470e3ac39a13be57ab18c7903d121a266")
+ << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size+1") << QString("6162636465666768696a6b6c6d6e6f310a")
- << QString("f0f9982e4118287cda37062f5acfd7b2f27741ddac7bd3882c7b4e4872b81047")
- << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size+1") << QString("6162636465666768696a6b6c6d6e6f310a")
+ << QString("f0f9982e4118287cda37062f5acfd7b2f27741ddac7bd3882c7b4e4872b81047")
+ << QString("0123456789ABCDEF0123456789ABCDEF0011223344556677")
+ << QString("00001111222233334444555566667777");
}
void CipherUnitTest::aes192_cbc_pkcs7()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes192-cbc-pkcs7", provider ) )
- QWARN( QString( "AES192 CBC with PKCS7 padding not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes192" ),
- QCA::Cipher::CBC,
- QCA::Cipher::DefaultPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes192" ),
- QCA::Cipher::CBC,
- QCA::Cipher::DefaultPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes192-cbc-pkcs7", provider)) {
+ QWARN(QString("AES192 CBC with PKCS7 padding not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes192"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::DefaultPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes192"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::DefaultPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
-
// This is from the Botan test suite
void CipherUnitTest::aes192_cfb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("cdc80d6fddf18cab34c25909c99a417467ce7f7f81173621961a2b70171d3d7a2e1e8a1dd59b88b1c8e60fed1efac4c9c05f9f9ca9834fa042ae8fba584b09ff")
- << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("cdc80d6fddf18cab34c25909c99a417467ce7f7f81173621961a2b70171d3d7a2e1e8a1dd59b88b1c8e60fed1efac4c9c05f9f9ca9834fa042ae8fba584b09ff")
+ << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes192_cfb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes192-cfb", provider ) )
- QWARN( QString( "AES192 CFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes192" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes192" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes192-cfb", provider)) {
+ QWARN(QString("AES192 CFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes192"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes192"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// This is from the Botan test suite
void CipherUnitTest::aes192_ofb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("cdc80d6fddf18cab34c25909c99a4174fcc28b8d4c63837c09e81700c11004018d9a9aeac0f6596f559c6d4daf59a5f26d9f200857ca6c3e9cac524bd9acc92a")
- << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("cdc80d6fddf18cab34c25909c99a4174fcc28b8d4c63837c09e81700c11004018d9a9aeac0f6596f559c6d4daf59a5f26d9f200857ca6c3e9cac524bd9acc92a")
+ << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes192_ofb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes192-ofb", provider ) )
- QWARN( QString( "AES192 OFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes192" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes192" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes192-ofb", provider)) {
+ QWARN(QString("AES192 OFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes192"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes192"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes192_ctr_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("cdc80d6fddf18cab34c25909c99a417437d8a639171fdcca63ebd17ce2d7321a79a0c96b53c7eeecd9ed7157c444fc7a845c37b2f511697b0e89d5ed60c4d49e")
- << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("cdc80d6fddf18cab34c25909c99a417437d8a639171fdcca63ebd17ce2d7321a79a0c96b53c7eeecd9ed7157c444fc7a845c37b2f511697b0e89d5ed60c4d49e")
+ << QString("8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes192_ctr()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes192-ctr", provider ) )
- QWARN( QString( "AES192 CTR not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes192" ),
- QCA::Cipher::CTR,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes192" ),
- QCA::Cipher::CTR,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes192-ctr", provider)) {
+ QWARN(QString("AES192 CTR not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes192"),
+ QCA::Cipher::CTR,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes192"),
+ QCA::Cipher::CTR,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes192_gcm_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("payload");
- QTest::addColumn<QString>("tag");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
-
- QTest::newRow("short") << QString("6f6820526f6d656d6f21")
- << QString("01ca25ff74121917f397")
- << QString("b90e97706d8eacbabc0be5e0a671b4e4")
- << QString("7ecb21a647fae54a0996ad281ab0c1a00cb905d9e2eb3b82")
- << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("payload");
+ QTest::addColumn<QString>("tag");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("long") << QString("54484520515549434b2042524f574e20464f58204a554d504544204f56455220544845204c415a5920444f472753204241434b2031323334353637383930")
- << QString("4c1c5874877f0bee6efd450ec341b1c591e1e100da40bd4744e1035ed0ed0fb458f8efdb7c4b0b2101e29c950c56dc2489c2febec2d7062da28b9a033173")
- << QString("af3ea1b7f275ea1e4d4e1fdce63f83fe")
- << QString("7ecb21a647fae54a0996ad281ab0c1a00cb905d9e2eb3b82")
- << QString("bfcd3a7252f7f199bf788df8cf61032a");
+ QTest::newRow("short") << QString("6f6820526f6d656d6f21")
+ << QString("01ca25ff74121917f397")
+ << QString("b90e97706d8eacbabc0be5e0a671b4e4")
+ << QString("7ecb21a647fae54a0996ad281ab0c1a00cb905d9e2eb3b82")
+ << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
+ QTest::newRow("long") << QString("54484520515549434b2042524f574e20464f58204a554d504544204f56455220544845204c415a5920444f472753204241434b2031323334353637383930")
+ << QString("4c1c5874877f0bee6efd450ec341b1c591e1e100da40bd4744e1035ed0ed0fb458f8efdb7c4b0b2101e29c950c56dc2489c2febec2d7062da28b9a033173")
+ << QString("af3ea1b7f275ea1e4d4e1fdce63f83fe")
+ << QString("7ecb21a647fae54a0996ad281ab0c1a00cb905d9e2eb3b82")
+ << QString("bfcd3a7252f7f199bf788df8cf61032a");
- QTest::newRow("wrongtag") << QString("6f6820526f6d656d6f21")
- << QString("773c3d06b94727c04afc")
- << QString("c558aca7f19050db49d94d99119277af")
- << QString("7ecb21a647fae54a0996ad281ab0c1a00cb905d9e2eb3b82")
- << QString("bfcd3a7252f7f199bf788df8cf61032a");
+ QTest::newRow("wrongtag") << QString("6f6820526f6d656d6f21")
+ << QString("773c3d06b94727c04afc")
+ << QString("c558aca7f19050db49d94d99119277af")
+ << QString("7ecb21a647fae54a0996ad281ab0c1a00cb905d9e2eb3b82")
+ << QString("bfcd3a7252f7f199bf788df8cf61032a");
}
void CipherUnitTest::aes192_gcm()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach (const QString &provider, providersToTest) {
- if (!QCA::isSupported( "aes192-gcm", provider))
- QWARN(QString("AES128 GCM not supported for " + provider).toLocal8Bit());
- else {
- QFETCH(QString, plainText);
- QFETCH(QString, payload);
- QFETCH(QString, tag);
- QFETCH(QString, keyText);
- QFETCH(QString, ivText);
-
- QCA::SymmetricKey key(QCA::hexToArray(keyText));
- QCA::InitializationVector iv(QCA::hexToArray(ivText));
- QCA::AuthTag authTag(16);
- QCA::Cipher forwardCipher(QString("aes192"),
- QCA::Cipher::GCM,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- authTag,
- provider);
- QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
- QVERIFY(forwardCipher.ok());
- update += QCA::arrayToHex(forwardCipher.final().toByteArray());
- authTag = forwardCipher.tag();
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QCOMPARE(QCA::arrayToHex(authTag.toByteArray()), tag);
- QCOMPARE(update, payload);
- QVERIFY(forwardCipher.ok());
-
- QCA::Cipher reverseCipher(QString( "aes192"),
- QCA::Cipher::GCM,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- QCA::AuthTag(QCA::hexToArray(tag)),
- provider);
-
- update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(payload)).toByteArray());
- QVERIFY(reverseCipher.ok());
- QCOMPARE(update, plainText.left(update.size()));
- update += QCA::arrayToHex(reverseCipher.final().toByteArray());
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QCOMPARE(update, plainText);
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QVERIFY(reverseCipher.ok());
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString &provider, providersToTest) {
+ if (!QCA::isSupported("aes192-gcm", provider)) {
+ QWARN(QString("AES128 GCM not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, payload);
+ QFETCH(QString, tag);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::AuthTag authTag(16);
+ QCA::Cipher forwardCipher(QString("aes192"),
+ QCA::Cipher::GCM,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ authTag,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ update += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ authTag = forwardCipher.tag();
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QCOMPARE(QCA::arrayToHex(authTag.toByteArray()), tag);
+ QCOMPARE(update, payload);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes192"),
+ QCA::Cipher::GCM,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ QCA::AuthTag(QCA::hexToArray(tag)),
+ provider);
+
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(payload)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ update += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QCOMPARE(update, plainText);
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
-
void CipherUnitTest::aes192_ccm_data()
{
}
void CipherUnitTest::aes192_ccm()
{
- // For future implementation
+ // For future implementation
}
void CipherUnitTest::aes256_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
-
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
- // From FIPS 197 Appendix C.3
- QTest::newRow("FIPS197 App C.3") << QString("00112233445566778899aabbccddeeff")
- << QString("8ea2b7ca516745bfeafc49904b496089")
- << QString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
+ // From FIPS 197 Appendix C.3
+ QTest::newRow("FIPS197 App C.3") << QString("00112233445566778899aabbccddeeff")
+ << QString("8ea2b7ca516745bfeafc49904b496089")
+ << QString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
- // These are from the Botan test suite
- QTest::newRow("1") << QString("e51aa0b135dba566939c3b6359a980c5")
- << QString("8cd9423dfc459e547155c5d1d522e540")
- << QString("e0e1e2e3e5e6e7e8eaebecedeff0f1f2f4f5f6f7f9fafbfcfefe010103040506");
+ // These are from the Botan test suite
+ QTest::newRow("1") << QString("e51aa0b135dba566939c3b6359a980c5")
+ << QString("8cd9423dfc459e547155c5d1d522e540")
+ << QString("e0e1e2e3e5e6e7e8eaebecedeff0f1f2f4f5f6f7f9fafbfcfefe010103040506");
- QTest::newRow("2") << QString("069a007fc76a459f98baf917fedf9521")
- << QString("080e9517eb1677719acf728086040ae3")
- << QString("08090a0b0d0e0f10121314151718191a1c1d1e1f21222324262728292b2c2d2e");
+ QTest::newRow("2") << QString("069a007fc76a459f98baf917fedf9521")
+ << QString("080e9517eb1677719acf728086040ae3")
+ << QString("08090a0b0d0e0f10121314151718191a1c1d1e1f21222324262728292b2c2d2e");
- QTest::newRow("3") << QString("726165c1723fbcf6c026d7d00b091027")
- << QString("7c1700211a3991fc0ecded0ab3e576b0")
- << QString("30313233353637383a3b3c3d3f40414244454647494a4b4c4e4f505153545556");
+ QTest::newRow("3") << QString("726165c1723fbcf6c026d7d00b091027")
+ << QString("7c1700211a3991fc0ecded0ab3e576b0")
+ << QString("30313233353637383a3b3c3d3f40414244454647494a4b4c4e4f505153545556");
- QTest::newRow("4") << QString("d7c544de91d55cfcde1f84ca382200ce")
- << QString("dabcbcc855839251db51e224fbe87435")
- << QString("58595a5b5d5e5f60626364656768696a6c6d6e6f71727374767778797b7c7d7e");
+ QTest::newRow("4") << QString("d7c544de91d55cfcde1f84ca382200ce")
+ << QString("dabcbcc855839251db51e224fbe87435")
+ << QString("58595a5b5d5e5f60626364656768696a6c6d6e6f71727374767778797b7c7d7e");
- QTest::newRow("5") << QString("fed3c9a161b9b5b2bd611b41dc9da357")
- << QString("68d56fad0406947a4dd27a7448c10f1d")
- << QString("80818283858687888a8b8c8d8f90919294959697999a9b9c9e9fa0a1a3a4a5a6");
+ QTest::newRow("5") << QString("fed3c9a161b9b5b2bd611b41dc9da357")
+ << QString("68d56fad0406947a4dd27a7448c10f1d")
+ << QString("80818283858687888a8b8c8d8f90919294959697999a9b9c9e9fa0a1a3a4a5a6");
- QTest::newRow("6") << QString("4f634cdc6551043409f30b635832cf82")
- << QString("da9a11479844d1ffee24bbf3719a9925")
- << QString("a8a9aaabadaeafb0b2b3b4b5b7b8b9babcbdbebfc1c2c3c4c6c7c8c9cbcccdce");
+ QTest::newRow("6") << QString("4f634cdc6551043409f30b635832cf82")
+ << QString("da9a11479844d1ffee24bbf3719a9925")
+ << QString("a8a9aaabadaeafb0b2b3b4b5b7b8b9babcbdbebfc1c2c3c4c6c7c8c9cbcccdce");
- QTest::newRow("7") << QString("109ce98db0dfb36734d9f3394711b4e6")
- << QString("5e4ba572f8d23e738da9b05ba24b8d81")
- << QString("d0d1d2d3d5d6d7d8dadbdcdddfe0e1e2e4e5e6e7e9eaebeceeeff0f1f3f4f5f6");
+ QTest::newRow("7") << QString("109ce98db0dfb36734d9f3394711b4e6")
+ << QString("5e4ba572f8d23e738da9b05ba24b8d81")
+ << QString("d0d1d2d3d5d6d7d8dadbdcdddfe0e1e2e4e5e6e7e9eaebeceeeff0f1f3f4f5f6");
- QTest::newRow("8") << QString("4ea6dfaba2d8a02ffdffa89835987242")
- << QString("a115a2065d667e3f0b883837a6e903f8")
- << QString("70717273757677787a7b7c7d7f80818284858687898a8b8c8e8f909193949596");
+ QTest::newRow("8") << QString("4ea6dfaba2d8a02ffdffa89835987242")
+ << QString("a115a2065d667e3f0b883837a6e903f8")
+ << QString("70717273757677787a7b7c7d7f80818284858687898a8b8c8e8f909193949596");
- QTest::newRow("9") << QString("5ae094f54af58e6e3cdbf976dac6d9ef")
- << QString("3e9e90dc33eac2437d86ad30b137e66e")
- << QString("98999a9b9d9e9fa0a2a3a4a5a7a8a9aaacadaeafb1b2b3b4b6b7b8b9bbbcbdbe");
+ QTest::newRow("9") << QString("5ae094f54af58e6e3cdbf976dac6d9ef")
+ << QString("3e9e90dc33eac2437d86ad30b137e66e")
+ << QString("98999a9b9d9e9fa0a2a3a4a5a7a8a9aaacadaeafb1b2b3b4b6b7b8b9bbbcbdbe");
- QTest::newRow("10") << QString("764d8e8e0f29926dbe5122e66354fdbe")
- << QString("01ce82d8fbcdae824cb3c48e495c3692")
- << QString("c0c1c2c3c5c6c7c8cacbcccdcfd0d1d2d4d5d6d7d9dadbdcdedfe0e1e3e4e5e6");
+ QTest::newRow("10") << QString("764d8e8e0f29926dbe5122e66354fdbe")
+ << QString("01ce82d8fbcdae824cb3c48e495c3692")
+ << QString("c0c1c2c3c5c6c7c8cacbcccdcfd0d1d2d4d5d6d7d9dadbdcdedfe0e1e3e4e5e6");
- QTest::newRow("11") << QString("3f0418f888cdf29a982bf6b75410d6a9")
- << QString("0c9cff163ce936faaf083cfd3dea3117")
- << QString("e8e9eaebedeeeff0f2f3f4f5f7f8f9fafcfdfeff01020304060708090b0c0d0e");
+ QTest::newRow("11") << QString("3f0418f888cdf29a982bf6b75410d6a9")
+ << QString("0c9cff163ce936faaf083cfd3dea3117")
+ << QString("e8e9eaebedeeeff0f2f3f4f5f7f8f9fafcfdfeff01020304060708090b0c0d0e");
- QTest::newRow("12") << QString("e4a3e7cb12cdd56aa4a75197a9530220")
- << QString("5131ba9bd48f2bba85560680df504b52")
- << QString("10111213151617181a1b1c1d1f20212224252627292a2b2c2e2f303133343536");
+ QTest::newRow("12") << QString("e4a3e7cb12cdd56aa4a75197a9530220")
+ << QString("5131ba9bd48f2bba85560680df504b52")
+ << QString("10111213151617181a1b1c1d1f20212224252627292a2b2c2e2f303133343536");
- QTest::newRow("13") << QString("211677684aac1ec1a160f44c4ebf3f26")
- << QString("9dc503bbf09823aec8a977a5ad26ccb2")
- << QString("38393a3b3d3e3f40424344454748494a4c4d4e4f51525354565758595b5c5d5e");
+ QTest::newRow("13") << QString("211677684aac1ec1a160f44c4ebf3f26")
+ << QString("9dc503bbf09823aec8a977a5ad26ccb2")
+ << QString("38393a3b3d3e3f40424344454748494a4c4d4e4f51525354565758595b5c5d5e");
- QTest::newRow("14") << QString("d21e439ff749ac8f18d6d4b105e03895")
- << QString("9a6db0c0862e506a9e397225884041d7")
- << QString("60616263656667686a6b6c6d6f70717274757677797a7b7c7e7f808183848586");
+ QTest::newRow("14") << QString("d21e439ff749ac8f18d6d4b105e03895")
+ << QString("9a6db0c0862e506a9e397225884041d7")
+ << QString("60616263656667686a6b6c6d6f70717274757677797a7b7c7e7f808183848586");
- QTest::newRow("15") << QString("d9f6ff44646c4725bd4c0103ff5552a7")
- << QString("430bf9570804185e1ab6365fc6a6860c")
- << QString("88898a8b8d8e8f90929394959798999a9c9d9e9fa1a2a3a4a6a7a8a9abacadae");
+ QTest::newRow("15") << QString("d9f6ff44646c4725bd4c0103ff5552a7")
+ << QString("430bf9570804185e1ab6365fc6a6860c")
+ << QString("88898a8b8d8e8f90929394959798999a9c9d9e9fa1a2a3a4a6a7a8a9abacadae");
- QTest::newRow("16") << QString("0b1256c2a00b976250cfc5b0c37ed382")
- << QString("3525ebc02f4886e6a5a3762813e8ce8a")
- << QString("b0b1b2b3b5b6b7b8babbbcbdbfc0c1c2c4c5c6c7c9cacbcccecfd0d1d3d4d5d6");
+ QTest::newRow("16") << QString("0b1256c2a00b976250cfc5b0c37ed382")
+ << QString("3525ebc02f4886e6a5a3762813e8ce8a")
+ << QString("b0b1b2b3b5b6b7b8babbbcbdbfc0c1c2c4c5c6c7c9cacbcccecfd0d1d3d4d5d6");
- QTest::newRow("17") << QString("b056447ffc6dc4523a36cc2e972a3a79")
- << QString("07fa265c763779cce224c7bad671027b")
- << QString("d8d9dadbdddedfe0e2e3e4e5e7e8e9eaecedeeeff1f2f3f4f6f7f8f9fbfcfdfe");
+ QTest::newRow("17") << QString("b056447ffc6dc4523a36cc2e972a3a79")
+ << QString("07fa265c763779cce224c7bad671027b")
+ << QString("d8d9dadbdddedfe0e2e3e4e5e7e8e9eaecedeeeff1f2f3f4f6f7f8f9fbfcfdfe");
- QTest::newRow("18") << QString("5e25ca78f0de55802524d38da3fe4456")
- << QString("e8b72b4e8be243438c9fff1f0e205872")
- << QString("00010203050607080a0b0c0d0f10111214151617191a1b1c1e1f202123242526");
+ QTest::newRow("18") << QString("5e25ca78f0de55802524d38da3fe4456")
+ << QString("e8b72b4e8be243438c9fff1f0e205872")
+ << QString("00010203050607080a0b0c0d0f10111214151617191a1b1c1e1f202123242526");
- QTest::newRow("19") << QString("a5bcf4728fa5eaad8567c0dc24675f83")
- << QString("109d4f999a0e11ace1f05e6b22cbcb50")
- << QString("28292a2b2d2e2f30323334353738393a3c3d3e3f41424344464748494b4c4d4e");
+ QTest::newRow("19") << QString("a5bcf4728fa5eaad8567c0dc24675f83")
+ << QString("109d4f999a0e11ace1f05e6b22cbcb50")
+ << QString("28292a2b2d2e2f30323334353738393a3c3d3e3f41424344464748494b4c4d4e");
- QTest::newRow("20") << QString("814e59f97ed84646b78b2ca022e9ca43")
- << QString("45a5e8d4c3ed58403ff08d68a0cc4029")
- << QString("50515253555657585a5b5c5d5f60616264656667696a6b6c6e6f707173747576");
+ QTest::newRow("20") << QString("814e59f97ed84646b78b2ca022e9ca43")
+ << QString("45a5e8d4c3ed58403ff08d68a0cc4029")
+ << QString("50515253555657585a5b5c5d5f60616264656667696a6b6c6e6f707173747576");
- QTest::newRow("21") << QString("15478beec58f4775c7a7f5d4395514d7")
- << QString("196865964db3d417b6bd4d586bcb7634")
- << QString("78797a7b7d7e7f80828384858788898a8c8d8e8f91929394969798999b9c9d9e");
+ QTest::newRow("21") << QString("15478beec58f4775c7a7f5d4395514d7")
+ << QString("196865964db3d417b6bd4d586bcb7634")
+ << QString("78797a7b7d7e7f80828384858788898a8c8d8e8f91929394969798999b9c9d9e");
}
-
-
void CipherUnitTest::aes256()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- // providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ // providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes256-ecb", provider ) )
- QWARN( QString( "AES256 ECB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes256-ecb", provider)) {
+ QWARN(QString("AES256 ECB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::Cipher forwardCipher( QString( "aes256" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::Cipher forwardCipher(QString("aes256"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( forwardCipher.blockSize(), 16 );
- QCOMPARE( forwardCipher.keyLength().minimum(), 32 );
- QCOMPARE( forwardCipher.keyLength().maximum(), 32 );
+ QCOMPARE(forwardCipher.blockSize(), 16);
+ QCOMPARE(forwardCipher.keyLength().minimum(), 32);
+ QCOMPARE(forwardCipher.keyLength().maximum(), 32);
- QString afterEncodeText = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ QString afterEncodeText = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
- afterEncodeText += QCA::arrayToHex( forwardCipher.final().toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ afterEncodeText += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ QVERIFY(forwardCipher.ok());
- QCOMPARE( afterEncodeText, cipherText );
+ QCOMPARE(afterEncodeText, cipherText);
- QCA::Cipher reverseCipher( QString( "aes256" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::Cipher reverseCipher(QString("aes256"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( reverseCipher.blockSize(), 16 );
- QCOMPARE( reverseCipher.keyLength().minimum(), 32 );
- QCOMPARE( reverseCipher.keyLength().maximum(), 32 );
+ QCOMPARE(reverseCipher.blockSize(), 16);
+ QCOMPARE(reverseCipher.keyLength().minimum(), 32);
+ QCOMPARE(reverseCipher.keyLength().maximum(), 32);
- QString afterDecodeText = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ QString afterDecodeText = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
- afterDecodeText += QCA::arrayToHex( reverseCipher.final().toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ afterDecodeText += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QVERIFY(reverseCipher.ok());
- QCOMPARE( afterDecodeText, plainText );
- }
- }
+ QCOMPARE(afterDecodeText, plainText);
+ }
+ }
}
-
// These are from the Botan test suite
void CipherUnitTest::aes256_cbc_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("f58c4c04d6e5f1ba779eabfb5f7bfbd69cfc4e967edb808d679f777bc6702c7d39f23369a9d9bacfa530e26304231461b2eb05e2c39be9fcda6c19078c6a9d1b")
- << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("f58c4c04d6e5f1ba779eabfb5f7bfbd69cfc4e967edb808d679f777bc6702c7d39f23369a9d9bacfa530e26304231461b2eb05e2c39be9fcda6c19078c6a9d1b")
+ << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes256_cbc()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes256-cbc", provider ) )
- QWARN( QString( "AES256 CBC not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes256" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes256" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
-
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes256-cbc", provider)) {
+ QWARN(QString("AES256 CBC not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes256"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes256"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// These were generated using OpenSSL's enc command
void CipherUnitTest::aes256_cbc_pkcs7_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("")
- << QString("99fac653629ddb546d65ac699d7323ba")
- << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("1") << QString("")
+ << QString("99fac653629ddb546d65ac699d7323ba")
+ << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("2") << QString("610a")
- << QString("1dd0366efe719f6bf0e2c30e8cc168fd")
- << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("2") << QString("610a")
+ << QString("1dd0366efe719f6bf0e2c30e8cc168fd")
+ << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("3") << QString("6162636465666768696a0a")
- << QString("a433fb0dc673093f726d748c8f76cf0d")
- << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("3") << QString("6162636465666768696a0a")
+ << QString("a433fb0dc673093f726d748c8f76cf0d")
+ << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size - 1") << QString("6162636465666768696a6b6c6d6e0a")
- << QString("b5cfa68d21ad91649eafc35dee06f007")
- << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size - 1") << QString("6162636465666768696a6b6c6d6e0a")
+ << QString("b5cfa68d21ad91649eafc35dee06f007")
+ << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size") << QString("6162636465666768696a6b6c6d6e310a")
- << QString("45c4b50e4d4433b011187983da5034fe14cf12c04cfc3bceb57a88c455491f46")
- << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size") << QString("6162636465666768696a6b6c6d6e310a")
+ << QString("45c4b50e4d4433b011187983da5034fe14cf12c04cfc3bceb57a88c455491f46")
+ << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
+ << QString("00001111222233334444555566667777");
- QTest::newRow("block size+1") << QString("6162636465666768696a6b6c6d6e6f310a")
- << QString("4ef5702f0c16bbfda9b57e6e98186763325c81c99b6cdd8e4bc34dcaa82d00e9")
- << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
- << QString("00001111222233334444555566667777");
+ QTest::newRow("block size+1") << QString("6162636465666768696a6b6c6d6e6f310a")
+ << QString("4ef5702f0c16bbfda9b57e6e98186763325c81c99b6cdd8e4bc34dcaa82d00e9")
+ << QString("0123456789ABCDEF0123456789ABCDEF00112233445566778899AABBCCDDEEFF")
+ << QString("00001111222233334444555566667777");
}
void CipherUnitTest::aes256_cbc_pkcs7()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes256-cbc-pkcs7", provider ) )
- QWARN( QString( "AES256 CBC with PKCS7 padding not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes256" ),
- QCA::Cipher::CBC,
- QCA::Cipher::DefaultPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes256" ),
- QCA::Cipher::CBC,
- QCA::Cipher::DefaultPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes256-cbc-pkcs7", provider)) {
+ QWARN(QString("AES256 CBC with PKCS7 padding not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes256"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::DefaultPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes256"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::DefaultPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
-
// These are from the Botan test suite
void CipherUnitTest::aes256_cfb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("dc7e84bfda79164b7ecd8486985d386039ffed143b28b1c832113c6331e5407bdf10132415e54b92a13ed0a8267ae2f975a385741ab9cef82031623d55b1e471")
- << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("dc7e84bfda79164b7ecd8486985d386039ffed143b28b1c832113c6331e5407bdf10132415e54b92a13ed0a8267ae2f975a385741ab9cef82031623d55b1e471")
+ << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes256_cfb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes256-cfb", provider ) )
- QWARN( QString( "AES256 CFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes256" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes256" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
-
- QCOMPARE( QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( QCA::arrayToHex( reverseCipher.final().toByteArray() ), QString( "" ) );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes256-cfb", provider)) {
+ QWARN(QString("AES256 CFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes256"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes256"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(QCA::arrayToHex(reverseCipher.final().toByteArray()), QString(""));
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes256_ofb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("dc7e84bfda79164b7ecd8486985d38604febdc6740d20b3ac88f6ad82a4fb08d71ab47a086e86eedf39d1c5bba97c4080126141d67f37be8538f5a8be740e484")
- << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("dc7e84bfda79164b7ecd8486985d38604febdc6740d20b3ac88f6ad82a4fb08d71ab47a086e86eedf39d1c5bba97c4080126141d67f37be8538f5a8be740e484")
+ << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes256_ofb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes256-ofb", provider ) )
- QWARN( QString( "AES256 OFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes256" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes256" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
-
- QCOMPARE( QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( QCA::arrayToHex( reverseCipher.final().toByteArray() ), QString( "" ) );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes256-ofb", provider)) {
+ QWARN(QString("AES256 OFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes256"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes256"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(QCA::arrayToHex(reverseCipher.final().toByteArray()), QString(""));
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes256_ctr_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
- << QString("dc7e84bfda79164b7ecd8486985d3860d577788b8d8a85745513a5d50f821f30ffe96d5cf54b238dcc8d6783a87f3beae9af546344cb9ca4d1e553ffc06bc73e")
- << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
- << QString("000102030405060708090a0b0c0d0e0f");
+ QTest::newRow("1") << QString("6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710")
+ << QString("dc7e84bfda79164b7ecd8486985d3860d577788b8d8a85745513a5d50f821f30ffe96d5cf54b238dcc8d6783a87f3beae9af546344cb9ca4d1e553ffc06bc73e")
+ << QString("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4")
+ << QString("000102030405060708090a0b0c0d0e0f");
}
void CipherUnitTest::aes256_ctr()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "aes256-ctr", provider ) )
- QWARN( QString( "AES256 CTR not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "aes256" ),
- QCA::Cipher::CTR,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "aes256" ),
- QCA::Cipher::CTR,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
-
- QCOMPARE( QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( QCA::arrayToHex( reverseCipher.final().toByteArray() ), QString( "" ) );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("aes256-ctr", provider)) {
+ QWARN(QString("AES256 CTR not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("aes256"),
+ QCA::Cipher::CTR,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes256"),
+ QCA::Cipher::CTR,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(QCA::arrayToHex(reverseCipher.final().toByteArray()), QString(""));
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes256_gcm_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("payload");
- QTest::addColumn<QString>("tag");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
-
- QTest::newRow("short") << QString("6f6820526f6d656d6f21")
- << QString("4ce2f4df041252820847")
- << QString("1c570805832dfe7babc1b386c26bcd04")
- << QString("3fa609690bf07a81a75839b0a4c0add774f54eb804d4f02df488691910298b04")
- << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("payload");
+ QTest::addColumn<QString>("tag");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("long") << QString("54484520515549434b2042524f574e20464f58204a554d504544204f56455220544845204c415a5920444f472753204241434b2031323334353637383930")
- << QString("e516c267146d6cfd3af3300e24aba7ac23ab3c5cb4765937a6c0156e454cae357e14f4c0dfb0def9624f4f70de90ad2bc9cd555171c4551c26b6346922ed")
- << QString("f59aac31ab9dace3fcc693e114dd6610")
- << QString("3fa609690bf07a81a75839b0a4c0add774f54eb804d4f02df488691910298b04")
- << QString("bfcd3a7252f7f199bf788df8cf61032a");
+ QTest::newRow("short") << QString("6f6820526f6d656d6f21")
+ << QString("4ce2f4df041252820847")
+ << QString("1c570805832dfe7babc1b386c26bcd04")
+ << QString("3fa609690bf07a81a75839b0a4c0add774f54eb804d4f02df488691910298b04")
+ << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
+ QTest::newRow("long") << QString("54484520515549434b2042524f574e20464f58204a554d504544204f56455220544845204c415a5920444f472753204241434b2031323334353637383930")
+ << QString("e516c267146d6cfd3af3300e24aba7ac23ab3c5cb4765937a6c0156e454cae357e14f4c0dfb0def9624f4f70de90ad2bc9cd555171c4551c26b6346922ed")
+ << QString("f59aac31ab9dace3fcc693e114dd6610")
+ << QString("3fa609690bf07a81a75839b0a4c0add774f54eb804d4f02df488691910298b04")
+ << QString("bfcd3a7252f7f199bf788df8cf61032a");
- QTest::newRow("wrongtag") << QString("6f6820526f6d656d6f21")
- << QString("4ce2f4df041252820847")
- << QString("1c570805833dfe7babc1b386c26bcd04")
- << QString("3fa609690bf07a81a75839b0a4c0add774f54eb804d4f02df488691910298b04")
- << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
+ QTest::newRow("wrongtag") << QString("6f6820526f6d656d6f21")
+ << QString("4ce2f4df041252820847")
+ << QString("1c570805833dfe7babc1b386c26bcd04")
+ << QString("3fa609690bf07a81a75839b0a4c0add774f54eb804d4f02df488691910298b04")
+ << QString("f85f8aad39164daf64a12ad9b3fc8a3a");
}
void CipherUnitTest::aes256_gcm()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach (const QString &provider, providersToTest) {
- if (!QCA::isSupported( "aes256-gcm", provider))
- QWARN(QString("AES256 GCM not supported for " + provider).toLocal8Bit());
- else {
- QFETCH(QString, plainText);
- QFETCH(QString, payload);
- QFETCH(QString, tag);
- QFETCH(QString, keyText);
- QFETCH(QString, ivText);
-
- QCA::SymmetricKey key(QCA::hexToArray(keyText));
- QCA::InitializationVector iv(QCA::hexToArray(ivText));
- QCA::AuthTag authTag(16);
- QCA::Cipher forwardCipher(QString("aes256"),
- QCA::Cipher::GCM,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- authTag,
- provider);
- QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
- QVERIFY(forwardCipher.ok());
- update += QCA::arrayToHex(forwardCipher.final().toByteArray());
- authTag = forwardCipher.tag();
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QCOMPARE(QCA::arrayToHex(authTag.toByteArray()), tag);
- QCOMPARE(update, payload);
- QVERIFY(forwardCipher.ok());
-
- QCA::Cipher reverseCipher(QString( "aes256"),
- QCA::Cipher::GCM,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- QCA::AuthTag(QCA::hexToArray(tag)),
- provider);
-
- update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(payload)).toByteArray());
- QVERIFY(reverseCipher.ok());
- QCOMPARE(update, plainText.left(update.size()));
- update += QCA::arrayToHex(reverseCipher.final().toByteArray());
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QCOMPARE(update, plainText);
- QEXPECT_FAIL("wrongtag", "It's OK", Continue);
- QVERIFY(reverseCipher.ok());
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString &provider, providersToTest) {
+ if (!QCA::isSupported("aes256-gcm", provider)) {
+ QWARN(QString("AES256 GCM not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, payload);
+ QFETCH(QString, tag);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::AuthTag authTag(16);
+ QCA::Cipher forwardCipher(QString("aes256"),
+ QCA::Cipher::GCM,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ authTag,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ update += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ authTag = forwardCipher.tag();
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QCOMPARE(QCA::arrayToHex(authTag.toByteArray()), tag);
+ QCOMPARE(update, payload);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("aes256"),
+ QCA::Cipher::GCM,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ QCA::AuthTag(QCA::hexToArray(tag)),
+ provider);
+
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(payload)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ update += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QCOMPARE(update, plainText);
+ QEXPECT_FAIL("wrongtag", "It's OK", Continue);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
void CipherUnitTest::aes256_ccm_data()
{
}
void CipherUnitTest::aes256_ccm()
{
- // For future implementation
+ // For future implementation
}
void CipherUnitTest::tripleDES_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
-
- QTest::newRow("1") << QString("42fd443059577fa2")
- << QString("af37fb421f8c4095")
- << QString("04b915ba43feb5b604b915ba43feb5b604b915ba43feb5b6");
-
- QTest::newRow("2") << QString("736f6d6564617461")
- << QString("18d748e563620572")
- << QString("0123456789abcdef5555555555555555fedcba9876543210");
- QTest::newRow("3") << QString("7371756967676c65")
- << QString("c07d2a0fa566fa30")
- << QString("0352020767208217860287665908219864056abdfea93457");
- QTest::newRow("4") << QString("0123456789abcde7")
- << QString("de0b7c06ae5e0ed5")
- << QString("0123456789abcdeffedcba987654321089abcdef01234567");
- QTest::newRow("5") << QString("0123456789abcde7")
- << QString("7f1d0a77826b8aff")
- << QString("0123456789abcdeffedcba98765432100123456789abcdef");
- QTest::newRow("6") << QString("4115e551299a5c4b")
- << QString("f7a0822fc310686c")
- << QString("1ef743a68d629f68a5e3136c36ad7953a835cf849bb4ec3c");
- QTest::newRow("7") << QString("d5ab44e0fe46e1b5")
- << QString("02aed9bf72eca222")
- << QString("b7d560be49c3936728ef0bf57b602d2eb7e5c631dd7f753e");
- QTest::newRow("8") << QString("b4077dfdb721d88c")
- << QString("f76aba838b1c4372")
- << QString("d2d98706e9ab867647d244bdcdbcd5ef8b4dbc9cf4f35493");
- QTest::newRow("9") << QString("890e98ab385fa1a1")
- << QString("187087c77790c3b2")
- << QString("153b963004101d12683e8f87116001b8c5526475510b5036");
- QTest::newRow("10") << QString("02d5da6d5f247cd2")
- << QString("89fc7df1e7913163")
- << QString("45e4275dccc5d8b5a27993c16d9960ca939c023e2763216a");
- QTest::newRow("11") << QString("5af9e5a3525e3f7d")
- << QString("8fcc7a8bc337e484")
- << QString("f6c2474b33934ea76e6c841d9b1e86e37189095a895a3e5a");
- QTest::newRow("12") << QString("12864dde8e694bd1")
- << QString("5b4dde8f000a5a9b")
- << QString("5b4f6d3185efbae97d58ed9cc75e2bae655d2cefb2dd09cd");
- QTest::newRow("13") << QString("0123456789abcde7")
- << QString("c95744256a5ed31d")
- << QString("0123456789abcdef0123456789abcdef0123456789abcdef");
- QTest::newRow("14") << QString("68652074696d6520")
- << QString("6a271787ab8883f9")
- << QString("0123456789abcdef0123456789abcdef0123456789abcdef");
-
- QTest::newRow("15") << QString("4e6f772069732074")
- << QString("3fa40e8a984d4815")
- << QString("0123456789abcdef0123456789abcdef0123456789abcdef");
-
- // These are from the Botan test suite
- QTest::newRow("16") << QString("0123456789abcde7")
- << QString("7f1d0a77826b8aff")
- << QString("0123456789abcdeffedcba9876543210");
- QTest::newRow("17") << QString("4e6f772069732074")
- << QString("3fa40e8a984d4815")
- << QString("0123456789abcdef0123456789abcdef");
- QTest::newRow("18") << QString("42fd443059577fa2")
- << QString("af37fb421f8c4095")
- << QString("04b915ba43feb5b604b915ba43feb5b6");
- QTest::newRow("19") << QString("afa4284fcceaa61a")
- << QString("32527d5701d92b90")
- << QString("4bc59e2c68aca60767a9a4b623bbbccc");
- QTest::newRow("20") << QString("50b503a331d5b5cc")
- << QString("e46a59e18b0c41e3")
- << QString("b955bb7861fde77e7dc6418475457fe1");
- QTest::newRow("21") << QString("3404435d5df2cb47")
- << QString("644dd68ea73053ae")
- << QString("c0557629eaa72abd4c102c5dc9ce8b47");
- QTest::newRow("22") << QString("c7d80e955d1b6627")
- << QString("9fe1c5a12cce6dd9")
- << QString("9eaa94da916f30092e79dacdcdcc45c0");
- QTest::newRow("23") << QString("bdcbe8929cd0e12f")
- << QString("f2b6430450ab348b")
- << QString("a55279671807d9b71fe62a77341249f8");
- QTest::newRow("24") << QString("4b7a96b7051c64fc")
- << QString("1555f08b2de690a0")
- << QString("672e20826ad49c3df7579fab3752479e");
- QTest::newRow("25") << QString("902f4edd44eaf3c1")
- << QString("3ce357eba0fb3e26")
- << QString("0ce61ede2659b413ab9f717ae4afad3e");
- QTest::newRow("26") << QString("39c0f8e4c85cd70d")
- << QString("882de9b6d0209a58")
- << QString("e878020815ae517cd2808b6571eac2b4");
- QTest::newRow("27") << QString("f77a1947a921b209")
- << QString("e10dbee5615f312e")
- << QString("d891ca20919f06a054ba3943c7daba16");
- QTest::newRow("28") << QString("06d0416e0f0db7ce")
- << QString("0cec5d1e59d7e347")
- << QString("4909aed1f94eb77b6cacbcae2b25689a");
- QTest::newRow("29") << QString("f7bb3a396d73d8a8")
- << QString("f893b6b2a15d3fce")
- << QString("8b9a5c13b0b118a1ee35eb912866ffa6");
- QTest::newRow("30") << QString("bd35e3134b90ccbc")
- << QString("12a7af172fd0ca7f")
- << QString("fa7911d664326074b42e2f38e599b288");
- QTest::newRow("31") << QString("e046b7f5707da4fc")
- << QString("32b6a3fc72c7c480")
- << QString("406903b340b8637928fde8058bdd6710");
- QTest::newRow("32") << QString("58eb1dc16c482213")
- << QString("a6c6234a8bbaa116")
- << QString("37a2b53e2af8f6c9a73b39f919d969de");
- QTest::newRow("33") << QString("4bd0f4854297fbde")
- << QString("f4ab771861457dc6")
- << QString("711f2cecdb92b2e201dfefa79fa7ba2f");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+
+ QTest::newRow("1") << QString("42fd443059577fa2")
+ << QString("af37fb421f8c4095")
+ << QString("04b915ba43feb5b604b915ba43feb5b604b915ba43feb5b6");
+
+ QTest::newRow("2") << QString("736f6d6564617461")
+ << QString("18d748e563620572")
+ << QString("0123456789abcdef5555555555555555fedcba9876543210");
+ QTest::newRow("3") << QString("7371756967676c65")
+ << QString("c07d2a0fa566fa30")
+ << QString("0352020767208217860287665908219864056abdfea93457");
+ QTest::newRow("4") << QString("0123456789abcde7")
+ << QString("de0b7c06ae5e0ed5")
+ << QString("0123456789abcdeffedcba987654321089abcdef01234567");
+ QTest::newRow("5") << QString("0123456789abcde7")
+ << QString("7f1d0a77826b8aff")
+ << QString("0123456789abcdeffedcba98765432100123456789abcdef");
+ QTest::newRow("6") << QString("4115e551299a5c4b")
+ << QString("f7a0822fc310686c")
+ << QString("1ef743a68d629f68a5e3136c36ad7953a835cf849bb4ec3c");
+ QTest::newRow("7") << QString("d5ab44e0fe46e1b5")
+ << QString("02aed9bf72eca222")
+ << QString("b7d560be49c3936728ef0bf57b602d2eb7e5c631dd7f753e");
+ QTest::newRow("8") << QString("b4077dfdb721d88c")
+ << QString("f76aba838b1c4372")
+ << QString("d2d98706e9ab867647d244bdcdbcd5ef8b4dbc9cf4f35493");
+ QTest::newRow("9") << QString("890e98ab385fa1a1")
+ << QString("187087c77790c3b2")
+ << QString("153b963004101d12683e8f87116001b8c5526475510b5036");
+ QTest::newRow("10") << QString("02d5da6d5f247cd2")
+ << QString("89fc7df1e7913163")
+ << QString("45e4275dccc5d8b5a27993c16d9960ca939c023e2763216a");
+ QTest::newRow("11") << QString("5af9e5a3525e3f7d")
+ << QString("8fcc7a8bc337e484")
+ << QString("f6c2474b33934ea76e6c841d9b1e86e37189095a895a3e5a");
+ QTest::newRow("12") << QString("12864dde8e694bd1")
+ << QString("5b4dde8f000a5a9b")
+ << QString("5b4f6d3185efbae97d58ed9cc75e2bae655d2cefb2dd09cd");
+ QTest::newRow("13") << QString("0123456789abcde7")
+ << QString("c95744256a5ed31d")
+ << QString("0123456789abcdef0123456789abcdef0123456789abcdef");
+ QTest::newRow("14") << QString("68652074696d6520")
+ << QString("6a271787ab8883f9")
+ << QString("0123456789abcdef0123456789abcdef0123456789abcdef");
+
+ QTest::newRow("15") << QString("4e6f772069732074")
+ << QString("3fa40e8a984d4815")
+ << QString("0123456789abcdef0123456789abcdef0123456789abcdef");
+
+ // These are from the Botan test suite
+ QTest::newRow("16") << QString("0123456789abcde7")
+ << QString("7f1d0a77826b8aff")
+ << QString("0123456789abcdeffedcba9876543210");
+ QTest::newRow("17") << QString("4e6f772069732074")
+ << QString("3fa40e8a984d4815")
+ << QString("0123456789abcdef0123456789abcdef");
+ QTest::newRow("18") << QString("42fd443059577fa2")
+ << QString("af37fb421f8c4095")
+ << QString("04b915ba43feb5b604b915ba43feb5b6");
+ QTest::newRow("19") << QString("afa4284fcceaa61a")
+ << QString("32527d5701d92b90")
+ << QString("4bc59e2c68aca60767a9a4b623bbbccc");
+ QTest::newRow("20") << QString("50b503a331d5b5cc")
+ << QString("e46a59e18b0c41e3")
+ << QString("b955bb7861fde77e7dc6418475457fe1");
+ QTest::newRow("21") << QString("3404435d5df2cb47")
+ << QString("644dd68ea73053ae")
+ << QString("c0557629eaa72abd4c102c5dc9ce8b47");
+ QTest::newRow("22") << QString("c7d80e955d1b6627")
+ << QString("9fe1c5a12cce6dd9")
+ << QString("9eaa94da916f30092e79dacdcdcc45c0");
+ QTest::newRow("23") << QString("bdcbe8929cd0e12f")
+ << QString("f2b6430450ab348b")
+ << QString("a55279671807d9b71fe62a77341249f8");
+ QTest::newRow("24") << QString("4b7a96b7051c64fc")
+ << QString("1555f08b2de690a0")
+ << QString("672e20826ad49c3df7579fab3752479e");
+ QTest::newRow("25") << QString("902f4edd44eaf3c1")
+ << QString("3ce357eba0fb3e26")
+ << QString("0ce61ede2659b413ab9f717ae4afad3e");
+ QTest::newRow("26") << QString("39c0f8e4c85cd70d")
+ << QString("882de9b6d0209a58")
+ << QString("e878020815ae517cd2808b6571eac2b4");
+ QTest::newRow("27") << QString("f77a1947a921b209")
+ << QString("e10dbee5615f312e")
+ << QString("d891ca20919f06a054ba3943c7daba16");
+ QTest::newRow("28") << QString("06d0416e0f0db7ce")
+ << QString("0cec5d1e59d7e347")
+ << QString("4909aed1f94eb77b6cacbcae2b25689a");
+ QTest::newRow("29") << QString("f7bb3a396d73d8a8")
+ << QString("f893b6b2a15d3fce")
+ << QString("8b9a5c13b0b118a1ee35eb912866ffa6");
+ QTest::newRow("30") << QString("bd35e3134b90ccbc")
+ << QString("12a7af172fd0ca7f")
+ << QString("fa7911d664326074b42e2f38e599b288");
+ QTest::newRow("31") << QString("e046b7f5707da4fc")
+ << QString("32b6a3fc72c7c480")
+ << QString("406903b340b8637928fde8058bdd6710");
+ QTest::newRow("32") << QString("58eb1dc16c482213")
+ << QString("a6c6234a8bbaa116")
+ << QString("37a2b53e2af8f6c9a73b39f919d969de");
+ QTest::newRow("33") << QString("4bd0f4854297fbde")
+ << QString("f4ab771861457dc6")
+ << QString("711f2cecdb92b2e201dfefa79fa7ba2f");
}
// TODO: ECB-PKCS7
void CipherUnitTest::tripleDES()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- // providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "tripledes-ecb", provider ) )
- QWARN( QString( "Triple DES, ECB not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Cipher cipherObj1( QString( "tripledes" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- QCA::SymmetricKey( 24 ),
- QCA::InitializationVector(),
- provider );
- // checking minimum is a bit hairy, because it depends on whether you are
- // doing 2 key or 3 key triple DES.
- QCOMPARE( cipherObj1.keyLength().minimum(), 16 );
- QCOMPARE( cipherObj1.keyLength().maximum(), 24 );
- QCOMPARE( cipherObj1.blockSize(), 8 );
-
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::Cipher forwardCipher( QString( "tripledes" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- QCA::InitializationVector(),
- provider );
-
- QString afterEncodeText = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
-
- afterEncodeText += QCA::arrayToHex( forwardCipher.final().toByteArray() );
- QVERIFY( forwardCipher.ok() );
-
- QCOMPARE( afterEncodeText, cipherText );
-
- QCA::Cipher reverseCipher( QString( "tripledes" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- QCA::InitializationVector(),
- provider );
-
- QString afterDecodeText = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
-
- afterDecodeText += QCA::arrayToHex( reverseCipher.final().toByteArray() );
- QVERIFY( reverseCipher.ok() );
-
- QCOMPARE( afterDecodeText, plainText );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ // providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("tripledes-ecb", provider)) {
+ QWARN(QString("Triple DES, ECB not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Cipher cipherObj1(QString("tripledes"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ QCA::SymmetricKey(24),
+ QCA::InitializationVector(),
+ provider);
+ // checking minimum is a bit hairy, because it depends on whether you are
+ // doing 2 key or 3 key triple DES.
+ QCOMPARE(cipherObj1.keyLength().minimum(), 16);
+ QCOMPARE(cipherObj1.keyLength().maximum(), 24);
+ QCOMPARE(cipherObj1.blockSize(), 8);
+
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::Cipher forwardCipher(QString("tripledes"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ QCA::InitializationVector(),
+ provider);
+
+ QString afterEncodeText = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+
+ afterEncodeText += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ QVERIFY(forwardCipher.ok());
+
+ QCOMPARE(afterEncodeText, cipherText);
+
+ QCA::Cipher reverseCipher(QString("tripledes"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ QCA::InitializationVector(),
+ provider);
+
+ QString afterDecodeText = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+
+ afterDecodeText += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QVERIFY(reverseCipher.ok());
+
+ QCOMPARE(afterDecodeText, plainText);
+ }
+ }
}
// These are from the Botan test suite - its ECB mode, no padding
void CipherUnitTest::des_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
-
- QTest::newRow("") << QString("059b5e0851cf143a") << QString("86a560f10ec6d85b") << QString("0113b970fd34f2ce");
- QTest::newRow("") << QString("4e6f772069732074") << QString("3fa40e8a984d4815") << QString("0123456789abcdef");
- QTest::newRow("") << QString("666f7220616c6c20") << QString("893d51ec4b563b53") << QString("0123456789abcdef");
- QTest::newRow("") << QString("68652074696d6520") << QString("6a271787ab8883f9") << QString("0123456789abcdef");
- QTest::newRow("") << QString("5cd54ca83def57da") << QString("7a389d10354bd271") << QString("0131d9619dc1376e");
- QTest::newRow("") << QString("0756d8e0774761d2") << QString("0cd3da020021dc09") << QString("0170f175468fb5e6");
- QTest::newRow("") << QString("1d9d5c5018f728c2") << QString("5f4c038ed12b2e41") << QString("018310dc409b26d6");
- QTest::newRow("") << QString("480d39006ee762f2") << QString("a1f9915541020b56") << QString("025816164629b007");
- QTest::newRow("") << QString("26955f6835af609a") << QString("5c513c9c4886c088") << QString("04689104c2fd3b2f");
- QTest::newRow("") << QString("42fd443059577fa2") << QString("af37fb421f8c4095") << QString("04b915ba43feb5b6");
- QTest::newRow("") << QString("0248d43806f67172") << QString("868ebb51cab4599a") << QString("07a1133e4a0b2686");
- QTest::newRow("") << QString("3bdd119049372802") << QString("dfd64a815caf1a0f") << QString("07a7137045da2a16");
- QTest::newRow("") << QString("16393bcdd6560506") << QString("9966adcfc53bf968") << QString("0a3fddc8350aff39");
- QTest::newRow("") << QString("dc7fc6cf0358ecc0") << QString("a47a7485661f7085") << QString("10dd6dcd5c89e151");
- QTest::newRow("") << QString("305532286d6f295a") << QString("63fac0d034d9f793") << QString("1c587f1c13924fef");
- QTest::newRow("") << QString("f786d02413c574fc") << QString("54c160d369f62ae3") << QString("1eb00767bdee584e");
- QTest::newRow("") << QString("6b056e18759f5cca") << QString("ef1bf03e5dfa575a") << QString("1f08260d1ac2465e");
- QTest::newRow("") << QString("905ea29aeea26e07") << QString("2292e9aebee6a4b6") << QString("28ee445d8a21c534");
- QTest::newRow("") << QString("164d5e404f275232") << QString("0a2aeeae3ff4ab77") << QString("37d06bb516cb7546");
- QTest::newRow("") << QString("51454b582ddf440a") << QString("7178876e01f19b2a") << QString("3849674c2602319e");
- QTest::newRow("") << QString("68ff9d6068c71513") << QString("84595f5b9d046132") << QString("3cde816ef9ef8edb");
- QTest::newRow("") << QString("762514b829bf486a") << QString("ea676b2cb7db2b7a") << QString("43297fad38e373fe");
- QTest::newRow("") << QString("437540c8698f3cfa") << QString("6fbf1cafcffd0556") << QString("49793ebc79b3258f");
- QTest::newRow("") << QString("02fe55778117f12a") << QString("5a6b612cc26cce4a") << QString("49e95d6d4ca229bf");
- QTest::newRow("") << QString("1f508a50adb3d6e2") << QString("470204969876604a") << QString("4bb53ecfefb38dde");
- QTest::newRow("") << QString("072d43a077075292") << QString("2f22e49bab7ca1ac") << QString("4fb05e1515ab73a7");
- QTest::newRow("") << QString("004bd6ef09176062") << QString("88bf0db6d70dee56") << QString("584023641aba6176");
- QTest::newRow("") << QString("5aa1d62806ae0ead") << QString("6db0f280fef2b564") << QString("5f2b51f59e781d9c");
- QTest::newRow("") << QString("7e1b1c6776833772") << QString("eb11cd3c72f7e90e") << QString("699c920d7ce1e0b1");
- QTest::newRow("") << QString("5dbfb47c5f471136") << QString("9c8b904d4d772be7") << QString("7ac2fdeee4c79746");
- QTest::newRow("") << QString("01a1d6d039776742") << QString("690f5b0d9a26939b") << QString("7ca110454a1a6e57");
- QTest::newRow("") << QString("4de2f0926cf598d7") << QString("ba107655991df529") << QString("7fc92c3098ecf14a");
- QTest::newRow("") << QString("f45e6819e3108559") << QString("f0c76ba556283b2f") << QString("9ab645e268430854");
- QTest::newRow("") << QString("51d4eaaac6d76553") << QString("bf3c6e8fd15ba861") << QString("a6b0ae88f980011a");
- QTest::newRow("") << QString("6a89626ea8038511") << QString("1067b36913cbcc47") << QString("bafebafafeaeeaff");
- QTest::newRow("") << QString("7b0313c0d3a866f9") << QString("e49e15e4f46f10e9") << QString("bb2420b5fee5a6a1");
- QTest::newRow("") << QString("9d4a44aefce79965") << QString("77b2ecc9278e9714") << QString("bebafbeabaffeaaf");
- QTest::newRow("") << QString("59bcdfc253424cb5") << QString("0a50abbbcd07061a") << QString("c38c6f20230d9ed5");
- QTest::newRow("") << QString("d6c059a85ee2b13e") << QString("25977533635beb5b") << QString("c6f974504d954c7e");
- QTest::newRow("") << QString("f9e4821dfcaa5466") << QString("48ec3a79399e9a00") << QString("cb959b7ffd94f734");
- QTest::newRow("") << QString("35e8554bad60fb29") << QString("993a3af0bc0d77a4") << QString("cfb23034323cd19a");
- QTest::newRow("") << QString("9f97210d75b7e6df") << QString("4729e3396e57ae4e") << QString("d4d861035745f2c8");
- QTest::newRow("") << QString("ffffffffffffffff") << QString("b5ce4f28fdeb21e8") << QString("e36972fc4bec7587");
- QTest::newRow("") << QString("323837024123c918") << QString("7f28bf28adfa1cf0") << QString("e91a71a7ed5eb0ef");
- QTest::newRow("") << QString("37dfe527086af0a0") << QString("5f53c6c87760256e") << QString("ebbbbaebfbbefaba");
- QTest::newRow("") << QString("20678f45b5b8ac00") << QString("7cc8ecf2638cc808") << QString("ebbeeeaebbbbffff");
- QTest::newRow("") << QString("78481ed0c5a7c93e") << QString("4ca3a08300ea6afc") << QString("fbeaffeeffeeabab");
- QTest::newRow("") << QString("e2ccd415ac25412a") << QString("bd85b3b659ab7276") << QString("fd8a675c0ed08301");
- // weak key
- QTest::newRow("") << QString("cccc5bdfd9029507") << QString("da57553d7d55775f") << QString("ffffffffffffffff");
- QTest::newRow("") << QString("0000000000000000") << QString("23083a3ca70dd027") << QString("d5d44ff720683d0d");
- QTest::newRow("") << QString("0100000000000000") << QString("6f353e3388abe2ef") << QString("d5d44ff720683d0d");
- //weak keys till next comment.
- QTest::newRow("") << QString("95f8a5e5dd31d900") << QString("8000000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("95f8a5e5dd31d900") << QString("8000000000000000") << QString("0000000000000000");
- QTest::newRow("") << QString("dd7f121ca5015619") << QString("4000000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("2e8653104f3834ea") << QString("2000000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("4bd388ff6cd81d4f") << QString("1000000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("20b9e767b2fb1456") << QString("0800000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("20b9e767b2fb1456") << QString("0800000000000000") << QString("0001010101010100");
- QTest::newRow("") << QString("55579380d77138ef") << QString("0400000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("6cc5defaaf04512f") << QString("0200000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("0d9f279ba5d87260") << QString("0100000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("d9031b0271bd5a0a") << QString("0080000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("424250b37c3dd951") << QString("0040000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("b8061b7ecd9a21e5") << QString("0020000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("f15d0f286b65bd28") << QString("0010000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("add0cc8d6e5deba1") << QString("0008000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("e6d5f82752ad63d1") << QString("0004000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("ecbfe3bd3f591a5e") << QString("0002000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("f356834379d165cd") << QString("0001000000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("2b9f982f20037fa9") << QString("0000800000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("889de068a16f0be6") << QString("0000400000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("e19e275d846a1298") << QString("0000200000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("329a8ed523d71aec") << QString("0000100000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("e7fce22557d23c97") << QString("0000080000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("12a9f5817ff2d65d") << QString("0000040000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("a484c3ad38dc9c19") << QString("0000020000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("fbe00a8a1ef8ad72") << QString("0000010000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("750d079407521363") << QString("0000008000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("64feed9c724c2faf") << QString("0000004000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("f02b263b328e2b60") << QString("0000002000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("9d64555a9a10b852") << QString("0000001000000000") << QString("0101010101010101");
- QTest::newRow("") << QString("d106ff0bed5255d7") << QString("0000000800000000") << QString("0101010101010101");
- QTest::newRow("") << QString("e1652c6b138c64a5") << QString("0000000400000000") << QString("0101010101010101");
- QTest::newRow("") << QString("e428581186ec8f46") << QString("0000000200000000") << QString("0101010101010101");
- QTest::newRow("") << QString("aeb5f5ede22d1a36") << QString("0000000100000000") << QString("0101010101010101");
- QTest::newRow("") << QString("e943d7568aec0c5c") << QString("0000000080000000") << QString("0101010101010101");
- QTest::newRow("") << QString("df98c8276f54b04b") << QString("0000000040000000") << QString("0101010101010101");
- QTest::newRow("") << QString("b160e4680f6c696f") << QString("0000000020000000") << QString("0101010101010101");
- QTest::newRow("") << QString("fa0752b07d9c4ab8") << QString("0000000010000000") << QString("0101010101010101");
- QTest::newRow("") << QString("ca3a2b036dbc8502") << QString("0000000008000000") << QString("0101010101010101");
- QTest::newRow("") << QString("5e0905517bb59bcf") << QString("0000000004000000") << QString("0101010101010101");
- QTest::newRow("") << QString("814eeb3b91d90726") << QString("0000000002000000") << QString("0101010101010101");
- QTest::newRow("") << QString("4d49db1532919c9f") << QString("0000000001000000") << QString("0101010101010101");
- QTest::newRow("") << QString("25eb5fc3f8cf0621") << QString("0000000000800000") << QString("0101010101010101");
- QTest::newRow("") << QString("ab6a20c0620d1c6f") << QString("0000000000400000") << QString("0101010101010101");
- QTest::newRow("") << QString("79e90dbc98f92cca") << QString("0000000000200000") << QString("0101010101010101");
- QTest::newRow("") << QString("866ecedd8072bb0e") << QString("0000000000100000") << QString("0101010101010101");
- QTest::newRow("") << QString("8b54536f2f3e64a8") << QString("0000000000080000") << QString("0101010101010101");
- QTest::newRow("") << QString("ea51d3975595b86b") << QString("0000000000040000") << QString("0101010101010101");
- QTest::newRow("") << QString("caffc6ac4542de31") << QString("0000000000020000") << QString("0101010101010101");
- QTest::newRow("") << QString("8dd45a2ddf90796c") << QString("0000000000010000") << QString("0101010101010101");
- QTest::newRow("") << QString("1029d55e880ec2d0") << QString("0000000000008000") << QString("0101010101010101");
- QTest::newRow("") << QString("5d86cb23639dbea9") << QString("0000000000004000") << QString("0101010101010101");
- QTest::newRow("") << QString("1d1ca853ae7c0c5f") << QString("0000000000002000") << QString("0101010101010101");
- QTest::newRow("") << QString("ce332329248f3228") << QString("0000000000001000") << QString("0101010101010101");
- QTest::newRow("") << QString("8405d1abe24fb942") << QString("0000000000000800") << QString("0101010101010101");
- QTest::newRow("") << QString("e643d78090ca4207") << QString("0000000000000400") << QString("0101010101010101");
- QTest::newRow("") << QString("48221b9937748a23") << QString("0000000000000200") << QString("0101010101010101");
- QTest::newRow("") << QString("dd7c0bbd61fafd54") << QString("0000000000000100") << QString("0101010101010101");
- QTest::newRow("") << QString("2fbc291a570db5c4") << QString("0000000000000080") << QString("0101010101010101");
- QTest::newRow("") << QString("e07c30d7e4e26e12") << QString("0000000000000040") << QString("0101010101010101");
- QTest::newRow("") << QString("0953e2258e8e90a1") << QString("0000000000000020") << QString("0101010101010101");
- QTest::newRow("") << QString("5b711bc4ceebf2ee") << QString("0000000000000010") << QString("0101010101010101");
- QTest::newRow("") << QString("cc083f1e6d9e85f6") << QString("0000000000000008") << QString("0101010101010101");
- QTest::newRow("") << QString("d2fd8867d50d2dfe") << QString("0000000000000004") << QString("0101010101010101");
- QTest::newRow("") << QString("06e7ea22ce92708f") << QString("0000000000000002") << QString("0101010101010101");
- QTest::newRow("") << QString("166b40b44aba4bd6") << QString("0000000000000001") << QString("0101010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("95a8d72813daa94d") << QString("8001010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("0eec1487dd8c26d5") << QString("4001010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("7ad16ffb79c45926") << QString("2001010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("d3746294ca6a6cf3") << QString("1001010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("809f5f873c1fd761") << QString("0801010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("c02faffec989d1fc") << QString("0401010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("4615aa1d33e72f10") << QString("0201010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("2055123350c00858") << QString("0180010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("df3b99d6577397c8") << QString("0140010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("31fe17369b5288c9") << QString("0120010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("dfdd3cc64dae1642") << QString("0110010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("178c83ce2b399d94") << QString("0108010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("50f636324a9b7f80") << QString("0104010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("a8468ee3bc18f06d") << QString("0102010101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("a2dc9e92fd3cde92") << QString("0101800101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("cac09f797d031287") << QString("0101400101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("90ba680b22aeb525") << QString("0101200101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("ce7a24f350e280b6") << QString("0101100101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("882bff0aa01a0b87") << QString("0101080101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("25610288924511c2") << QString("0101040101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("c71516c29c75d170") << QString("0101020101010101");
- QTest::newRow("") << QString("0000000000000000") << QString("5199c29a52c9f059") << QString("0101018001010101");
- QTest::newRow("") << QString("0000000000000000") << QString("c22f0a294a71f29f") << QString("0101014001010101");
- QTest::newRow("") << QString("0000000000000000") << QString("ee371483714c02ea") << QString("0101012001010101");
- QTest::newRow("") << QString("0000000000000000") << QString("a81fbd448f9e522f") << QString("0101011001010101");
- QTest::newRow("") << QString("0000000000000000") << QString("4f644c92e192dfed") << QString("0101010801010101");
- QTest::newRow("") << QString("0000000000000000") << QString("1afa9a66a6df92ae") << QString("0101010401010101");
- QTest::newRow("") << QString("0000000000000000") << QString("b3c1cc715cb879d8") << QString("0101010201010101");
- QTest::newRow("") << QString("0000000000000000") << QString("19d032e64ab0bd8b") << QString("0101010180010101");
- QTest::newRow("") << QString("0000000000000000") << QString("3cfaa7a7dc8720dc") << QString("0101010140010101");
- QTest::newRow("") << QString("0000000000000000") << QString("b7265f7f447ac6f3") << QString("0101010120010101");
- QTest::newRow("") << QString("0000000000000000") << QString("9db73b3c0d163f54") << QString("0101010110010101");
- QTest::newRow("") << QString("0000000000000000") << QString("8181b65babf4a975") << QString("0101010108010101");
- QTest::newRow("") << QString("0000000000000000") << QString("93c9b64042eaa240") << QString("0101010104010101");
- QTest::newRow("") << QString("0000000000000000") << QString("5570530829705592") << QString("0101010102010101");
- QTest::newRow("") << QString("0000000000000000") << QString("8638809e878787a0") << QString("0101010101800101");
- QTest::newRow("") << QString("0000000000000000") << QString("41b9a79af79ac208") << QString("0101010101400101");
- QTest::newRow("") << QString("0000000000000000") << QString("7a9be42f2009a892") << QString("0101010101200101");
- QTest::newRow("") << QString("0000000000000000") << QString("29038d56ba6d2745") << QString("0101010101100101");
- QTest::newRow("") << QString("0000000000000000") << QString("5495c6abf1e5df51") << QString("0101010101080101");
- QTest::newRow("") << QString("0000000000000000") << QString("ae13dbd561488933") << QString("0101010101040101");
- QTest::newRow("") << QString("0000000000000000") << QString("024d1ffa8904e389") << QString("0101010101020101");
- QTest::newRow("") << QString("0000000000000000") << QString("d1399712f99bf02e") << QString("0101010101018001");
- QTest::newRow("") << QString("0000000000000000") << QString("14c1d7c1cffec79e") << QString("0101010101014001");
- QTest::newRow("") << QString("0000000000000000") << QString("1de5279dae3bed6f") << QString("0101010101012001");
- QTest::newRow("") << QString("0000000000000000") << QString("e941a33f85501303") << QString("0101010101011001");
- QTest::newRow("") << QString("0000000000000000") << QString("da99dbbc9a03f379") << QString("0101010101010801");
- QTest::newRow("") << QString("0000000000000000") << QString("b7fc92f91d8e92e9") << QString("0101010101010401");
- QTest::newRow("") << QString("0000000000000000") << QString("ae8e5caa3ca04e85") << QString("0101010101010201");
- QTest::newRow("") << QString("0000000000000000") << QString("9cc62df43b6eed74") << QString("0101010101010180");
- QTest::newRow("") << QString("0000000000000000") << QString("d863dbb5c59a91a0") << QString("0101010101010140");
- QTest::newRow("") << QString("0000000000000000") << QString("a1ab2190545b91d7") << QString("0101010101010120");
- QTest::newRow("") << QString("0000000000000000") << QString("0875041e64c570f7") << QString("0101010101010110");
- QTest::newRow("") << QString("0000000000000000") << QString("5a594528bebef1cc") << QString("0101010101010108");
- QTest::newRow("") << QString("0000000000000000") << QString("fcdb3291de21f0c0") << QString("0101010101010104");
- QTest::newRow("") << QString("0000000000000000") << QString("869efd7f9f265a09") << QString("0101010101010102");
- //end of weak keys
- QTest::newRow("") << QString("0000000000000000") << QString("88d55e54f54c97b4") << QString("1046913489980131");
- QTest::newRow("") << QString("0000000000000000") << QString("0c0cc00c83ea48fd") << QString("1007103489988020");
- QTest::newRow("") << QString("0000000000000000") << QString("83bc8ef3a6570183") << QString("10071034c8980120");
- QTest::newRow("") << QString("0000000000000000") << QString("df725dcad94ea2e9") << QString("1046103489988020");
- QTest::newRow("") << QString("0000000000000000") << QString("e652b53b550be8b0") << QString("1086911519190101");
- QTest::newRow("") << QString("0000000000000000") << QString("af527120c485cbb0") << QString("1086911519580101");
- QTest::newRow("") << QString("0000000000000000") << QString("0f04ce393db926d5") << QString("5107b01519580101");
- QTest::newRow("") << QString("0000000000000000") << QString("c9f00ffc74079067") << QString("1007b01519190101");
- QTest::newRow("") << QString("0000000000000000") << QString("7cfd82a593252b4e") << QString("3107915498080101");
- QTest::newRow("") << QString("0000000000000000") << QString("cb49a2f9e91363e3") << QString("3107919498080101");
- QTest::newRow("") << QString("0000000000000000") << QString("00b588be70d23f56") << QString("10079115b9080140");
- QTest::newRow("") << QString("0000000000000000") << QString("406a9a6ab43399ae") << QString("3107911598090140");
- QTest::newRow("") << QString("0000000000000000") << QString("6cb773611dca9ada") << QString("1007d01589980101");
- QTest::newRow("") << QString("0000000000000000") << QString("67fd21c17dbb5d70") << QString("9107911589980101");
- QTest::newRow("") << QString("0000000000000000") << QString("9592cb4110430787") << QString("9107d01589190101");
- QTest::newRow("") << QString("0000000000000000") << QString("a6b7ff68a318ddd3") << QString("1007d01598980120");
- QTest::newRow("") << QString("0000000000000000") << QString("4d102196c914ca16") << QString("1007940498190101");
- QTest::newRow("") << QString("0000000000000000") << QString("2dfa9f4573594965") << QString("0107910491190401");
- QTest::newRow("") << QString("0000000000000000") << QString("b46604816c0e0774") << QString("0107910491190101");
- QTest::newRow("") << QString("0000000000000000") << QString("6e7e6221a4f34e87") << QString("0107940491190401");
- QTest::newRow("") << QString("0000000000000000") << QString("aa85e74643233199") << QString("19079210981a0101");
- QTest::newRow("") << QString("0000000000000000") << QString("2e5a19db4d1962d6") << QString("1007911998190801");
- QTest::newRow("") << QString("0000000000000000") << QString("23a866a809d30894") << QString("10079119981a0801");
- QTest::newRow("") << QString("0000000000000000") << QString("d812d961f017d320") << QString("1007921098190101");
- QTest::newRow("") << QString("0000000000000000") << QString("055605816e58608f") << QString("100791159819010b");
- QTest::newRow("") << QString("0000000000000000") << QString("abd88e8b1b7716f1") << QString("1004801598190101");
- QTest::newRow("") << QString("0000000000000000") << QString("537ac95be69da1e1") << QString("1004801598190102");
- QTest::newRow("") << QString("0000000000000000") << QString("aed0f6ae3c25cdd8") << QString("1004801598190108");
- QTest::newRow("") << QString("0000000000000000") << QString("b3e35a5ee53e7b8d") << QString("1002911598100104");
- QTest::newRow("") << QString("0000000000000000") << QString("61c79c71921a2ef8") << QString("1002911598190104");
- QTest::newRow("") << QString("0000000000000000") << QString("e2f5728f0995013c") << QString("1002911598100201");
- QTest::newRow("") << QString("0000000000000000") << QString("1aeac39a61f0a464") << QString("1002911698100101");
- QTest::newRow("") << QString("059b5e0851cf143a") << QString("86a560f10ec6d85b") << QString("0113b970fd34f2ce");
- QTest::newRow("") << QString("4e6f772069732074") << QString("3fa40e8a984d4815") << QString("0123456789abcdef");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+
+ QTest::newRow("") << QString("059b5e0851cf143a") << QString("86a560f10ec6d85b") << QString("0113b970fd34f2ce");
+ QTest::newRow("") << QString("4e6f772069732074") << QString("3fa40e8a984d4815") << QString("0123456789abcdef");
+ QTest::newRow("") << QString("666f7220616c6c20") << QString("893d51ec4b563b53") << QString("0123456789abcdef");
+ QTest::newRow("") << QString("68652074696d6520") << QString("6a271787ab8883f9") << QString("0123456789abcdef");
+ QTest::newRow("") << QString("5cd54ca83def57da") << QString("7a389d10354bd271") << QString("0131d9619dc1376e");
+ QTest::newRow("") << QString("0756d8e0774761d2") << QString("0cd3da020021dc09") << QString("0170f175468fb5e6");
+ QTest::newRow("") << QString("1d9d5c5018f728c2") << QString("5f4c038ed12b2e41") << QString("018310dc409b26d6");
+ QTest::newRow("") << QString("480d39006ee762f2") << QString("a1f9915541020b56") << QString("025816164629b007");
+ QTest::newRow("") << QString("26955f6835af609a") << QString("5c513c9c4886c088") << QString("04689104c2fd3b2f");
+ QTest::newRow("") << QString("42fd443059577fa2") << QString("af37fb421f8c4095") << QString("04b915ba43feb5b6");
+ QTest::newRow("") << QString("0248d43806f67172") << QString("868ebb51cab4599a") << QString("07a1133e4a0b2686");
+ QTest::newRow("") << QString("3bdd119049372802") << QString("dfd64a815caf1a0f") << QString("07a7137045da2a16");
+ QTest::newRow("") << QString("16393bcdd6560506") << QString("9966adcfc53bf968") << QString("0a3fddc8350aff39");
+ QTest::newRow("") << QString("dc7fc6cf0358ecc0") << QString("a47a7485661f7085") << QString("10dd6dcd5c89e151");
+ QTest::newRow("") << QString("305532286d6f295a") << QString("63fac0d034d9f793") << QString("1c587f1c13924fef");
+ QTest::newRow("") << QString("f786d02413c574fc") << QString("54c160d369f62ae3") << QString("1eb00767bdee584e");
+ QTest::newRow("") << QString("6b056e18759f5cca") << QString("ef1bf03e5dfa575a") << QString("1f08260d1ac2465e");
+ QTest::newRow("") << QString("905ea29aeea26e07") << QString("2292e9aebee6a4b6") << QString("28ee445d8a21c534");
+ QTest::newRow("") << QString("164d5e404f275232") << QString("0a2aeeae3ff4ab77") << QString("37d06bb516cb7546");
+ QTest::newRow("") << QString("51454b582ddf440a") << QString("7178876e01f19b2a") << QString("3849674c2602319e");
+ QTest::newRow("") << QString("68ff9d6068c71513") << QString("84595f5b9d046132") << QString("3cde816ef9ef8edb");
+ QTest::newRow("") << QString("762514b829bf486a") << QString("ea676b2cb7db2b7a") << QString("43297fad38e373fe");
+ QTest::newRow("") << QString("437540c8698f3cfa") << QString("6fbf1cafcffd0556") << QString("49793ebc79b3258f");
+ QTest::newRow("") << QString("02fe55778117f12a") << QString("5a6b612cc26cce4a") << QString("49e95d6d4ca229bf");
+ QTest::newRow("") << QString("1f508a50adb3d6e2") << QString("470204969876604a") << QString("4bb53ecfefb38dde");
+ QTest::newRow("") << QString("072d43a077075292") << QString("2f22e49bab7ca1ac") << QString("4fb05e1515ab73a7");
+ QTest::newRow("") << QString("004bd6ef09176062") << QString("88bf0db6d70dee56") << QString("584023641aba6176");
+ QTest::newRow("") << QString("5aa1d62806ae0ead") << QString("6db0f280fef2b564") << QString("5f2b51f59e781d9c");
+ QTest::newRow("") << QString("7e1b1c6776833772") << QString("eb11cd3c72f7e90e") << QString("699c920d7ce1e0b1");
+ QTest::newRow("") << QString("5dbfb47c5f471136") << QString("9c8b904d4d772be7") << QString("7ac2fdeee4c79746");
+ QTest::newRow("") << QString("01a1d6d039776742") << QString("690f5b0d9a26939b") << QString("7ca110454a1a6e57");
+ QTest::newRow("") << QString("4de2f0926cf598d7") << QString("ba107655991df529") << QString("7fc92c3098ecf14a");
+ QTest::newRow("") << QString("f45e6819e3108559") << QString("f0c76ba556283b2f") << QString("9ab645e268430854");
+ QTest::newRow("") << QString("51d4eaaac6d76553") << QString("bf3c6e8fd15ba861") << QString("a6b0ae88f980011a");
+ QTest::newRow("") << QString("6a89626ea8038511") << QString("1067b36913cbcc47") << QString("bafebafafeaeeaff");
+ QTest::newRow("") << QString("7b0313c0d3a866f9") << QString("e49e15e4f46f10e9") << QString("bb2420b5fee5a6a1");
+ QTest::newRow("") << QString("9d4a44aefce79965") << QString("77b2ecc9278e9714") << QString("bebafbeabaffeaaf");
+ QTest::newRow("") << QString("59bcdfc253424cb5") << QString("0a50abbbcd07061a") << QString("c38c6f20230d9ed5");
+ QTest::newRow("") << QString("d6c059a85ee2b13e") << QString("25977533635beb5b") << QString("c6f974504d954c7e");
+ QTest::newRow("") << QString("f9e4821dfcaa5466") << QString("48ec3a79399e9a00") << QString("cb959b7ffd94f734");
+ QTest::newRow("") << QString("35e8554bad60fb29") << QString("993a3af0bc0d77a4") << QString("cfb23034323cd19a");
+ QTest::newRow("") << QString("9f97210d75b7e6df") << QString("4729e3396e57ae4e") << QString("d4d861035745f2c8");
+ QTest::newRow("") << QString("ffffffffffffffff") << QString("b5ce4f28fdeb21e8") << QString("e36972fc4bec7587");
+ QTest::newRow("") << QString("323837024123c918") << QString("7f28bf28adfa1cf0") << QString("e91a71a7ed5eb0ef");
+ QTest::newRow("") << QString("37dfe527086af0a0") << QString("5f53c6c87760256e") << QString("ebbbbaebfbbefaba");
+ QTest::newRow("") << QString("20678f45b5b8ac00") << QString("7cc8ecf2638cc808") << QString("ebbeeeaebbbbffff");
+ QTest::newRow("") << QString("78481ed0c5a7c93e") << QString("4ca3a08300ea6afc") << QString("fbeaffeeffeeabab");
+ QTest::newRow("") << QString("e2ccd415ac25412a") << QString("bd85b3b659ab7276") << QString("fd8a675c0ed08301");
+ // weak key
+ QTest::newRow("") << QString("cccc5bdfd9029507") << QString("da57553d7d55775f") << QString("ffffffffffffffff");
+ QTest::newRow("") << QString("0000000000000000") << QString("23083a3ca70dd027") << QString("d5d44ff720683d0d");
+ QTest::newRow("") << QString("0100000000000000") << QString("6f353e3388abe2ef") << QString("d5d44ff720683d0d");
+ //weak keys till next comment.
+ QTest::newRow("") << QString("95f8a5e5dd31d900") << QString("8000000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("95f8a5e5dd31d900") << QString("8000000000000000") << QString("0000000000000000");
+ QTest::newRow("") << QString("dd7f121ca5015619") << QString("4000000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("2e8653104f3834ea") << QString("2000000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("4bd388ff6cd81d4f") << QString("1000000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("20b9e767b2fb1456") << QString("0800000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("20b9e767b2fb1456") << QString("0800000000000000") << QString("0001010101010100");
+ QTest::newRow("") << QString("55579380d77138ef") << QString("0400000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("6cc5defaaf04512f") << QString("0200000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("0d9f279ba5d87260") << QString("0100000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("d9031b0271bd5a0a") << QString("0080000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("424250b37c3dd951") << QString("0040000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("b8061b7ecd9a21e5") << QString("0020000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("f15d0f286b65bd28") << QString("0010000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("add0cc8d6e5deba1") << QString("0008000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("e6d5f82752ad63d1") << QString("0004000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("ecbfe3bd3f591a5e") << QString("0002000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("f356834379d165cd") << QString("0001000000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("2b9f982f20037fa9") << QString("0000800000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("889de068a16f0be6") << QString("0000400000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("e19e275d846a1298") << QString("0000200000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("329a8ed523d71aec") << QString("0000100000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("e7fce22557d23c97") << QString("0000080000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("12a9f5817ff2d65d") << QString("0000040000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("a484c3ad38dc9c19") << QString("0000020000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("fbe00a8a1ef8ad72") << QString("0000010000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("750d079407521363") << QString("0000008000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("64feed9c724c2faf") << QString("0000004000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("f02b263b328e2b60") << QString("0000002000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("9d64555a9a10b852") << QString("0000001000000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("d106ff0bed5255d7") << QString("0000000800000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("e1652c6b138c64a5") << QString("0000000400000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("e428581186ec8f46") << QString("0000000200000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("aeb5f5ede22d1a36") << QString("0000000100000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("e943d7568aec0c5c") << QString("0000000080000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("df98c8276f54b04b") << QString("0000000040000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("b160e4680f6c696f") << QString("0000000020000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("fa0752b07d9c4ab8") << QString("0000000010000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("ca3a2b036dbc8502") << QString("0000000008000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("5e0905517bb59bcf") << QString("0000000004000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("814eeb3b91d90726") << QString("0000000002000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("4d49db1532919c9f") << QString("0000000001000000") << QString("0101010101010101");
+ QTest::newRow("") << QString("25eb5fc3f8cf0621") << QString("0000000000800000") << QString("0101010101010101");
+ QTest::newRow("") << QString("ab6a20c0620d1c6f") << QString("0000000000400000") << QString("0101010101010101");
+ QTest::newRow("") << QString("79e90dbc98f92cca") << QString("0000000000200000") << QString("0101010101010101");
+ QTest::newRow("") << QString("866ecedd8072bb0e") << QString("0000000000100000") << QString("0101010101010101");
+ QTest::newRow("") << QString("8b54536f2f3e64a8") << QString("0000000000080000") << QString("0101010101010101");
+ QTest::newRow("") << QString("ea51d3975595b86b") << QString("0000000000040000") << QString("0101010101010101");
+ QTest::newRow("") << QString("caffc6ac4542de31") << QString("0000000000020000") << QString("0101010101010101");
+ QTest::newRow("") << QString("8dd45a2ddf90796c") << QString("0000000000010000") << QString("0101010101010101");
+ QTest::newRow("") << QString("1029d55e880ec2d0") << QString("0000000000008000") << QString("0101010101010101");
+ QTest::newRow("") << QString("5d86cb23639dbea9") << QString("0000000000004000") << QString("0101010101010101");
+ QTest::newRow("") << QString("1d1ca853ae7c0c5f") << QString("0000000000002000") << QString("0101010101010101");
+ QTest::newRow("") << QString("ce332329248f3228") << QString("0000000000001000") << QString("0101010101010101");
+ QTest::newRow("") << QString("8405d1abe24fb942") << QString("0000000000000800") << QString("0101010101010101");
+ QTest::newRow("") << QString("e643d78090ca4207") << QString("0000000000000400") << QString("0101010101010101");
+ QTest::newRow("") << QString("48221b9937748a23") << QString("0000000000000200") << QString("0101010101010101");
+ QTest::newRow("") << QString("dd7c0bbd61fafd54") << QString("0000000000000100") << QString("0101010101010101");
+ QTest::newRow("") << QString("2fbc291a570db5c4") << QString("0000000000000080") << QString("0101010101010101");
+ QTest::newRow("") << QString("e07c30d7e4e26e12") << QString("0000000000000040") << QString("0101010101010101");
+ QTest::newRow("") << QString("0953e2258e8e90a1") << QString("0000000000000020") << QString("0101010101010101");
+ QTest::newRow("") << QString("5b711bc4ceebf2ee") << QString("0000000000000010") << QString("0101010101010101");
+ QTest::newRow("") << QString("cc083f1e6d9e85f6") << QString("0000000000000008") << QString("0101010101010101");
+ QTest::newRow("") << QString("d2fd8867d50d2dfe") << QString("0000000000000004") << QString("0101010101010101");
+ QTest::newRow("") << QString("06e7ea22ce92708f") << QString("0000000000000002") << QString("0101010101010101");
+ QTest::newRow("") << QString("166b40b44aba4bd6") << QString("0000000000000001") << QString("0101010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("95a8d72813daa94d") << QString("8001010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("0eec1487dd8c26d5") << QString("4001010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("7ad16ffb79c45926") << QString("2001010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("d3746294ca6a6cf3") << QString("1001010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("809f5f873c1fd761") << QString("0801010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("c02faffec989d1fc") << QString("0401010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("4615aa1d33e72f10") << QString("0201010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("2055123350c00858") << QString("0180010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("df3b99d6577397c8") << QString("0140010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("31fe17369b5288c9") << QString("0120010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("dfdd3cc64dae1642") << QString("0110010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("178c83ce2b399d94") << QString("0108010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("50f636324a9b7f80") << QString("0104010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("a8468ee3bc18f06d") << QString("0102010101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("a2dc9e92fd3cde92") << QString("0101800101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("cac09f797d031287") << QString("0101400101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("90ba680b22aeb525") << QString("0101200101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("ce7a24f350e280b6") << QString("0101100101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("882bff0aa01a0b87") << QString("0101080101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("25610288924511c2") << QString("0101040101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("c71516c29c75d170") << QString("0101020101010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("5199c29a52c9f059") << QString("0101018001010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("c22f0a294a71f29f") << QString("0101014001010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("ee371483714c02ea") << QString("0101012001010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("a81fbd448f9e522f") << QString("0101011001010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("4f644c92e192dfed") << QString("0101010801010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("1afa9a66a6df92ae") << QString("0101010401010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("b3c1cc715cb879d8") << QString("0101010201010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("19d032e64ab0bd8b") << QString("0101010180010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("3cfaa7a7dc8720dc") << QString("0101010140010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("b7265f7f447ac6f3") << QString("0101010120010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("9db73b3c0d163f54") << QString("0101010110010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("8181b65babf4a975") << QString("0101010108010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("93c9b64042eaa240") << QString("0101010104010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("5570530829705592") << QString("0101010102010101");
+ QTest::newRow("") << QString("0000000000000000") << QString("8638809e878787a0") << QString("0101010101800101");
+ QTest::newRow("") << QString("0000000000000000") << QString("41b9a79af79ac208") << QString("0101010101400101");
+ QTest::newRow("") << QString("0000000000000000") << QString("7a9be42f2009a892") << QString("0101010101200101");
+ QTest::newRow("") << QString("0000000000000000") << QString("29038d56ba6d2745") << QString("0101010101100101");
+ QTest::newRow("") << QString("0000000000000000") << QString("5495c6abf1e5df51") << QString("0101010101080101");
+ QTest::newRow("") << QString("0000000000000000") << QString("ae13dbd561488933") << QString("0101010101040101");
+ QTest::newRow("") << QString("0000000000000000") << QString("024d1ffa8904e389") << QString("0101010101020101");
+ QTest::newRow("") << QString("0000000000000000") << QString("d1399712f99bf02e") << QString("0101010101018001");
+ QTest::newRow("") << QString("0000000000000000") << QString("14c1d7c1cffec79e") << QString("0101010101014001");
+ QTest::newRow("") << QString("0000000000000000") << QString("1de5279dae3bed6f") << QString("0101010101012001");
+ QTest::newRow("") << QString("0000000000000000") << QString("e941a33f85501303") << QString("0101010101011001");
+ QTest::newRow("") << QString("0000000000000000") << QString("da99dbbc9a03f379") << QString("0101010101010801");
+ QTest::newRow("") << QString("0000000000000000") << QString("b7fc92f91d8e92e9") << QString("0101010101010401");
+ QTest::newRow("") << QString("0000000000000000") << QString("ae8e5caa3ca04e85") << QString("0101010101010201");
+ QTest::newRow("") << QString("0000000000000000") << QString("9cc62df43b6eed74") << QString("0101010101010180");
+ QTest::newRow("") << QString("0000000000000000") << QString("d863dbb5c59a91a0") << QString("0101010101010140");
+ QTest::newRow("") << QString("0000000000000000") << QString("a1ab2190545b91d7") << QString("0101010101010120");
+ QTest::newRow("") << QString("0000000000000000") << QString("0875041e64c570f7") << QString("0101010101010110");
+ QTest::newRow("") << QString("0000000000000000") << QString("5a594528bebef1cc") << QString("0101010101010108");
+ QTest::newRow("") << QString("0000000000000000") << QString("fcdb3291de21f0c0") << QString("0101010101010104");
+ QTest::newRow("") << QString("0000000000000000") << QString("869efd7f9f265a09") << QString("0101010101010102");
+ //end of weak keys
+ QTest::newRow("") << QString("0000000000000000") << QString("88d55e54f54c97b4") << QString("1046913489980131");
+ QTest::newRow("") << QString("0000000000000000") << QString("0c0cc00c83ea48fd") << QString("1007103489988020");
+ QTest::newRow("") << QString("0000000000000000") << QString("83bc8ef3a6570183") << QString("10071034c8980120");
+ QTest::newRow("") << QString("0000000000000000") << QString("df725dcad94ea2e9") << QString("1046103489988020");
+ QTest::newRow("") << QString("0000000000000000") << QString("e652b53b550be8b0") << QString("1086911519190101");
+ QTest::newRow("") << QString("0000000000000000") << QString("af527120c485cbb0") << QString("1086911519580101");
+ QTest::newRow("") << QString("0000000000000000") << QString("0f04ce393db926d5") << QString("5107b01519580101");
+ QTest::newRow("") << QString("0000000000000000") << QString("c9f00ffc74079067") << QString("1007b01519190101");
+ QTest::newRow("") << QString("0000000000000000") << QString("7cfd82a593252b4e") << QString("3107915498080101");
+ QTest::newRow("") << QString("0000000000000000") << QString("cb49a2f9e91363e3") << QString("3107919498080101");
+ QTest::newRow("") << QString("0000000000000000") << QString("00b588be70d23f56") << QString("10079115b9080140");
+ QTest::newRow("") << QString("0000000000000000") << QString("406a9a6ab43399ae") << QString("3107911598090140");
+ QTest::newRow("") << QString("0000000000000000") << QString("6cb773611dca9ada") << QString("1007d01589980101");
+ QTest::newRow("") << QString("0000000000000000") << QString("67fd21c17dbb5d70") << QString("9107911589980101");
+ QTest::newRow("") << QString("0000000000000000") << QString("9592cb4110430787") << QString("9107d01589190101");
+ QTest::newRow("") << QString("0000000000000000") << QString("a6b7ff68a318ddd3") << QString("1007d01598980120");
+ QTest::newRow("") << QString("0000000000000000") << QString("4d102196c914ca16") << QString("1007940498190101");
+ QTest::newRow("") << QString("0000000000000000") << QString("2dfa9f4573594965") << QString("0107910491190401");
+ QTest::newRow("") << QString("0000000000000000") << QString("b46604816c0e0774") << QString("0107910491190101");
+ QTest::newRow("") << QString("0000000000000000") << QString("6e7e6221a4f34e87") << QString("0107940491190401");
+ QTest::newRow("") << QString("0000000000000000") << QString("aa85e74643233199") << QString("19079210981a0101");
+ QTest::newRow("") << QString("0000000000000000") << QString("2e5a19db4d1962d6") << QString("1007911998190801");
+ QTest::newRow("") << QString("0000000000000000") << QString("23a866a809d30894") << QString("10079119981a0801");
+ QTest::newRow("") << QString("0000000000000000") << QString("d812d961f017d320") << QString("1007921098190101");
+ QTest::newRow("") << QString("0000000000000000") << QString("055605816e58608f") << QString("100791159819010b");
+ QTest::newRow("") << QString("0000000000000000") << QString("abd88e8b1b7716f1") << QString("1004801598190101");
+ QTest::newRow("") << QString("0000000000000000") << QString("537ac95be69da1e1") << QString("1004801598190102");
+ QTest::newRow("") << QString("0000000000000000") << QString("aed0f6ae3c25cdd8") << QString("1004801598190108");
+ QTest::newRow("") << QString("0000000000000000") << QString("b3e35a5ee53e7b8d") << QString("1002911598100104");
+ QTest::newRow("") << QString("0000000000000000") << QString("61c79c71921a2ef8") << QString("1002911598190104");
+ QTest::newRow("") << QString("0000000000000000") << QString("e2f5728f0995013c") << QString("1002911598100201");
+ QTest::newRow("") << QString("0000000000000000") << QString("1aeac39a61f0a464") << QString("1002911698100101");
+ QTest::newRow("") << QString("059b5e0851cf143a") << QString("86a560f10ec6d85b") << QString("0113b970fd34f2ce");
+ QTest::newRow("") << QString("4e6f772069732074") << QString("3fa40e8a984d4815") << QString("0123456789abcdef");
}
-
void CipherUnitTest::des()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- // providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ // providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "des-ecb", provider ) )
- QWARN( QString( "DES ECB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("des-ecb", provider)) {
+ QWARN(QString("DES ECB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::Cipher forwardCipher( QString( "des" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::Cipher forwardCipher(QString("des"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( forwardCipher.blockSize(), 8 );
- QCOMPARE( forwardCipher.keyLength().minimum(), 8 );
- QCOMPARE( forwardCipher.keyLength().maximum(), 8 );
+ QCOMPARE(forwardCipher.blockSize(), 8);
+ QCOMPARE(forwardCipher.keyLength().minimum(), 8);
+ QCOMPARE(forwardCipher.keyLength().maximum(), 8);
- QString afterEncodeText = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ QString afterEncodeText = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
- afterEncodeText += QCA::arrayToHex( forwardCipher.final().toByteArray() );
- QVERIFY( forwardCipher.ok() );
+ afterEncodeText += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ QVERIFY(forwardCipher.ok());
- QCOMPARE( afterEncodeText, cipherText );
+ QCOMPARE(afterEncodeText, cipherText);
- QCA::Cipher reverseCipher( QString( "des" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- QCA::InitializationVector(),
- provider );
+ QCA::Cipher reverseCipher(QString("des"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ QCA::InitializationVector(),
+ provider);
- QCOMPARE( reverseCipher.blockSize(), 8 );
- QCOMPARE( reverseCipher.keyLength().minimum(), 8 );
- QCOMPARE( reverseCipher.keyLength().maximum(), 8 );
+ QCOMPARE(reverseCipher.blockSize(), 8);
+ QCOMPARE(reverseCipher.keyLength().minimum(), 8);
+ QCOMPARE(reverseCipher.keyLength().maximum(), 8);
- QString afterDecodeText = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ QString afterDecodeText = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
- afterDecodeText += QCA::arrayToHex( reverseCipher.final().toByteArray() );
- QVERIFY( reverseCipher.ok() );
+ afterDecodeText += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QVERIFY(reverseCipher.ok());
- QCOMPARE( afterDecodeText, plainText );
- }
- }
+ QCOMPARE(afterDecodeText, plainText);
+ }
+ }
}
// This is from the Botan test suite
void CipherUnitTest::des_cbc_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
- << QString("e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6")
- << QString("0123456789abcdef")
- << QString("1234567890abcdef");
+ QTest::newRow("1") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
+ << QString("e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6")
+ << QString("0123456789abcdef")
+ << QString("1234567890abcdef");
}
-
void CipherUnitTest::des_cbc()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "des-cbc", provider ) )
- QWARN( QString( "DES CBC not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "des" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "des" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("des-cbc", provider)) {
+ QWARN(QString("DES CBC not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("des"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("des"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
-
// This is from the Botan test suite
void CipherUnitTest::des_cfb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
-
- QTest::newRow("") << QString("5eef8199471c2a7ef97509623cae32c35a90245b70a21ce36e")
- << QString("658b25e25df23948847afa4c9ffdd5b3ddf35d801cbe945168")
- << QString("add9ce7bcf48c44b") << QString("0f90e78835ba3183");
- QTest::newRow("") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
- << QString("f3096249c7f46e51a69e839b1a92f78403467133898ea622")
- << QString("0123456789abcdef") << QString("1234567890abcdef");
- QTest::newRow("") << QString("d14fd67a9b4d7b0f65b7ca3da91741603da446")
- << QString("0cb8929a854e61ab3beb72ce0f13ba328ba73a")
- << QString("7132d895529a7aff") << QString("fa1fe8f921706c75");
- QTest::newRow("") << QString("16") << QString("e1")
- << QString("f51cf13fd55f33b8") << QString("10e61c7f8276132e");
- QTest::newRow("") << QString("b8f7") << QString("9f09")
- << QString("6a2306397e6399af") << QString("6791874e16642dd8");
- QTest::newRow("") << QString("914aa4") << QString("1cddad")
- << QString("08d3b08cb02e2547") << QString("b35072a53fa36190");
- QTest::newRow("") << QString("252f0616") << QString("e22a706a")
- << QString("454a9aca108ad24c") << QString("64dadb33ccf1debd");
- QTest::newRow("") << QString("f06f376c6e") << QString("c2f054e435")
- << QString("087fc9f0b8be08f3") << QString("5e511251c063b3c7");
- QTest::newRow("") << QString("9a181afec04c") << QString("c49218c8a25b")
- << QString("fe1ea0f0ac5f2c02") << QString("a247e69ced4a2bf1");
- QTest::newRow("") << QString("ac465cbd745341") << QString("768b6f5bfa9c24")
- << QString("1e7c7274307edb90") << QString("afb634941c366c1d");
- QTest::newRow("") << QString("52bdfd51e3434e94") << QString("c5d84483756ac360")
- << QString("53e241e43aad03e7") << QString("be0a4ae59056d8fe");
- QTest::newRow("") << QString("a62c02059afe67cd7f") << QString("032a99be4df6b63f97")
- << QString("487c9fbd140ef278") << QString("43f88de155e98523");
- QTest::newRow("") << QString("32d3c8a283257f6276c3") << QString("bcfa26efe2d93a4b1364")
- << QString("8b068595d5b79177") << QString("7129287761d94d9f");
- QTest::newRow("") << QString("17cb11a60f880c16d6cc3a") << QString("3dc099d927b8aa66b2a5c8")
- << QString("750c87995afd65ee") << QString("a61398fff559faad");
- QTest::newRow("") << QString("eaa91cede4efc60f02b1e0ee") << QString("75614ea2fd5474fdfe3a5612")
- << QString("08a5f56200ac9300") << QString("9f9ed0928b8cd2dd");
- QTest::newRow("") << QString("68db8992e91d759256ab373748") << QString("9d0e14f0b2be2d3b47103da75f")
- << QString("b11dfa915ad86ff9") << QString("3885ecf48a611dc5");
- QTest::newRow("") << QString("d75acdd3e4040dfda924ce09e627")
- << QString("a878ce766412a9c387ad61642fb7")
- << QString("fbf9e6d9344b0f2c") << QString("6917f8fe1ac12101");
- QTest::newRow("") << QString("38b667a6e4458c8732aae6f4d0ac36")
- << QString("5bcfd93d6b4b45d9d0d03162fa8fb9")
- << QString("8616d2ea6e6106b3") << QString("cfe4dfa7044f56ab");
- QTest::newRow("") << QString("0b439a72a4430b3d15e234034ba2c066")
- << QString("1adae0a4a0d582b70b60ed1c859a07b3")
- << QString("e255e4a4c3606081") << QString("3f160dff918c3f78");
- QTest::newRow("") << QString("82e27182fc22cd8918dddbdb850034a4f2")
- << QString("9767881b1909db5e146caaf5fc6a118814")
- << QString("b9cdd5442e1c7fd7") << QString("5d1b1eceb7335274");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
+
+ QTest::newRow("") << QString("5eef8199471c2a7ef97509623cae32c35a90245b70a21ce36e")
+ << QString("658b25e25df23948847afa4c9ffdd5b3ddf35d801cbe945168")
+ << QString("add9ce7bcf48c44b") << QString("0f90e78835ba3183");
+ QTest::newRow("") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
+ << QString("f3096249c7f46e51a69e839b1a92f78403467133898ea622")
+ << QString("0123456789abcdef") << QString("1234567890abcdef");
+ QTest::newRow("") << QString("d14fd67a9b4d7b0f65b7ca3da91741603da446")
+ << QString("0cb8929a854e61ab3beb72ce0f13ba328ba73a")
+ << QString("7132d895529a7aff") << QString("fa1fe8f921706c75");
+ QTest::newRow("") << QString("16") << QString("e1")
+ << QString("f51cf13fd55f33b8") << QString("10e61c7f8276132e");
+ QTest::newRow("") << QString("b8f7") << QString("9f09")
+ << QString("6a2306397e6399af") << QString("6791874e16642dd8");
+ QTest::newRow("") << QString("914aa4") << QString("1cddad")
+ << QString("08d3b08cb02e2547") << QString("b35072a53fa36190");
+ QTest::newRow("") << QString("252f0616") << QString("e22a706a")
+ << QString("454a9aca108ad24c") << QString("64dadb33ccf1debd");
+ QTest::newRow("") << QString("f06f376c6e") << QString("c2f054e435")
+ << QString("087fc9f0b8be08f3") << QString("5e511251c063b3c7");
+ QTest::newRow("") << QString("9a181afec04c") << QString("c49218c8a25b")
+ << QString("fe1ea0f0ac5f2c02") << QString("a247e69ced4a2bf1");
+ QTest::newRow("") << QString("ac465cbd745341") << QString("768b6f5bfa9c24")
+ << QString("1e7c7274307edb90") << QString("afb634941c366c1d");
+ QTest::newRow("") << QString("52bdfd51e3434e94") << QString("c5d84483756ac360")
+ << QString("53e241e43aad03e7") << QString("be0a4ae59056d8fe");
+ QTest::newRow("") << QString("a62c02059afe67cd7f") << QString("032a99be4df6b63f97")
+ << QString("487c9fbd140ef278") << QString("43f88de155e98523");
+ QTest::newRow("") << QString("32d3c8a283257f6276c3") << QString("bcfa26efe2d93a4b1364")
+ << QString("8b068595d5b79177") << QString("7129287761d94d9f");
+ QTest::newRow("") << QString("17cb11a60f880c16d6cc3a") << QString("3dc099d927b8aa66b2a5c8")
+ << QString("750c87995afd65ee") << QString("a61398fff559faad");
+ QTest::newRow("") << QString("eaa91cede4efc60f02b1e0ee") << QString("75614ea2fd5474fdfe3a5612")
+ << QString("08a5f56200ac9300") << QString("9f9ed0928b8cd2dd");
+ QTest::newRow("") << QString("68db8992e91d759256ab373748") << QString("9d0e14f0b2be2d3b47103da75f")
+ << QString("b11dfa915ad86ff9") << QString("3885ecf48a611dc5");
+ QTest::newRow("") << QString("d75acdd3e4040dfda924ce09e627")
+ << QString("a878ce766412a9c387ad61642fb7")
+ << QString("fbf9e6d9344b0f2c") << QString("6917f8fe1ac12101");
+ QTest::newRow("") << QString("38b667a6e4458c8732aae6f4d0ac36")
+ << QString("5bcfd93d6b4b45d9d0d03162fa8fb9")
+ << QString("8616d2ea6e6106b3") << QString("cfe4dfa7044f56ab");
+ QTest::newRow("") << QString("0b439a72a4430b3d15e234034ba2c066")
+ << QString("1adae0a4a0d582b70b60ed1c859a07b3")
+ << QString("e255e4a4c3606081") << QString("3f160dff918c3f78");
+ QTest::newRow("") << QString("82e27182fc22cd8918dddbdb850034a4f2")
+ << QString("9767881b1909db5e146caaf5fc6a118814")
+ << QString("b9cdd5442e1c7fd7") << QString("5d1b1eceb7335274");
}
-
void CipherUnitTest::des_cfb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "des-cfb", provider ) )
- QWARN( QString( "DES CFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "des" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "des" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("des-cfb", provider)) {
+ QWARN(QString("DES CFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("des"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("des"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// This is from the Botan test suite
void CipherUnitTest::des_ofb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
-
- QTest::newRow("1") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
- << QString("f3096249c7f46e5135f24a242eeb3d3f3d6d5be3255af8c3")
- << QString("0123456789abcdef") << QString("1234567890abcdef");
- QTest::newRow("2") << QString("b25330d1cab11fddff278192aa2c935a9c7745733e6da8")
- << QString("39b9bf284d6da6e639b8040b8da01e469dba4c6e50b1ab")
- << QString("f871822c7fd1d6a3") << QString("b311792c8bc02ee8");
- QTest::newRow("3") << QString("73ad356623a1d6e0717e838b9344b4fff21bda")
- << QString("0c06e63e9e81d9976e16d2009255f917797d51")
- << QString("5860f4a413de6c68") << QString("527a1e050a9d71f0");
- QTest::newRow("4") << QString("08a6091fa2987fdc682a8199a6d6bd1f")
- << QString("640b5033dcf26873fa8a34db644f2bf2")
- << QString("3307042dc775035e") << QString("99de32ff0351509b");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
+
+ QTest::newRow("1") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
+ << QString("f3096249c7f46e5135f24a242eeb3d3f3d6d5be3255af8c3")
+ << QString("0123456789abcdef") << QString("1234567890abcdef");
+ QTest::newRow("2") << QString("b25330d1cab11fddff278192aa2c935a9c7745733e6da8")
+ << QString("39b9bf284d6da6e639b8040b8da01e469dba4c6e50b1ab")
+ << QString("f871822c7fd1d6a3") << QString("b311792c8bc02ee8");
+ QTest::newRow("3") << QString("73ad356623a1d6e0717e838b9344b4fff21bda")
+ << QString("0c06e63e9e81d9976e16d2009255f917797d51")
+ << QString("5860f4a413de6c68") << QString("527a1e050a9d71f0");
+ QTest::newRow("4") << QString("08a6091fa2987fdc682a8199a6d6bd1f")
+ << QString("640b5033dcf26873fa8a34db644f2bf2")
+ << QString("3307042dc775035e") << QString("99de32ff0351509b");
}
-
void CipherUnitTest::des_ofb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "des-ofb", provider ) )
- QWARN( QString( "DES OFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "des" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "des" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("des-ofb", provider)) {
+ QWARN(QString("DES OFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("des"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("des"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// These are from the Botan test suite
void CipherUnitTest::des_pkcs7_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
-
- QTest::newRow("") << QString("") << QString("705fdf4dc7abfbfc") << QString("02d863a4885d417a");
- QTest::newRow("") << QString("fa") << QString("2281ac7cfa703ba9") << QString("05add235b01bbda7");
- QTest::newRow("") << QString("b895") << QString("8c3bf9ab9d16c8cf") << QString("93f04843afc3a191");
- QTest::newRow("") << QString("8e97de") << QString("be38bd2afe108d2a") << QString("1f4e2c013314b55a");
- QTest::newRow("") << QString("c1dae88e") << QString("998341e8b0cce82e") << QString("0f59c05186431e13");
- QTest::newRow("") << QString("a6e0360e88") << QString("f5e88fcc387b8883") << QString("e68bf7b98d61fed0");
- QTest::newRow("") << QString("55e67a79f043") << QString("a868b107bd96f35c") << QString("ae3ab00a0ba38be0");
- QTest::newRow("") << QString("d77c93b63d6d5b") << QString("19da07a34fa683c4") << QString("9b661c7a536afc6d");
- QTest::newRow("") << QString("328d09508e747ae1")
- << QString("9c75845c6bff94438eb7e7e4c77342f0") << QString("8e1c689280575f05");
- QTest::newRow("") << QString("421d4bdc3869e59f07")
- << QString("8df60dc27a2e2ee23360be31343fcbdb") << QString("eb4a6b437572e1e7");
- QTest::newRow("") << QString("160e525583c3e4fbc4fe")
- << QString("9b649660dfe5b875cd81180ad627943f") << QString("ffe58726b90c9f97");
- QTest::newRow("") << QString("e873b3c2b31130719e6469")
- << QString("6e33ae2af48cc39697800a3aa357cc5e")
- << QString("560ee1ed2cc2bffb");
- QTest::newRow("") << QString("405915adc0111eb8af225612")
- << QString("569be1f2ae91785b0634f8dd4ec1dff2") << QString("012a7de9cbfbd230");
- QTest::newRow("") << QString("e923c535186730f309cdea6dea")
- << QString("846d7314f76e00902054bd2b2ae1f580") << QString("3d5d56ca2e8e359c");
- QTest::newRow("") << QString("116053a5820f9d36650eef49a05b")
- << QString("9bd56c43036485b648efe6d31e69f0c6") << QString("2ad63a5312bf4259");
- QTest::newRow("") << QString("b6dcd40077fe89138b5a2ed35e1b3d")
- << QString("2fbe419bada6d4bf3f6c7bb2a1aac329") << QString("7ff12d4d8a9ef138");
- QTest::newRow("") << QString("08f0aa208f8a06c6292838a8cee9104e")
- << QString("44bfca2722d274504af482e9261cdb7b16918be77a461b3b")
- << QString("f71a3b1aabd660bd");
- QTest::newRow("") << QString("878412f6255ff4360a22772711289fd351")
- << QString("9c92fdde178d3b6c895aad1b8dc886176910b021d5b3aa77")
- << QString("1ed8b08898872631");
- QTest::newRow("") << QString("1399a0cd9f2778bcfba9c0f7e7c89ca069e3")
- << QString("5972f89d8c161dd30a409bcdbf43b20bb104e8a293c48fdd")
- << QString("0dcb3527035253a5");
- QTest::newRow("") << QString("ea1cc272d3725e4c5dc56079fa3c9f26a1373a")
- << QString("d1b2fcc83cbf11e022c058fcb988cbbbc3843517f5e9d900")
- << QString("bf4b260909243b2f");
- QTest::newRow("") << QString("098dd47ea5784d307c115824cfc3443983fdf58b")
- << QString("77dfae7f46af6db0d0e5775859943e2875854a680b54b59b")
- << QString("5d869f3486dfe1a1");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+
+ QTest::newRow("") << QString("") << QString("705fdf4dc7abfbfc") << QString("02d863a4885d417a");
+ QTest::newRow("") << QString("fa") << QString("2281ac7cfa703ba9") << QString("05add235b01bbda7");
+ QTest::newRow("") << QString("b895") << QString("8c3bf9ab9d16c8cf") << QString("93f04843afc3a191");
+ QTest::newRow("") << QString("8e97de") << QString("be38bd2afe108d2a") << QString("1f4e2c013314b55a");
+ QTest::newRow("") << QString("c1dae88e") << QString("998341e8b0cce82e") << QString("0f59c05186431e13");
+ QTest::newRow("") << QString("a6e0360e88") << QString("f5e88fcc387b8883") << QString("e68bf7b98d61fed0");
+ QTest::newRow("") << QString("55e67a79f043") << QString("a868b107bd96f35c") << QString("ae3ab00a0ba38be0");
+ QTest::newRow("") << QString("d77c93b63d6d5b") << QString("19da07a34fa683c4") << QString("9b661c7a536afc6d");
+ QTest::newRow("") << QString("328d09508e747ae1")
+ << QString("9c75845c6bff94438eb7e7e4c77342f0") << QString("8e1c689280575f05");
+ QTest::newRow("") << QString("421d4bdc3869e59f07")
+ << QString("8df60dc27a2e2ee23360be31343fcbdb") << QString("eb4a6b437572e1e7");
+ QTest::newRow("") << QString("160e525583c3e4fbc4fe")
+ << QString("9b649660dfe5b875cd81180ad627943f") << QString("ffe58726b90c9f97");
+ QTest::newRow("") << QString("e873b3c2b31130719e6469")
+ << QString("6e33ae2af48cc39697800a3aa357cc5e")
+ << QString("560ee1ed2cc2bffb");
+ QTest::newRow("") << QString("405915adc0111eb8af225612")
+ << QString("569be1f2ae91785b0634f8dd4ec1dff2") << QString("012a7de9cbfbd230");
+ QTest::newRow("") << QString("e923c535186730f309cdea6dea")
+ << QString("846d7314f76e00902054bd2b2ae1f580") << QString("3d5d56ca2e8e359c");
+ QTest::newRow("") << QString("116053a5820f9d36650eef49a05b")
+ << QString("9bd56c43036485b648efe6d31e69f0c6") << QString("2ad63a5312bf4259");
+ QTest::newRow("") << QString("b6dcd40077fe89138b5a2ed35e1b3d")
+ << QString("2fbe419bada6d4bf3f6c7bb2a1aac329") << QString("7ff12d4d8a9ef138");
+ QTest::newRow("") << QString("08f0aa208f8a06c6292838a8cee9104e")
+ << QString("44bfca2722d274504af482e9261cdb7b16918be77a461b3b")
+ << QString("f71a3b1aabd660bd");
+ QTest::newRow("") << QString("878412f6255ff4360a22772711289fd351")
+ << QString("9c92fdde178d3b6c895aad1b8dc886176910b021d5b3aa77")
+ << QString("1ed8b08898872631");
+ QTest::newRow("") << QString("1399a0cd9f2778bcfba9c0f7e7c89ca069e3")
+ << QString("5972f89d8c161dd30a409bcdbf43b20bb104e8a293c48fdd")
+ << QString("0dcb3527035253a5");
+ QTest::newRow("") << QString("ea1cc272d3725e4c5dc56079fa3c9f26a1373a")
+ << QString("d1b2fcc83cbf11e022c058fcb988cbbbc3843517f5e9d900")
+ << QString("bf4b260909243b2f");
+ QTest::newRow("") << QString("098dd47ea5784d307c115824cfc3443983fdf58b")
+ << QString("77dfae7f46af6db0d0e5775859943e2875854a680b54b59b")
+ << QString("5d869f3486dfe1a1");
}
-
// This is DES ECB, PKCS7 padding
void CipherUnitTest::des_pkcs7()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "des-ecb-pkcs7", provider ) )
- QWARN( QString( "DES ECB with PKCS7 padding not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- // just a filler
- QCA::InitializationVector iv;
- QCA::Cipher forwardCipher( QString( "des" ),
- QCA::Cipher::ECB,
- QCA::Cipher::PKCS7,
- QCA::Encode,
- key,
- iv,
- provider);
-
- QCOMPARE( forwardCipher.keyLength().minimum(), 8 );
- QCOMPARE( forwardCipher.keyLength().maximum(), 8 );
- QCOMPARE( forwardCipher.blockSize(), 8 );
-
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update, cipherText.left(update.size()) );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "des" ),
- QCA::Cipher::ECB,
- QCA::Cipher::PKCS7,
- QCA::Decode,
- key,
- iv,
- provider);
-
- QCOMPARE( reverseCipher.keyLength().minimum(), 8 );
- QCOMPARE( reverseCipher.keyLength().maximum(), 8 );
- QCOMPARE( reverseCipher.blockSize(), 8 );
-
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size()) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("des-ecb-pkcs7", provider)) {
+ QWARN(QString("DES ECB with PKCS7 padding not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ // just a filler
+ QCA::InitializationVector iv;
+ QCA::Cipher forwardCipher(QString("des"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::PKCS7,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(forwardCipher.keyLength().minimum(), 8);
+ QCOMPARE(forwardCipher.keyLength().maximum(), 8);
+ QCOMPARE(forwardCipher.blockSize(), 8);
+
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update, cipherText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("des"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::PKCS7,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(reverseCipher.keyLength().minimum(), 8);
+ QCOMPARE(reverseCipher.keyLength().maximum(), 8);
+ QCOMPARE(reverseCipher.blockSize(), 8);
+
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// These are from the Botan test suite
void CipherUnitTest::des_cbc_pkcs7_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
-
- QTest::newRow("1") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
- << QString("e5c7cdde872bf27c43e934008c389c0f683788499a7c05f662c16a27e4fcf277")
- << QString("0123456789abcdef") << QString("1234567890abcdef");
- QTest::newRow("2") << QString("") << QString("ff4903e653af83c4")
- << QString("46b534fbffdae457") << QString("297873b948a44b5f");
- QTest::newRow("3") << QString("69") << QString("60fa7b46523aa51f")
- << QString("d581a1d0c70f94a1") << QString("c1ddd7447249ef80");
- QTest::newRow("4") << QString("02b7") << QString("63c1c1ef79555ed8")
- << QString("a415b62e7e94caf2") << QString("57fa9b2f95f57401");
- QTest::newRow("5") << QString("568960") << QString("d0321483090f524d")
- << QString("5dcbe42db374090e") << QString("b6215a095582763f");
- QTest::newRow("6") << QString("b6eaf23c") << QString("88e289e1de3e6451")
- << QString("8fe92291c654ec9b") << QString("0c054bbd31a9f623");
- QTest::newRow("7") << QString("60a658cbbd") << QString("89bffa9e36ff1780")
- << QString("dbcee35e86088501") << QString("11a8928bc6d0d117");
- QTest::newRow("8") << QString("7e10cbd9e95c") << QString("afc5cdf559abc6d3")
- << QString("72338f946012ced5") << QString("eaaa48b0c2ee2f3f");
- QTest::newRow("9") << QString("d907ce88f077fa") << QString("3476402272856ea8")
- << QString("837fbb3167f0ccaa") << QString("cd399dd3e402f8f2");
- QTest::newRow("10") << QString("9476e85b198c9aee") << QString("1af298a150514ca70d252f88271b3ca7")
- << QString("308d1c02e7a4e09d") << QString("6baa74f7f1a72e1f");
- QTest::newRow("11") << QString("5c11285270e9606cdf") << QString("78665abfe3def34f8bd55796825ee915")
- << QString("126aff39882542ea") << QString("51badb479de66a73");
- QTest::newRow("12") << QString("d1d3d8675e42a4242fba")
- << QString("e77bb4a24b4ee8c9ebda4971c2e60d10")
- << QString("0ae8510bb0fb3994") << QString("6c7293a8427bcb3b");
- QTest::newRow("13") << QString("65026a8a41edc1d880f6c9")
- << QString("45a6ef4acd49f9f1d892a808fa7b6f28")
- << QString("0be9277b3504d524") << QString("e47ec7a77db94755");
- QTest::newRow("14") << QString("d72e81f4130107e396d5fb27")
- << QString("a88eff91876a1b6958d52f99fe9b18fb")
- << QString("2f03c36de4f78e13") << QString("99fd2e8848f33fe7");
- QTest::newRow("15") << QString("c8a3971efda18af1b18bfad98f")
- << QString("54ff90bd90f6213d761f4b3ff89a8ded")
- << QString("69329672e546c969") << QString("294922cbe7e12341");
- QTest::newRow("16") << QString("bb9a90f11551531de512dd48270e")
- << QString("9ba7908e56edb1bef992faee40f5b1ca")
- << QString("3007d71e86d8eaf2") << QString("d7e300e168f60063");
- QTest::newRow("17") << QString("77d6c182e4ddd444d614bcff98fb13")
- << QString("cb50dec4728fc2f1a1a5dfb84fa1bd25")
- << QString("f73c8c3355092eb6") << QString("2e0db2552bb83ad3");
- QTest::newRow("18") << QString("40aed22f93dcfcb1d734b7e4657dd31a")
- << QString("66d17a6e9d5be3281e857b4c7e497988ca684524fd994882")
- << QString("dd006f15e727cb62") << QString("b256dc4fdb58451b");
- QTest::newRow("19") << QString("bb25564c7ea1e5bd22016915805c27b51b")
- << QString("b7ceb5f5ed2945f131064bbb9213694b19a04fbd1f138866")
- << QString("df70ff987582ccfe") << QString("88bb3b9bb2ea56d7");
- QTest::newRow("20") << QString("49dab8d85ea753cf4ae2ece7a80f0784e42b")
- << QString("d7fce9e5bed161ad7d950e453677e5bee422b7542afc0bd3")
- << QString("747e09fa9ba257dc") << QString("f1bbd406191de0d1");
- QTest::newRow("21") << QString("dc13a6abaa35ceb3e6650f825a67942114af2e")
- << QString("bafdb50e16c9ff4449bf336d410441d56e1e5335b54c9f11")
- << QString("cdad411d0fa80e9d") << QString("c83d55b1196958c4");
- QTest::newRow("22") << QString("a8896d88907ad77ae790828c0a3384c1614e07d9")
- << QString("70a9eb1c11bfd1b1d68c20a6b72c869dac5372a8ed46aa07")
- << QString("642d12c591f6a4f4") << QString("c17d0c69067af296");
- QTest::newRow("23") << QString("b3fec4cc29dc1abbcf7d86f01d2c02c2a723e7c2f8")
- << QString("48ed5583a04d333ffac9d6462fd96bf79222eeec70a6ae70")
- << QString("62c62f54c426c59f") << QString("cb6252ca271ff303");
- QTest::newRow("24") << QString("ac0b4d5752d2009bdcd42314d9723716294146424542")
- << QString("8a284713f8c9873ad5f558b995c5a67a66557a52601975d1")
- << QString("386dcad5eae86830") << QString("48153b966c8d686d");
- QTest::newRow("25") << QString("ea331f6e518a8aeab2ef0a4e92e0d198df5dd0cc74369e")
- << QString("6d3d7de9938935f9fb9af839e416ef6f842f2ed827334bfb")
- << QString("782545ea65d89b01") << QString("c2ce203020aabb0a");
- QTest::newRow("26") << QString("b292d3a3fdc5d709709c87ef91122761847871f9b4e33426")
- << QString("21dae17d157192146b52c49d90f898b25d0d1dfe677e8cd5b568814e9c6bb6a8")
- << QString("ecc650e1ed1ce8a0") << QString("aebc43ab811ab5f1");
- QTest::newRow("27") << QString("65026a8a41edc1d880f6c90be9277b3504d524e47ec7a77db9")
- << QString("a3b6404c4d87f72d5e0995d7cc20ece742d9705d48524cfa2820317087faf578")
- << QString("4755b8639fd7c8a1") << QString("4152e22f14baaf0a");
- QTest::newRow("28") << QString("d1d3d8675e42a4242fba0ae8510bb0fb39946c7293a8427bcb3b")
- << QString("db621f2fac9a924c83ed0b9e8acec9f1e23bf3ff2ad6efa814903f2ce293107b")
- << QString("92a18b78a25c4b7a") << QString("c3aabc68ceeb22d9");
- QTest::newRow("29") << QString("c8a3971efda18af1b18bfad98f69329672e546c969294922cbe7e1")
- << QString("940c610a41f04e7d9be0a74d5d00fe97a2647d3d16e9b76ff0db5bbdc197c82a")
- << QString("2341239c09c73427") << QString("c4d5b2b6863db060");
- QTest::newRow("30") << QString("d72e81f4130107e396d5fb272f03c36de4f78e1399fd2e8848f33fe7")
- << QString("7d495cba50c4127347e3ad29e3b8c098a3312782e3d45abfa1621f64bf8b8a06")
- << QString("166ea8ed9d29e1b0") << QString("2be993c1be8fe9ed");
- QTest::newRow("31") << QString("77d6c182e4ddd444d614bcff98fb13f73c8c3355092eb62e0db2552bb8")
- << QString("9d926142271e814ba4603509187c9020daa0d50f15af6e698e384644e9468c11")
- << QString("3ad3301094b2f471") << QString("8638489af44732f0");
- QTest::newRow("32") << QString("bb9a90f11551531de512dd48270e3007d71e86d8eaf2d7e300e168f60063")
- << QString("44858416f946c7fbdffd720282881630803803ab91ceab1af4f68f50e9c16dce")
- << QString("04bbfd95ac12e6ff") << QString("30cb120d13391c44");
- QTest::newRow("33") << QString("8eb8faf49126ad5b8a0aa6df8b52dbe50dd5aed271641ef983bd650da69816")
- << QString("5b4622f1c4faa817ee3ac181b969a7afed7117e23f68bc6017519a7d1399cfe9")
- << QString("35501029e137d63d") << QString("c1e0e3a06b357b51");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
+
+ QTest::newRow("1") << QString("4e6f77206973207468652074696d6520666f7220616c6c20")
+ << QString("e5c7cdde872bf27c43e934008c389c0f683788499a7c05f662c16a27e4fcf277")
+ << QString("0123456789abcdef") << QString("1234567890abcdef");
+ QTest::newRow("2") << QString("") << QString("ff4903e653af83c4")
+ << QString("46b534fbffdae457") << QString("297873b948a44b5f");
+ QTest::newRow("3") << QString("69") << QString("60fa7b46523aa51f")
+ << QString("d581a1d0c70f94a1") << QString("c1ddd7447249ef80");
+ QTest::newRow("4") << QString("02b7") << QString("63c1c1ef79555ed8")
+ << QString("a415b62e7e94caf2") << QString("57fa9b2f95f57401");
+ QTest::newRow("5") << QString("568960") << QString("d0321483090f524d")
+ << QString("5dcbe42db374090e") << QString("b6215a095582763f");
+ QTest::newRow("6") << QString("b6eaf23c") << QString("88e289e1de3e6451")
+ << QString("8fe92291c654ec9b") << QString("0c054bbd31a9f623");
+ QTest::newRow("7") << QString("60a658cbbd") << QString("89bffa9e36ff1780")
+ << QString("dbcee35e86088501") << QString("11a8928bc6d0d117");
+ QTest::newRow("8") << QString("7e10cbd9e95c") << QString("afc5cdf559abc6d3")
+ << QString("72338f946012ced5") << QString("eaaa48b0c2ee2f3f");
+ QTest::newRow("9") << QString("d907ce88f077fa") << QString("3476402272856ea8")
+ << QString("837fbb3167f0ccaa") << QString("cd399dd3e402f8f2");
+ QTest::newRow("10") << QString("9476e85b198c9aee") << QString("1af298a150514ca70d252f88271b3ca7")
+ << QString("308d1c02e7a4e09d") << QString("6baa74f7f1a72e1f");
+ QTest::newRow("11") << QString("5c11285270e9606cdf") << QString("78665abfe3def34f8bd55796825ee915")
+ << QString("126aff39882542ea") << QString("51badb479de66a73");
+ QTest::newRow("12") << QString("d1d3d8675e42a4242fba")
+ << QString("e77bb4a24b4ee8c9ebda4971c2e60d10")
+ << QString("0ae8510bb0fb3994") << QString("6c7293a8427bcb3b");
+ QTest::newRow("13") << QString("65026a8a41edc1d880f6c9")
+ << QString("45a6ef4acd49f9f1d892a808fa7b6f28")
+ << QString("0be9277b3504d524") << QString("e47ec7a77db94755");
+ QTest::newRow("14") << QString("d72e81f4130107e396d5fb27")
+ << QString("a88eff91876a1b6958d52f99fe9b18fb")
+ << QString("2f03c36de4f78e13") << QString("99fd2e8848f33fe7");
+ QTest::newRow("15") << QString("c8a3971efda18af1b18bfad98f")
+ << QString("54ff90bd90f6213d761f4b3ff89a8ded")
+ << QString("69329672e546c969") << QString("294922cbe7e12341");
+ QTest::newRow("16") << QString("bb9a90f11551531de512dd48270e")
+ << QString("9ba7908e56edb1bef992faee40f5b1ca")
+ << QString("3007d71e86d8eaf2") << QString("d7e300e168f60063");
+ QTest::newRow("17") << QString("77d6c182e4ddd444d614bcff98fb13")
+ << QString("cb50dec4728fc2f1a1a5dfb84fa1bd25")
+ << QString("f73c8c3355092eb6") << QString("2e0db2552bb83ad3");
+ QTest::newRow("18") << QString("40aed22f93dcfcb1d734b7e4657dd31a")
+ << QString("66d17a6e9d5be3281e857b4c7e497988ca684524fd994882")
+ << QString("dd006f15e727cb62") << QString("b256dc4fdb58451b");
+ QTest::newRow("19") << QString("bb25564c7ea1e5bd22016915805c27b51b")
+ << QString("b7ceb5f5ed2945f131064bbb9213694b19a04fbd1f138866")
+ << QString("df70ff987582ccfe") << QString("88bb3b9bb2ea56d7");
+ QTest::newRow("20") << QString("49dab8d85ea753cf4ae2ece7a80f0784e42b")
+ << QString("d7fce9e5bed161ad7d950e453677e5bee422b7542afc0bd3")
+ << QString("747e09fa9ba257dc") << QString("f1bbd406191de0d1");
+ QTest::newRow("21") << QString("dc13a6abaa35ceb3e6650f825a67942114af2e")
+ << QString("bafdb50e16c9ff4449bf336d410441d56e1e5335b54c9f11")
+ << QString("cdad411d0fa80e9d") << QString("c83d55b1196958c4");
+ QTest::newRow("22") << QString("a8896d88907ad77ae790828c0a3384c1614e07d9")
+ << QString("70a9eb1c11bfd1b1d68c20a6b72c869dac5372a8ed46aa07")
+ << QString("642d12c591f6a4f4") << QString("c17d0c69067af296");
+ QTest::newRow("23") << QString("b3fec4cc29dc1abbcf7d86f01d2c02c2a723e7c2f8")
+ << QString("48ed5583a04d333ffac9d6462fd96bf79222eeec70a6ae70")
+ << QString("62c62f54c426c59f") << QString("cb6252ca271ff303");
+ QTest::newRow("24") << QString("ac0b4d5752d2009bdcd42314d9723716294146424542")
+ << QString("8a284713f8c9873ad5f558b995c5a67a66557a52601975d1")
+ << QString("386dcad5eae86830") << QString("48153b966c8d686d");
+ QTest::newRow("25") << QString("ea331f6e518a8aeab2ef0a4e92e0d198df5dd0cc74369e")
+ << QString("6d3d7de9938935f9fb9af839e416ef6f842f2ed827334bfb")
+ << QString("782545ea65d89b01") << QString("c2ce203020aabb0a");
+ QTest::newRow("26") << QString("b292d3a3fdc5d709709c87ef91122761847871f9b4e33426")
+ << QString("21dae17d157192146b52c49d90f898b25d0d1dfe677e8cd5b568814e9c6bb6a8")
+ << QString("ecc650e1ed1ce8a0") << QString("aebc43ab811ab5f1");
+ QTest::newRow("27") << QString("65026a8a41edc1d880f6c90be9277b3504d524e47ec7a77db9")
+ << QString("a3b6404c4d87f72d5e0995d7cc20ece742d9705d48524cfa2820317087faf578")
+ << QString("4755b8639fd7c8a1") << QString("4152e22f14baaf0a");
+ QTest::newRow("28") << QString("d1d3d8675e42a4242fba0ae8510bb0fb39946c7293a8427bcb3b")
+ << QString("db621f2fac9a924c83ed0b9e8acec9f1e23bf3ff2ad6efa814903f2ce293107b")
+ << QString("92a18b78a25c4b7a") << QString("c3aabc68ceeb22d9");
+ QTest::newRow("29") << QString("c8a3971efda18af1b18bfad98f69329672e546c969294922cbe7e1")
+ << QString("940c610a41f04e7d9be0a74d5d00fe97a2647d3d16e9b76ff0db5bbdc197c82a")
+ << QString("2341239c09c73427") << QString("c4d5b2b6863db060");
+ QTest::newRow("30") << QString("d72e81f4130107e396d5fb272f03c36de4f78e1399fd2e8848f33fe7")
+ << QString("7d495cba50c4127347e3ad29e3b8c098a3312782e3d45abfa1621f64bf8b8a06")
+ << QString("166ea8ed9d29e1b0") << QString("2be993c1be8fe9ed");
+ QTest::newRow("31") << QString("77d6c182e4ddd444d614bcff98fb13f73c8c3355092eb62e0db2552bb8")
+ << QString("9d926142271e814ba4603509187c9020daa0d50f15af6e698e384644e9468c11")
+ << QString("3ad3301094b2f471") << QString("8638489af44732f0");
+ QTest::newRow("32") << QString("bb9a90f11551531de512dd48270e3007d71e86d8eaf2d7e300e168f60063")
+ << QString("44858416f946c7fbdffd720282881630803803ab91ceab1af4f68f50e9c16dce")
+ << QString("04bbfd95ac12e6ff") << QString("30cb120d13391c44");
+ QTest::newRow("33") << QString("8eb8faf49126ad5b8a0aa6df8b52dbe50dd5aed271641ef983bd650da69816")
+ << QString("5b4622f1c4faa817ee3ac181b969a7afed7117e23f68bc6017519a7d1399cfe9")
+ << QString("35501029e137d63d") << QString("c1e0e3a06b357b51");
}
void CipherUnitTest::des_cbc_pkcs7()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- // providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "des-cbc-pkcs7", provider ) )
- QWARN( QString( "DES CBC with PKCS7 padding not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "des" ),
- QCA::Cipher::CBC,
- QCA::Cipher::PKCS7,
- QCA::Encode,
- key,
- iv,
- provider);
-
- QCOMPARE( forwardCipher.keyLength().minimum(), 8 );
- QCOMPARE( forwardCipher.keyLength().maximum(), 8 );
- QCOMPARE( forwardCipher.blockSize(), 8 );
-
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update, cipherText.left(update.size()) );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "des" ),
- QCA::Cipher::CBC,
- QCA::Cipher::PKCS7,
- QCA::Decode,
- key,
- iv,
- provider);
-
- QCOMPARE( reverseCipher.keyLength().minimum(), 8 );
- QCOMPARE( reverseCipher.keyLength().maximum(), 8 );
- QCOMPARE( reverseCipher.blockSize(), 8 );
-
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size()) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ // providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("des-cbc-pkcs7", provider)) {
+ QWARN(QString("DES CBC with PKCS7 padding not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("des"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::PKCS7,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(forwardCipher.keyLength().minimum(), 8);
+ QCOMPARE(forwardCipher.keyLength().maximum(), 8);
+ QCOMPARE(forwardCipher.blockSize(), 8);
+
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update, cipherText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("des"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::PKCS7,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(reverseCipher.keyLength().minimum(), 8);
+ QCOMPARE(reverseCipher.keyLength().maximum(), 8);
+ QCOMPARE(reverseCipher.blockSize(), 8);
+
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
#if 0
-if (!QCA::isSupported("des-ecb-pkcs7") )
-QWARN("DES, ECB mode with PKCS7 padding not supported!");
-else {
-QCA::Cipher cipherObj1( QString( "des" ),
- QCA::Cipher::ECB,
- QCA::Cipher::PKCS7,
- QCA::Encode,
- QCA::SymmetricKey( 8 ) );
-QCOMPARE( cipherObj1.keyLength().minimum(), 8 );
-QCOMPARE( cipherObj1.keyLength().maximum(), 8 );
-QCOMPARE( cipherObj1.blockSize(), 8 );
-
-for (int n = 0; (0 != desEcbPkcs7TestValues[n].plaintext); n++) {
- QCA::SymmetricKey key( QCA::hexToArray( desEcbPkcs7TestValues[n].key ) );
- QCA::DES forwardCipher( QCA::Cipher::ECB, QCA::Cipher::PKCS7, QCA::Encode, key);
- QCOMPARE( QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( desEcbPkcs7TestValues[n].plaintext ) ).toByteArray() ),
- QString( desEcbPkcs7TestValues[n].ciphertext ) );
- QCOMPARE( forwardCipher.ok(), true );
- QCOMPARE( QCA::arrayToHex( forwardCipher.final().toByteArray() ), QString( "" ) );
- QCOMPARE( forwardCipher.ok(), true );
-
- QCA::DES reverseCipher( QCA::Cipher::ECB, QCA::Cipher::PKCS7, QCA::Decode, key);
-
- QCOMPARE( QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( desEcbPkcs7TestValues[n].ciphertext ) ).toByteArray() ),
- QString( desEcbPkcs7TestValues[n].plaintext ) );
- QCOMPARE( reverseCipher.ok(), true );
- QCOMPARE( QCA::arrayToHex( reverseCipher.final().toByteArray() ), QString( "" ) );
- QCOMPARE( reverseCipher.ok(), true );
-}
+if (!QCA::isSupported("des-ecb-pkcs7"))
+{
+ QWARN("DES, ECB mode with PKCS7 padding not supported!");
+} else
+{
+ QCA::Cipher cipherObj1(QString("des"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::PKCS7,
+ QCA::Encode,
+ QCA::SymmetricKey(8));
+ QCOMPARE(cipherObj1.keyLength().minimum(), 8);
+ QCOMPARE(cipherObj1.keyLength().maximum(), 8);
+ QCOMPARE(cipherObj1.blockSize(), 8);
+
+ for (int n = 0; (0 != desEcbPkcs7TestValues[n].plaintext); n++) {
+ QCA::SymmetricKey key(QCA::hexToArray(desEcbPkcs7TestValues[n].key));
+ QCA::DES forwardCipher(QCA::Cipher::ECB, QCA::Cipher::PKCS7, QCA::Encode, key);
+ QCOMPARE(QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(desEcbPkcs7TestValues[n].plaintext)).toByteArray()),
+ QString(desEcbPkcs7TestValues[n].ciphertext));
+ QCOMPARE(forwardCipher.ok(), true);
+ QCOMPARE(QCA::arrayToHex(forwardCipher.final().toByteArray()), QString(""));
+ QCOMPARE(forwardCipher.ok(), true);
+
+ QCA::DES reverseCipher(QCA::Cipher::ECB, QCA::Cipher::PKCS7, QCA::Decode, key);
+
+ QCOMPARE(QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(desEcbPkcs7TestValues[n].ciphertext)).toByteArray()),
+ QString(desEcbPkcs7TestValues[n].plaintext));
+ QCOMPARE(reverseCipher.ok(), true);
+ QCOMPARE(QCA::arrayToHex(reverseCipher.final().toByteArray()), QString(""));
+ QCOMPARE(reverseCipher.ok(), true);
+ }
}
#endif
// These are from the Botan test suite. They match the test vectors from Bruce's site
void CipherUnitTest::blowfish_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
-
- QTest::newRow("1") << QString("0000000000000000") << QString("245946885754369a") << QString("0123456789abcdef" );
- QTest::newRow("2") << QString("0000000000000000") << QString("4ef997456198dd78") << QString("0000000000000000" );
- QTest::newRow("3") << QString("0000000000000000") << QString("f21e9a77b71c49bc") << QString("ffffffffffffffff" );
- QTest::newRow("4") << QString("004bd6ef09176062") << QString("452031c1e4fada8e") << QString("584023641aba6176" );
- QTest::newRow("5") << QString("0123456789abcdef") << QString("0aceab0fc6a0a28d") << QString("fedcba9876543210" );
- QTest::newRow("6") << QString("0123456789abcdef") << QString("7d0cc630afda1ec7") << QString("1111111111111111" );
- QTest::newRow("7") << QString("0123456789abcdef") << QString("a790795108ea3cae") << QString("1f1f1f1f0e0e0e0e" );
- QTest::newRow("8") << QString("0123456789abcdef") << QString("c39e072d9fac631d") << QString("e0fee0fef1fef1fe" );
- QTest::newRow("9") << QString("0123456789abcdef") << QString("fa34ec4847b268b2") << QString("0101010101010101" );
- QTest::newRow("10") << QString("01a1d6d039776742") << QString("59c68245eb05282b") << QString("7ca110454a1a6e57" );
- QTest::newRow("11") << QString("0248d43806f67172") << QString("1730e5778bea1da4") << QString("07a1133e4a0b2686" );
- QTest::newRow("12") << QString("02fe55778117f12a") << QString("cf9c5d7a4986adb5") << QString("49e95d6d4ca229bf" );
- QTest::newRow("13") << QString("059b5e0851cf143a") << QString("48f4d0884c379918") << QString("0113b970fd34f2ce" );
- QTest::newRow("14") << QString("072d43a077075292") << QString("7a8e7bfa937e89a3") << QString("4fb05e1515ab73a7" );
- QTest::newRow("15") << QString("0756d8e0774761d2") << QString("432193b78951fc98") << QString("0170f175468fb5e6" );
- QTest::newRow("16") << QString("1000000000000001") << QString("7d856f9a613063f2") << QString("3000000000000000" );
- QTest::newRow("17") << QString("1111111111111111") << QString("2466dd878b963c9d") << QString("1111111111111111" );
- QTest::newRow("18") << QString("1111111111111111") << QString("61f9c3802281b096") << QString("0123456789abcdef" );
- QTest::newRow("19") << QString("164d5e404f275232") << QString("5f99d04f5b163969") << QString("37d06bb516cb7546" );
- QTest::newRow("20") << QString("1d9d5c5018f728c2") << QString("d1abb290658bc778") << QString("018310dc409b26d6" );
- QTest::newRow("21") << QString("26955f6835af609a") << QString("d887e0393c2da6e3") << QString("04689104c2fd3b2f" );
- QTest::newRow("22") << QString("305532286d6f295a") << QString("55cb3774d13ef201") << QString("1c587f1c13924fef" );
- QTest::newRow("23") << QString("3bdd119049372802") << QString("2eedda93ffd39c79") << QString("07a7137045da2a16" );
- QTest::newRow("24") << QString("42fd443059577fa2") << QString("353882b109ce8f1a") << QString("04b915ba43feb5b6" );
- QTest::newRow("25") << QString("437540c8698f3cfa") << QString("53c55f9cb49fc019") << QString("49793ebc79b3258f" );
- QTest::newRow("26") << QString("480d39006ee762f2") << QString("7555ae39f59b87bd") << QString("025816164629b007" );
- QTest::newRow("27") << QString("51454b582ddf440a") << QString("a25e7856cf2651eb") << QString("3849674c2602319e" );
- QTest::newRow("28") << QString("5cd54ca83def57da") << QString("b1b8cc0b250f09a0") << QString("0131d9619dc1376e" );
- QTest::newRow("29") << QString("6b056e18759f5cca") << QString("4a057a3b24d3977b") << QString("1f08260d1ac2465e" );
- QTest::newRow("30") << QString("762514b829bf486a") << QString("13f04154d69d1ae5") << QString("43297fad38e373fe" );
- QTest::newRow("31") << QString("ffffffffffffffff") << QString("014933e0cdaff6e4") << QString("0000000000000000" );
- QTest::newRow("32") << QString("ffffffffffffffff") << QString("51866fd5b85ecb8a") << QString("ffffffffffffffff" );
- QTest::newRow("33") << QString("ffffffffffffffff") << QString("6b5c5a9c5d9e0a5a") << QString("fedcba9876543210" );
- QTest::newRow("34") << QString("0123456789abcdef1111111111111111") << QString("7d0cc630afda1ec72466dd878b963c9d")
- << QString("1111111111111111" );
- QTest::newRow("35") << QString("fedcba9876543210") << QString("cc91732b8022f684")
- << QString("57686f206973204a6f686e2047616c743f" );
- QTest::newRow("36") << QString("424c4f5746495348") << QString("324ed0fef413a203")
- << QString("6162636465666768696a6b6c6d6e6f707172737475767778797a" );
- QTest::newRow("37") << QString("fedcba9876543210") << QString("f9ad597c49db005e") << QString("f0" );
- QTest::newRow("38") << QString("fedcba9876543210") << QString("e91d21c1d961a6d6") << QString("f0e1" );
- QTest::newRow("39") << QString("fedcba9876543210") << QString("e9c2b70a1bc65cf3") << QString("f0e1d2" );
- QTest::newRow("40") << QString("fedcba9876543210") << QString("be1e639408640f05") << QString("f0e1d2c3" );
- QTest::newRow("41") << QString("fedcba9876543210") << QString("b39e44481bdb1e6e") << QString("f0e1d2c3b4" );
- QTest::newRow("42") << QString("fedcba9876543210") << QString("9457aa83b1928c0d") << QString("f0e1d2c3b4a5" );
- QTest::newRow("43") << QString("fedcba9876543210") << QString("8bb77032f960629d") << QString("f0e1d2c3b4a596" );
- QTest::newRow("44") << QString("fedcba9876543210") << QString("e87a244e2cc85e82") << QString("f0e1d2c3b4a59687" );
- QTest::newRow("45") << QString("fedcba9876543210") << QString("15750e7a4f4ec577") << QString("f0e1d2c3b4a5968778" );
- QTest::newRow("46") << QString("fedcba9876543210") << QString("122ba70b3ab64ae0") << QString("f0e1d2c3b4a596877869" );
- QTest::newRow("47") << QString("fedcba9876543210") << QString("3a833c9affc537f6")
- << QString("f0e1d2c3b4a5968778695a" );
- QTest::newRow("48") << QString("fedcba9876543210") << QString("9409da87a90f6bf2")
- << QString("f0e1d2c3b4a5968778695a4b" );
- QTest::newRow("49") << QString("fedcba9876543210") << QString("884f80625060b8b4")
- << QString("f0e1d2c3b4a5968778695a4b3c" );
- QTest::newRow("50") << QString("fedcba9876543210") << QString("1f85031c19e11968")
- << QString("f0e1d2c3b4a5968778695a4b3c2d" );
- QTest::newRow("51") << QString("fedcba9876543210") << QString("79d9373a714ca34f")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e" );
- QTest::newRow("52") << QString("fedcba9876543210") << QString("93142887ee3be15c")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f" );
- QTest::newRow("53") << QString("fedcba9876543210") << QString("03429e838ce2d14b")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f00" );
- QTest::newRow("54") << QString("fedcba9876543210") << QString("a4299e27469ff67b")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f0011" );
- QTest::newRow("55") << QString("fedcba9876543210") << QString("afd5aed1c1bc96a8")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f001122" );
- QTest::newRow("56") << QString("fedcba9876543210") << QString("10851c0e3858da9f")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f00112233" );
- QTest::newRow("57") << QString("fedcba9876543210") << QString("e6f51ed79b9db21f")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f0011223344" );
- QTest::newRow("58") << QString("fedcba9876543210") << QString("64a6e14afd36b46f")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f001122334455" );
- QTest::newRow("59") << QString("fedcba9876543210") << QString("80c7d7d45a5479ad")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f00112233445566" );
- QTest::newRow("60") << QString("fedcba9876543210") << QString("05044b62fa52d080")
- << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f0011223344556677" );
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+
+ QTest::newRow("1") << QString("0000000000000000") << QString("245946885754369a") << QString("0123456789abcdef");
+ QTest::newRow("2") << QString("0000000000000000") << QString("4ef997456198dd78") << QString("0000000000000000");
+ QTest::newRow("3") << QString("0000000000000000") << QString("f21e9a77b71c49bc") << QString("ffffffffffffffff");
+ QTest::newRow("4") << QString("004bd6ef09176062") << QString("452031c1e4fada8e") << QString("584023641aba6176");
+ QTest::newRow("5") << QString("0123456789abcdef") << QString("0aceab0fc6a0a28d") << QString("fedcba9876543210");
+ QTest::newRow("6") << QString("0123456789abcdef") << QString("7d0cc630afda1ec7") << QString("1111111111111111");
+ QTest::newRow("7") << QString("0123456789abcdef") << QString("a790795108ea3cae") << QString("1f1f1f1f0e0e0e0e");
+ QTest::newRow("8") << QString("0123456789abcdef") << QString("c39e072d9fac631d") << QString("e0fee0fef1fef1fe");
+ QTest::newRow("9") << QString("0123456789abcdef") << QString("fa34ec4847b268b2") << QString("0101010101010101");
+ QTest::newRow("10") << QString("01a1d6d039776742") << QString("59c68245eb05282b") << QString("7ca110454a1a6e57");
+ QTest::newRow("11") << QString("0248d43806f67172") << QString("1730e5778bea1da4") << QString("07a1133e4a0b2686");
+ QTest::newRow("12") << QString("02fe55778117f12a") << QString("cf9c5d7a4986adb5") << QString("49e95d6d4ca229bf");
+ QTest::newRow("13") << QString("059b5e0851cf143a") << QString("48f4d0884c379918") << QString("0113b970fd34f2ce");
+ QTest::newRow("14") << QString("072d43a077075292") << QString("7a8e7bfa937e89a3") << QString("4fb05e1515ab73a7");
+ QTest::newRow("15") << QString("0756d8e0774761d2") << QString("432193b78951fc98") << QString("0170f175468fb5e6");
+ QTest::newRow("16") << QString("1000000000000001") << QString("7d856f9a613063f2") << QString("3000000000000000");
+ QTest::newRow("17") << QString("1111111111111111") << QString("2466dd878b963c9d") << QString("1111111111111111");
+ QTest::newRow("18") << QString("1111111111111111") << QString("61f9c3802281b096") << QString("0123456789abcdef");
+ QTest::newRow("19") << QString("164d5e404f275232") << QString("5f99d04f5b163969") << QString("37d06bb516cb7546");
+ QTest::newRow("20") << QString("1d9d5c5018f728c2") << QString("d1abb290658bc778") << QString("018310dc409b26d6");
+ QTest::newRow("21") << QString("26955f6835af609a") << QString("d887e0393c2da6e3") << QString("04689104c2fd3b2f");
+ QTest::newRow("22") << QString("305532286d6f295a") << QString("55cb3774d13ef201") << QString("1c587f1c13924fef");
+ QTest::newRow("23") << QString("3bdd119049372802") << QString("2eedda93ffd39c79") << QString("07a7137045da2a16");
+ QTest::newRow("24") << QString("42fd443059577fa2") << QString("353882b109ce8f1a") << QString("04b915ba43feb5b6");
+ QTest::newRow("25") << QString("437540c8698f3cfa") << QString("53c55f9cb49fc019") << QString("49793ebc79b3258f");
+ QTest::newRow("26") << QString("480d39006ee762f2") << QString("7555ae39f59b87bd") << QString("025816164629b007");
+ QTest::newRow("27") << QString("51454b582ddf440a") << QString("a25e7856cf2651eb") << QString("3849674c2602319e");
+ QTest::newRow("28") << QString("5cd54ca83def57da") << QString("b1b8cc0b250f09a0") << QString("0131d9619dc1376e");
+ QTest::newRow("29") << QString("6b056e18759f5cca") << QString("4a057a3b24d3977b") << QString("1f08260d1ac2465e");
+ QTest::newRow("30") << QString("762514b829bf486a") << QString("13f04154d69d1ae5") << QString("43297fad38e373fe");
+ QTest::newRow("31") << QString("ffffffffffffffff") << QString("014933e0cdaff6e4") << QString("0000000000000000");
+ QTest::newRow("32") << QString("ffffffffffffffff") << QString("51866fd5b85ecb8a") << QString("ffffffffffffffff");
+ QTest::newRow("33") << QString("ffffffffffffffff") << QString("6b5c5a9c5d9e0a5a") << QString("fedcba9876543210");
+ QTest::newRow("34") << QString("0123456789abcdef1111111111111111") << QString("7d0cc630afda1ec72466dd878b963c9d")
+ << QString("1111111111111111");
+ QTest::newRow("35") << QString("fedcba9876543210") << QString("cc91732b8022f684")
+ << QString("57686f206973204a6f686e2047616c743f");
+ QTest::newRow("36") << QString("424c4f5746495348") << QString("324ed0fef413a203")
+ << QString("6162636465666768696a6b6c6d6e6f707172737475767778797a");
+ QTest::newRow("37") << QString("fedcba9876543210") << QString("f9ad597c49db005e") << QString("f0");
+ QTest::newRow("38") << QString("fedcba9876543210") << QString("e91d21c1d961a6d6") << QString("f0e1");
+ QTest::newRow("39") << QString("fedcba9876543210") << QString("e9c2b70a1bc65cf3") << QString("f0e1d2");
+ QTest::newRow("40") << QString("fedcba9876543210") << QString("be1e639408640f05") << QString("f0e1d2c3");
+ QTest::newRow("41") << QString("fedcba9876543210") << QString("b39e44481bdb1e6e") << QString("f0e1d2c3b4");
+ QTest::newRow("42") << QString("fedcba9876543210") << QString("9457aa83b1928c0d") << QString("f0e1d2c3b4a5");
+ QTest::newRow("43") << QString("fedcba9876543210") << QString("8bb77032f960629d") << QString("f0e1d2c3b4a596");
+ QTest::newRow("44") << QString("fedcba9876543210") << QString("e87a244e2cc85e82") << QString("f0e1d2c3b4a59687");
+ QTest::newRow("45") << QString("fedcba9876543210") << QString("15750e7a4f4ec577") << QString("f0e1d2c3b4a5968778");
+ QTest::newRow("46") << QString("fedcba9876543210") << QString("122ba70b3ab64ae0") << QString("f0e1d2c3b4a596877869");
+ QTest::newRow("47") << QString("fedcba9876543210") << QString("3a833c9affc537f6")
+ << QString("f0e1d2c3b4a5968778695a");
+ QTest::newRow("48") << QString("fedcba9876543210") << QString("9409da87a90f6bf2")
+ << QString("f0e1d2c3b4a5968778695a4b");
+ QTest::newRow("49") << QString("fedcba9876543210") << QString("884f80625060b8b4")
+ << QString("f0e1d2c3b4a5968778695a4b3c");
+ QTest::newRow("50") << QString("fedcba9876543210") << QString("1f85031c19e11968")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d");
+ QTest::newRow("51") << QString("fedcba9876543210") << QString("79d9373a714ca34f")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e");
+ QTest::newRow("52") << QString("fedcba9876543210") << QString("93142887ee3be15c")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f");
+ QTest::newRow("53") << QString("fedcba9876543210") << QString("03429e838ce2d14b")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f00");
+ QTest::newRow("54") << QString("fedcba9876543210") << QString("a4299e27469ff67b")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f0011");
+ QTest::newRow("55") << QString("fedcba9876543210") << QString("afd5aed1c1bc96a8")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f001122");
+ QTest::newRow("56") << QString("fedcba9876543210") << QString("10851c0e3858da9f")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f00112233");
+ QTest::newRow("57") << QString("fedcba9876543210") << QString("e6f51ed79b9db21f")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f0011223344");
+ QTest::newRow("58") << QString("fedcba9876543210") << QString("64a6e14afd36b46f")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f001122334455");
+ QTest::newRow("59") << QString("fedcba9876543210") << QString("80c7d7d45a5479ad")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f00112233445566");
+ QTest::newRow("60") << QString("fedcba9876543210") << QString("05044b62fa52d080")
+ << QString("f0e1d2c3b4a5968778695a4b3c2d1e0f0011223344556677");
}
-
void CipherUnitTest::blowfish()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- // providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "blowfish-ecb", provider ) )
- QWARN( QString( "Blowfish ECB not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Cipher cipherObj1( QString( "blowfish" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- QCA::SymmetricKey( 16 ),
- QCA::InitializationVector(), provider );
-
- // TODO: add some test for min and max keysizes
- QCOMPARE( cipherObj1.blockSize(), 8 );
-
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::Cipher forwardCipher( QString( "blowfish" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- QCA::InitializationVector(),
- provider );
-
- QString afterEncodeText = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
-
- afterEncodeText += QCA::arrayToHex( forwardCipher.final().toByteArray() );
- QVERIFY( forwardCipher.ok() );
-
- QCOMPARE( afterEncodeText, cipherText );
-
- QCA::Cipher reverseCipher( QString( "blowfish" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- QCA::InitializationVector(),
- provider );
- QString afterDecodeText = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
-
- afterDecodeText += QCA::arrayToHex( reverseCipher.final().toByteArray() );
- QVERIFY( reverseCipher.ok() );
-
- QCOMPARE( afterDecodeText, plainText );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ // providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("blowfish-ecb", provider)) {
+ QWARN(QString("Blowfish ECB not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Cipher cipherObj1(QString("blowfish"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ QCA::SymmetricKey(16),
+ QCA::InitializationVector(), provider);
+
+ // TODO: add some test for min and max keysizes
+ QCOMPARE(cipherObj1.blockSize(), 8);
+
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::Cipher forwardCipher(QString("blowfish"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ QCA::InitializationVector(),
+ provider);
+
+ QString afterEncodeText = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+
+ afterEncodeText += QCA::arrayToHex(forwardCipher.final().toByteArray());
+ QVERIFY(forwardCipher.ok());
+
+ QCOMPARE(afterEncodeText, cipherText);
+
+ QCA::Cipher reverseCipher(QString("blowfish"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ QCA::InitializationVector(),
+ provider);
+ QString afterDecodeText = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+
+ afterDecodeText += QCA::arrayToHex(reverseCipher.final().toByteArray());
+ QVERIFY(reverseCipher.ok());
+
+ QCOMPARE(afterDecodeText, plainText);
+ }
+ }
}
// From the Eric Young test vectors on Bruce's site. I modified
// them to remove the incomplete block.
void CipherUnitTest::blowfish_cbc_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520")
- << QString("6b77b4d63006dee605b156e27403979358deb9e7154616d9")
- << QString("0123456789abcdeff0e1d2c3b4a59687")
- << QString("fedcba9876543210");
- QTest::newRow("pkcs7") << QString("37363534333231204e6f77206973207468652074696d6520666f722000030303")
- << QString("6b77b4d63006dee605b156e27403979358deb9e7154616d9749decbec05d264b")
- << QString("0123456789abcdeff0e1d2c3b4a59687")
- << QString("fedcba9876543210");
+ QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520")
+ << QString("6b77b4d63006dee605b156e27403979358deb9e7154616d9")
+ << QString("0123456789abcdeff0e1d2c3b4a59687")
+ << QString("fedcba9876543210");
+ QTest::newRow("pkcs7") << QString("37363534333231204e6f77206973207468652074696d6520666f722000030303")
+ << QString("6b77b4d63006dee605b156e27403979358deb9e7154616d9749decbec05d264b")
+ << QString("0123456789abcdeff0e1d2c3b4a59687")
+ << QString("fedcba9876543210");
}
-
void CipherUnitTest::blowfish_cbc()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "blowfish-cbc", provider ) )
- QWARN( QString( "Blowfish CBC not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "blowfish" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "blowfish" ),
- QCA::Cipher::CBC,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size() ) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("blowfish-cbc", provider)) {
+ QWARN(QString("Blowfish CBC not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("blowfish"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("blowfish"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// I can't find any independent test vectors. I used the no padding case, with hand padding added,
// as a poor check.
void CipherUnitTest::blowfish_cbc_pkcs7_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
-
- QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520666f722000")
- << QString("6b77b4d63006dee605b156e27403979358deb9e7154616d9749decbec05d264b")
- << QString("0123456789abcdeff0e1d2c3b4a59687")
- << QString("fedcba9876543210");
+ QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520666f722000")
+ << QString("6b77b4d63006dee605b156e27403979358deb9e7154616d9749decbec05d264b")
+ << QString("0123456789abcdeff0e1d2c3b4a59687")
+ << QString("fedcba9876543210");
}
void CipherUnitTest::blowfish_cbc_pkcs7()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-nss");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "blowfish-cbc-pkcs7", provider ) )
- QWARN( QString( "Blowfish CBC with PKCS7 padding not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "blowfish" ),
- QCA::Cipher::CBC,
- QCA::Cipher::PKCS7,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update, cipherText.left(update.size()) );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "blowfish" ),
- QCA::Cipher::CBC,
- QCA::Cipher::PKCS7,
- QCA::Decode,
- key,
- iv,
- provider);
- update = QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( update, plainText.left(update.size()) );
- QCOMPARE( update + QCA::arrayToHex( reverseCipher.final().toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-nss");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("blowfish-cbc-pkcs7", provider)) {
+ QWARN(QString("Blowfish CBC with PKCS7 padding not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("blowfish"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::PKCS7,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update, cipherText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("blowfish"),
+ QCA::Cipher::CBC,
+ QCA::Cipher::PKCS7,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ update = QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray());
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(update, plainText.left(update.size()));
+ QCOMPARE(update + QCA::arrayToHex(reverseCipher.final().toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
-
// From the Eric Young test vectors on Bruce's site:
void CipherUnitTest::blowfish_cfb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520666f722000")
- << QString("e73214a2822139caf26ecf6d2eb9e76e3da3de04d1517200519d57a6c3")
- << QString("0123456789abcdeff0e1d2c3b4a59687")
- << QString("fedcba9876543210");
+ QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520666f722000")
+ << QString("e73214a2822139caf26ecf6d2eb9e76e3da3de04d1517200519d57a6c3")
+ << QString("0123456789abcdeff0e1d2c3b4a59687")
+ << QString("fedcba9876543210");
}
void CipherUnitTest::blowfish_cfb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "blowfish-cfb", provider ) )
- QWARN( QString( "Blowfish CFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "blowfish" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "blowfish" ),
- QCA::Cipher::CFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
- QCOMPARE( QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( QCA::arrayToHex( reverseCipher.final().toByteArray() ), QString( "" ) );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("blowfish-cfb", provider)) {
+ QWARN(QString("Blowfish CFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("blowfish"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("blowfish"),
+ QCA::Cipher::CFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+ QCOMPARE(QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(QCA::arrayToHex(reverseCipher.final().toByteArray()), QString(""));
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
// From the Eric Young test vectors on Bruce's site:
void CipherUnitTest::blowfish_ofb_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
- QTest::addColumn<QString>("ivText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("ivText");
- QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520666f722000")
- << QString("e73214a2822139ca62b343cc5b65587310dd908d0c241b2263c2cf80da")
- << QString("0123456789abcdeff0e1d2c3b4a59687")
- << QString("fedcba9876543210");
+ QTest::newRow("1") << QString("37363534333231204e6f77206973207468652074696d6520666f722000")
+ << QString("e73214a2822139ca62b343cc5b65587310dd908d0c241b2263c2cf80da")
+ << QString("0123456789abcdeff0e1d2c3b4a59687")
+ << QString("fedcba9876543210");
}
void CipherUnitTest::blowfish_ofb()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-gcrypt");
- providersToTest.append("qca-botan");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "blowfish-ofb", provider ) )
- QWARN( QString( "Blowfish OFB not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
- QFETCH( QString, ivText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv( QCA::hexToArray( ivText ) );
- QCA::Cipher forwardCipher( QString( "blowfish" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "blowfish" ),
- QCA::Cipher::OFB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
-
- QCOMPARE( QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( QCA::arrayToHex( reverseCipher.final().toByteArray() ), QString( "" ) );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-gcrypt");
+ providersToTest.append("qca-botan");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("blowfish-ofb", provider)) {
+ QWARN(QString("Blowfish OFB not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+ QFETCH(QString, ivText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv(QCA::hexToArray(ivText));
+ QCA::Cipher forwardCipher(QString("blowfish"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("blowfish"),
+ QCA::Cipher::OFB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(QCA::arrayToHex(reverseCipher.final().toByteArray()), QString(""));
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
-
// From RFC2144 Appendix B
void CipherUnitTest::cast5_data()
{
- QTest::addColumn<QString>("plainText");
- QTest::addColumn<QString>("cipherText");
- QTest::addColumn<QString>("keyText");
+ QTest::addColumn<QString>("plainText");
+ QTest::addColumn<QString>("cipherText");
+ QTest::addColumn<QString>("keyText");
- QTest::newRow("128-bit") << QString("0123456789abcdef")
- << QString("238b4fe5847e44b2")
- << QString("0123456712345678234567893456789A");
+ QTest::newRow("128-bit") << QString("0123456789abcdef")
+ << QString("238b4fe5847e44b2")
+ << QString("0123456712345678234567893456789A");
- QTest::newRow("80-bit") << QString("0123456789abcdef")
- << QString("eb6a711a2c02271b")
- << QString("01234567123456782345");
+ QTest::newRow("80-bit") << QString("0123456789abcdef")
+ << QString("eb6a711a2c02271b")
+ << QString("01234567123456782345");
- QTest::newRow("40-bit") << QString("0123456789abcdef")
- << QString("7ac816d16e9b302e")
- << QString("0123456712");
+ QTest::newRow("40-bit") << QString("0123456789abcdef")
+ << QString("7ac816d16e9b302e")
+ << QString("0123456712");
}
void CipherUnitTest::cast5()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
-
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cast5-ecb", provider ) )
- QWARN( QString( "CAST5 not supported for "+provider).toLocal8Bit() );
- else {
- QFETCH( QString, plainText );
- QFETCH( QString, cipherText );
- QFETCH( QString, keyText );
-
- QCA::SymmetricKey key( QCA::hexToArray( keyText ) );
- QCA::InitializationVector iv;
- QCA::Cipher forwardCipher( QString( "cast5" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Encode,
- key,
- iv,
- provider);
- QString update = QCA::arrayToHex( forwardCipher.update( QCA::hexToArray( plainText ) ).toByteArray() );
- QVERIFY( forwardCipher.ok() );
- QCOMPARE( update + QCA::arrayToHex( forwardCipher.final().toByteArray() ), cipherText );
- QVERIFY( forwardCipher.ok() );
-
- QCA::Cipher reverseCipher( QString( "cast5" ),
- QCA::Cipher::ECB,
- QCA::Cipher::NoPadding,
- QCA::Decode,
- key,
- iv,
- provider);
-
- QCOMPARE( QCA::arrayToHex( reverseCipher.update( QCA::hexToArray( cipherText ) ).toByteArray() ), plainText );
- QVERIFY( reverseCipher.ok() );
- QCOMPARE( QCA::arrayToHex( reverseCipher.final().toByteArray() ), QString( "" ) );
- QVERIFY( reverseCipher.ok() );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cast5-ecb", provider)) {
+ QWARN(QString("CAST5 not supported for " + provider).toLocal8Bit());
+ } else {
+ QFETCH(QString, plainText);
+ QFETCH(QString, cipherText);
+ QFETCH(QString, keyText);
+
+ QCA::SymmetricKey key(QCA::hexToArray(keyText));
+ QCA::InitializationVector iv;
+ QCA::Cipher forwardCipher(QString("cast5"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Encode,
+ key,
+ iv,
+ provider);
+ QString update = QCA::arrayToHex(forwardCipher.update(QCA::hexToArray(plainText)).toByteArray());
+ QVERIFY(forwardCipher.ok());
+ QCOMPARE(update + QCA::arrayToHex(forwardCipher.final().toByteArray()), cipherText);
+ QVERIFY(forwardCipher.ok());
+
+ QCA::Cipher reverseCipher(QString("cast5"),
+ QCA::Cipher::ECB,
+ QCA::Cipher::NoPadding,
+ QCA::Decode,
+ key,
+ iv,
+ provider);
+
+ QCOMPARE(QCA::arrayToHex(reverseCipher.update(QCA::hexToArray(cipherText)).toByteArray()), plainText);
+ QVERIFY(reverseCipher.ok());
+ QCOMPARE(QCA::arrayToHex(reverseCipher.final().toByteArray()), QString(""));
+ QVERIFY(reverseCipher.ok());
+ }
+ }
}
-
-
QTEST_MAIN(CipherUnitTest)
diff --git a/unittest/cipherunittest/cipherunittest.h b/unittest/cipherunittest/cipherunittest.h
index bb3ece4d..69876598 100644
--- a/unittest/cipherunittest/cipherunittest.h
+++ b/unittest/cipherunittest/cipherunittest.h
@@ -1,126 +1,125 @@
/**
* Copyright (C) 2004-2007 Brad Hards <bradh@frogmouth.net>
* Copyright (C) 2013-2016 Ivan Romanov <drizt@land.ru>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CIPHERUNITTEST_H
#define CIPHERUNITTEST_H
#include <QtCrypto>
class CipherUnitTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
- void initTestCase();
- void cleanupTestCase();
- void aes128_data();
- void aes128();
- void aes128_cbc_data();
- void aes128_cbc();
- void aes128_cbc_pkcs7_data();
- void aes128_cbc_pkcs7();
- void aes128_cfb_data();
- void aes128_cfb();
- void aes128_ofb_data();
- void aes128_ofb();
- void aes128_ctr_data();
- void aes128_ctr();
- void aes128_gcm_data();
- void aes128_gcm();
- void aes128_ccm_data();
- void aes128_ccm();
+ void initTestCase();
+ void cleanupTestCase();
+ void aes128_data();
+ void aes128();
+ void aes128_cbc_data();
+ void aes128_cbc();
+ void aes128_cbc_pkcs7_data();
+ void aes128_cbc_pkcs7();
+ void aes128_cfb_data();
+ void aes128_cfb();
+ void aes128_ofb_data();
+ void aes128_ofb();
+ void aes128_ctr_data();
+ void aes128_ctr();
+ void aes128_gcm_data();
+ void aes128_gcm();
+ void aes128_ccm_data();
+ void aes128_ccm();
- void aes192_data();
- void aes192();
- void aes192_cbc_data();
- void aes192_cbc();
- void aes192_cbc_pkcs7_data();
- void aes192_cbc_pkcs7();
- void aes192_cfb_data();
- void aes192_cfb();
- void aes192_ofb_data();
- void aes192_ofb();
- void aes192_ctr_data();
- void aes192_ctr();
- void aes192_gcm_data();
- void aes192_gcm();
- void aes192_ccm_data();
- void aes192_ccm();
+ void aes192_data();
+ void aes192();
+ void aes192_cbc_data();
+ void aes192_cbc();
+ void aes192_cbc_pkcs7_data();
+ void aes192_cbc_pkcs7();
+ void aes192_cfb_data();
+ void aes192_cfb();
+ void aes192_ofb_data();
+ void aes192_ofb();
+ void aes192_ctr_data();
+ void aes192_ctr();
+ void aes192_gcm_data();
+ void aes192_gcm();
+ void aes192_ccm_data();
+ void aes192_ccm();
- void aes256_data();
- void aes256();
- void aes256_cbc_data();
- void aes256_cbc();
- void aes256_cbc_pkcs7_data();
- void aes256_cbc_pkcs7();
- void aes256_cfb_data();
- void aes256_cfb();
- void aes256_ofb_data();
- void aes256_ofb();
- void aes256_ctr_data();
- void aes256_ctr();
- void aes256_gcm_data();
- void aes256_gcm();
- void aes256_ccm_data();
- void aes256_ccm();
+ void aes256_data();
+ void aes256();
+ void aes256_cbc_data();
+ void aes256_cbc();
+ void aes256_cbc_pkcs7_data();
+ void aes256_cbc_pkcs7();
+ void aes256_cfb_data();
+ void aes256_cfb();
+ void aes256_ofb_data();
+ void aes256_ofb();
+ void aes256_ctr_data();
+ void aes256_ctr();
+ void aes256_gcm_data();
+ void aes256_gcm();
+ void aes256_ccm_data();
+ void aes256_ccm();
- void tripleDES_data();
- void tripleDES();
+ void tripleDES_data();
+ void tripleDES();
- void des_data();
- void des();
- void des_pkcs7_data();
- void des_pkcs7();
- void des_cbc_data();
- void des_cbc();
- void des_cbc_pkcs7_data();
- void des_cbc_pkcs7();
- void des_cfb_data();
- void des_cfb();
- void des_ofb_data();
- void des_ofb();
+ void des_data();
+ void des();
+ void des_pkcs7_data();
+ void des_pkcs7();
+ void des_cbc_data();
+ void des_cbc();
+ void des_cbc_pkcs7_data();
+ void des_cbc_pkcs7();
+ void des_cfb_data();
+ void des_cfb();
+ void des_ofb_data();
+ void des_ofb();
- void blowfish_data();
- void blowfish();
- void blowfish_cbc_data();
- void blowfish_cbc();
- void blowfish_cbc_pkcs7_data();
- void blowfish_cbc_pkcs7();
- void blowfish_cfb_data();
- void blowfish_cfb();
- void blowfish_ofb_data();
- void blowfish_ofb();
+ void blowfish_data();
+ void blowfish();
+ void blowfish_cbc_data();
+ void blowfish_cbc();
+ void blowfish_cbc_pkcs7_data();
+ void blowfish_cbc_pkcs7();
+ void blowfish_cfb_data();
+ void blowfish_cfb();
+ void blowfish_ofb_data();
+ void blowfish_ofb();
-
- void cast5_data();
- void cast5();
+ void cast5_data();
+ void cast5();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
#endif // CIPHERUNITTEST_H
diff --git a/unittest/clientplugin/clientplugin.cpp b/unittest/clientplugin/clientplugin.cpp
index 7b33a52c..a93ebdea 100644
--- a/unittest/clientplugin/clientplugin.cpp
+++ b/unittest/clientplugin/clientplugin.cpp
@@ -1,112 +1,115 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtCore/QPointer>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class ClientPlugin : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testInsertRemovePlugin();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void ClientPlugin::initTestCase()
{
m_init = new QCA::Initializer;
}
void ClientPlugin::cleanupTestCase()
{
delete m_init;
}
const QString providerName = "testClientSideProvider";
class TestClientProvider : public QObject, public QCA::Provider
{
- Q_OBJECT
+ Q_OBJECT
public:
- int qcaVersion() const
+ int qcaVersion() const
+ {
+ return QCA_VERSION;
+ }
+
+ QString name() const
+ {
+ return providerName;
+ }
+
+ QStringList features() const
+ {
+ QStringList list;
+ list += "testClientSideProviderFeature1";
+ list += "testClientSideProviderFeature2";
+ return list;
+ }
+
+ Provider::Context *createContext(const QString &type)
+ {
+ if (type == "testClientSideProviderFeature1")
+ // return new Feature1Context(this);
{
- return QCA_VERSION;
- }
-
- QString name() const
- {
- return providerName;
- }
-
- QStringList features() const
- {
- QStringList list;
- list += "testClientSideProviderFeature1";
- list += "testClientSideProviderFeature2";
- return list;
- }
-
- Provider::Context *createContext(const QString &type)
+ return 0;
+ } else if (type == "testClientSideProviderFeature2")
+ // return new Feature2Context(this);
{
- if(type == "testClientSideProviderFeature1")
- // return new Feature1Context(this);
- return 0;
- else if (type == "testClientSideProviderFeature2")
- // return new Feature2Context(this);
- return 0;
- else
- return 0;
+ return 0;
+ } else {
+ return 0;
}
+ }
};
void ClientPlugin::testInsertRemovePlugin()
{
QPointer<TestClientProvider> provider = new TestClientProvider;
QVERIFY(QCA::insertProvider(provider, 10));
QCOMPARE(QCA::findProvider(providerName), provider.data());
QCOMPARE(QCA::providerPriority(providerName), 10);
QVERIFY(QCA::unloadProvider(providerName));
QCOMPARE(QCA::findProvider(providerName), static_cast<QCA::Provider *>(0));
QVERIFY(provider.isNull());
}
QTEST_MAIN(ClientPlugin)
#include "clientplugin.moc"
diff --git a/unittest/clientplugin/clientplugin.h b/unittest/clientplugin/clientplugin.h
index e1dc65b3..7de72d29 100644
--- a/unittest/clientplugin/clientplugin.h
+++ b/unittest/clientplugin/clientplugin.h
@@ -1,45 +1,45 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef CLIENTPLUGIN_H
#define CLIENTPLUGIN_H
#include <QtCrypto>
#include <QtTest/QtTest>
class ClientPlugin : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testInsertPlugin();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
#endif
diff --git a/unittest/cms/cms.cpp b/unittest/cms/cms.cpp
index 042d7873..c78db3cd 100644
--- a/unittest/cms/cms.cpp
+++ b/unittest/cms/cms.cpp
@@ -1,504 +1,500 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class CMSut : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void xcrypt_data();
void xcrypt();
void signverify_data();
void signverify();
void signverify_message_data();
void signverify_message();
void signverify_message_invalid_data();
void signverify_message_invalid();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
-
void CMSut::initTestCase()
{
m_init = new QCA::Initializer;
}
void CMSut::cleanupTestCase()
{
delete m_init;
}
void CMSut::xcrypt_data()
{
QTest::addColumn<QByteArray>("testText");
QTest::newRow("empty") << QByteArray("");
QTest::newRow("0") << QByteArray("0");
QTest::newRow("07") << QByteArray("07899847jkjjfasjaJKJLJkljklj&kjlj;/**-+.01");
QTest::newRow("dubious") << QByteArray("~!#**$#&&%^@#^&()");
}
void CMSut::xcrypt()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate not supported for "+provider).toLocal8Bit() );
- else if( !QCA::isSupported( "cms", provider ) )
- QWARN( QString( "CMS not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate pubCert = QCA::Certificate::fromPEMFile( "QcaTestClientCert.pem",0, provider );
- QCOMPARE( pubCert.isNull(), false );
-
- QCA::SecureMessageKey secMsgKey;
- QCA::CertificateChain chain;
- chain += pubCert;
- secMsgKey.setX509CertificateChain( chain );
-
- QCA::CMS cms;
- QCA::SecureMessage msg(&cms);
- QCOMPARE( msg.canClearsign(), false );
- QCOMPARE( msg.canSignAndEncrypt(), false );
- QCOMPARE( msg.type(), QCA::SecureMessage::CMS );
-
- msg.setRecipient(secMsgKey);
-
- QFETCH( QByteArray, testText );
-
- msg.startEncrypt();
- msg.update(testText);
- msg.end();
-
- msg.waitForFinished(-1);
-
- QByteArray encryptedResult1 = msg.read();
- QCOMPARE( encryptedResult1.isEmpty(), false );
-
- msg.reset();
- msg.setRecipient(secMsgKey);
- msg.startEncrypt();
- msg.update( testText );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.success() );
-
- QByteArray encryptedResult2 = msg.read();
- QCOMPARE( encryptedResult2.isEmpty(), false );
-
- QCA::ConvertResult res;
- QCA::SecureArray passPhrase = "start";
- QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile( "QcaTestClientKey.pem", passPhrase, &res );
- QCOMPARE( res, QCA::ConvertGood );
-
- secMsgKey.setX509PrivateKey( privKey );
- QCA::SecureMessageKeyList privKeyList;
- privKeyList += secMsgKey;
- QCA::CMS cms2;
- cms2.setPrivateKeys( privKeyList );
-
- QCA::SecureMessage msg2( &cms2 );
-
- msg2.startDecrypt();
- msg2.update( encryptedResult1 );
- msg2.end();
- msg2.waitForFinished(-1);
- QVERIFY( msg2.success() );
- QByteArray decryptedResult1 = msg2.read();
- QCOMPARE( decryptedResult1, testText );
-
- msg2.reset();
- msg2.startDecrypt();
- msg2.update( encryptedResult1 );
- msg2.end();
- msg2.waitForFinished(-1);
- QVERIFY( msg2.success() );
- QByteArray decryptedResult2 = msg2.read();
-
- QCOMPARE( decryptedResult1, decryptedResult2 );
-
- QCOMPARE( msg2.canClearsign(), false );
- QCOMPARE( msg2.canSignAndEncrypt(), false );
- QCOMPARE( msg2.type(), QCA::SecureMessage::CMS );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate not supported for " + provider).toLocal8Bit());
+ } else if (!QCA::isSupported("cms", provider)) {
+ QWARN(QString("CMS not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate pubCert = QCA::Certificate::fromPEMFile("QcaTestClientCert.pem", 0, provider);
+ QCOMPARE(pubCert.isNull(), false);
+
+ QCA::SecureMessageKey secMsgKey;
+ QCA::CertificateChain chain;
+ chain += pubCert;
+ secMsgKey.setX509CertificateChain(chain);
+
+ QCA::CMS cms;
+ QCA::SecureMessage msg(&cms);
+ QCOMPARE(msg.canClearsign(), false);
+ QCOMPARE(msg.canSignAndEncrypt(), false);
+ QCOMPARE(msg.type(), QCA::SecureMessage::CMS);
+
+ msg.setRecipient(secMsgKey);
+
+ QFETCH(QByteArray, testText);
+
+ msg.startEncrypt();
+ msg.update(testText);
+ msg.end();
+
+ msg.waitForFinished(-1);
+
+ QByteArray encryptedResult1 = msg.read();
+ QCOMPARE(encryptedResult1.isEmpty(), false);
+
+ msg.reset();
+ msg.setRecipient(secMsgKey);
+ msg.startEncrypt();
+ msg.update(testText);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.success());
+
+ QByteArray encryptedResult2 = msg.read();
+ QCOMPARE(encryptedResult2.isEmpty(), false);
+
+ QCA::ConvertResult res;
+ QCA::SecureArray passPhrase = "start";
+ QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile("QcaTestClientKey.pem", passPhrase, &res);
+ QCOMPARE(res, QCA::ConvertGood);
+
+ secMsgKey.setX509PrivateKey(privKey);
+ QCA::SecureMessageKeyList privKeyList;
+ privKeyList += secMsgKey;
+ QCA::CMS cms2;
+ cms2.setPrivateKeys(privKeyList);
+
+ QCA::SecureMessage msg2(&cms2);
+
+ msg2.startDecrypt();
+ msg2.update(encryptedResult1);
+ msg2.end();
+ msg2.waitForFinished(-1);
+ QVERIFY(msg2.success());
+ QByteArray decryptedResult1 = msg2.read();
+ QCOMPARE(decryptedResult1, testText);
+
+ msg2.reset();
+ msg2.startDecrypt();
+ msg2.update(encryptedResult1);
+ msg2.end();
+ msg2.waitForFinished(-1);
+ QVERIFY(msg2.success());
+ QByteArray decryptedResult2 = msg2.read();
+
+ QCOMPARE(decryptedResult1, decryptedResult2);
+
+ QCOMPARE(msg2.canClearsign(), false);
+ QCOMPARE(msg2.canSignAndEncrypt(), false);
+ QCOMPARE(msg2.type(), QCA::SecureMessage::CMS);
+ }
}
}
void CMSut::signverify_data()
{
QTest::addColumn<QByteArray>("testText");
QTest::newRow("empty") << QByteArray("");
QTest::newRow("0") << QByteArray("0");
QTest::newRow("07") << QByteArray("07899847jkjjfasjaJKJLJkljklj&kjlj;/**-+.01");
QTest::newRow("dubious") << QByteArray("~!#**$#&&%^@#^&()");
}
// This one tests Detached format.
void CMSut::signverify()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate not supported for "+provider).toLocal8Bit() );
- else if( !QCA::isSupported( "cms", provider ) )
- QWARN( QString( "CMS not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult res;
- QCA::SecureArray passPhrase = "start";
- QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile( "QcaTestClientKey.pem", passPhrase, &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
-
- QCA::Certificate pubCert = QCA::Certificate::fromPEMFile( "QcaTestClientCert.pem", &res, provider);
- QCOMPARE( res, QCA::ConvertGood );
- QCOMPARE( pubCert.isNull(), false );
-
- QCA::CertificateChain chain;
- chain += pubCert;
- QCA::SecureMessageKey secMsgKey;
- secMsgKey.setX509CertificateChain( chain );
- secMsgKey.setX509PrivateKey( privKey );
-
- QCA::SecureMessageKeyList privKeyList;
- privKeyList += secMsgKey;
- QCA::CMS cms2;
- cms2.setPrivateKeys( privKeyList );
-
- QCA::SecureMessage msg2( &cms2 );
- msg2.setSigners( privKeyList );
- QCOMPARE( msg2.canClearsign(), false );
- QCOMPARE( msg2.canSignAndEncrypt(), false );
- QCOMPARE( msg2.type(), QCA::SecureMessage::CMS );
-
- QFETCH( QByteArray, testText );
-
- msg2.startSign(QCA::SecureMessage::Detached);
- msg2.update( testText );
- msg2.end();
- msg2.waitForFinished(-1);
- QVERIFY( msg2.success() );
- QByteArray signedResult1 = msg2.signature();
- QCOMPARE( signedResult1.isEmpty(), false );
-
- msg2.reset();
-
- msg2.setSigners( privKeyList );
- msg2.startSign(QCA::SecureMessage::Detached);
- msg2.update( testText );
- msg2.end();
- msg2.waitForFinished(-1);
- QVERIFY( msg2.success() );
- QByteArray signedResult2 = msg2.signature();
-
- QCOMPARE( signedResult2.isEmpty(), false );
-
- QCA::CMS cms;
- QCA::Certificate caCert = QCA::Certificate::fromPEMFile( "QcaTestRootCert.pem", &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
- QCA::CertificateCollection caCertCollection;
- caCertCollection.addCertificate(caCert);
-
- cms.setTrustedCertificates( caCertCollection );
- QCA::SecureMessage msg( &cms );
- QCOMPARE( msg.canClearsign(), false );
- QCOMPARE( msg.canSignAndEncrypt(), false );
- QCOMPARE( msg.type(), QCA::SecureMessage::CMS );
-
- msg.startVerify( signedResult1 );
- msg.update( testText );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QEXPECT_FAIL( "empty", "We don't seem to be able to verify signature of a zero length message", Continue);
- QVERIFY( msg.verifySuccess() );
-
- msg.reset();
-
- msg.startVerify( signedResult2);
- msg.update( testText );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QEXPECT_FAIL( "empty", "We don't seem to be able to verify signature of a zero length message", Continue);
- QVERIFY( msg.verifySuccess() );
-
- msg.reset();
-
- // This tests junk on the end of the signature - should fail
- msg.startVerify( signedResult2 + "junk");
- msg.update( testText );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QCOMPARE( msg.verifySuccess(), false );
-
- msg.reset();
-
- // This tests junk on the end of the message - should fail
- msg.startVerify( signedResult2 );
- msg.update( testText+"junk" );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QCOMPARE( msg.verifySuccess(), false );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate not supported for " + provider).toLocal8Bit());
+ } else if (!QCA::isSupported("cms", provider)) {
+ QWARN(QString("CMS not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult res;
+ QCA::SecureArray passPhrase = "start";
+ QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile("QcaTestClientKey.pem", passPhrase, &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+
+ QCA::Certificate pubCert = QCA::Certificate::fromPEMFile("QcaTestClientCert.pem", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+ QCOMPARE(pubCert.isNull(), false);
+
+ QCA::CertificateChain chain;
+ chain += pubCert;
+ QCA::SecureMessageKey secMsgKey;
+ secMsgKey.setX509CertificateChain(chain);
+ secMsgKey.setX509PrivateKey(privKey);
+
+ QCA::SecureMessageKeyList privKeyList;
+ privKeyList += secMsgKey;
+ QCA::CMS cms2;
+ cms2.setPrivateKeys(privKeyList);
+
+ QCA::SecureMessage msg2(&cms2);
+ msg2.setSigners(privKeyList);
+ QCOMPARE(msg2.canClearsign(), false);
+ QCOMPARE(msg2.canSignAndEncrypt(), false);
+ QCOMPARE(msg2.type(), QCA::SecureMessage::CMS);
+
+ QFETCH(QByteArray, testText);
+
+ msg2.startSign(QCA::SecureMessage::Detached);
+ msg2.update(testText);
+ msg2.end();
+ msg2.waitForFinished(-1);
+ QVERIFY(msg2.success());
+ QByteArray signedResult1 = msg2.signature();
+ QCOMPARE(signedResult1.isEmpty(), false);
+
+ msg2.reset();
+
+ msg2.setSigners(privKeyList);
+ msg2.startSign(QCA::SecureMessage::Detached);
+ msg2.update(testText);
+ msg2.end();
+ msg2.waitForFinished(-1);
+ QVERIFY(msg2.success());
+ QByteArray signedResult2 = msg2.signature();
+
+ QCOMPARE(signedResult2.isEmpty(), false);
+
+ QCA::CMS cms;
+ QCA::Certificate caCert = QCA::Certificate::fromPEMFile("QcaTestRootCert.pem", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+ QCA::CertificateCollection caCertCollection;
+ caCertCollection.addCertificate(caCert);
+
+ cms.setTrustedCertificates(caCertCollection);
+ QCA::SecureMessage msg(&cms);
+ QCOMPARE(msg.canClearsign(), false);
+ QCOMPARE(msg.canSignAndEncrypt(), false);
+ QCOMPARE(msg.type(), QCA::SecureMessage::CMS);
+
+ msg.startVerify(signedResult1);
+ msg.update(testText);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QEXPECT_FAIL("empty", "We don't seem to be able to verify signature of a zero length message", Continue);
+ QVERIFY(msg.verifySuccess());
+
+ msg.reset();
+
+ msg.startVerify(signedResult2);
+ msg.update(testText);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QEXPECT_FAIL("empty", "We don't seem to be able to verify signature of a zero length message", Continue);
+ QVERIFY(msg.verifySuccess());
+
+ msg.reset();
+
+ // This tests junk on the end of the signature - should fail
+ msg.startVerify(signedResult2 + "junk");
+ msg.update(testText);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QCOMPARE(msg.verifySuccess(), false);
+
+ msg.reset();
+
+ // This tests junk on the end of the message - should fail
+ msg.startVerify(signedResult2);
+ msg.update(testText + "junk");
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QCOMPARE(msg.verifySuccess(), false);
+ }
}
}
-
void CMSut::signverify_message_data()
{
QTest::addColumn<QByteArray>("testText");
QTest::newRow("empty") << QByteArray("");
QTest::newRow("0") << QByteArray("0");
QTest::newRow("07") << QByteArray("07899847jkjjfasjaJKJLJkljklj&kjlj;/**-+.01");
QTest::newRow("dubious") << QByteArray("~!#**$#&&%^@#^&()");
}
// This one tests Message format
void CMSut::signverify_message()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate not supported for "+provider).toLocal8Bit() );
- else if( !QCA::isSupported( "cms", provider ) )
- QWARN( QString( "CMS not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult res;
- QCA::SecureArray passPhrase = "start";
- QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile( "QcaTestClientKey.pem", passPhrase, &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
-
- QCA::Certificate pubCert = QCA::Certificate::fromPEMFile( "QcaTestClientCert.pem", &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
- QCOMPARE( pubCert.isNull(), false );
-
- QCA::CertificateChain chain;
- chain += pubCert;
- QCA::SecureMessageKey secMsgKey;
- secMsgKey.setX509CertificateChain( chain );
- secMsgKey.setX509PrivateKey( privKey );
-
- QCA::SecureMessageKeyList privKeyList;
- privKeyList += secMsgKey;
- QCA::CMS cms2;
- cms2.setPrivateKeys( privKeyList );
-
- QCA::SecureMessage msg2( &cms2 );
- msg2.setSigners( privKeyList );
- QCOMPARE( msg2.canClearsign(), false );
- QCOMPARE( msg2.canSignAndEncrypt(), false );
- QCOMPARE( msg2.type(), QCA::SecureMessage::CMS );
-
- QFETCH( QByteArray, testText );
-
- msg2.startSign( QCA::SecureMessage::Message );
- msg2.update( testText );
- msg2.end();
- msg2.waitForFinished(-1);
- QVERIFY( msg2.success() );
- QByteArray signedResult1 = msg2.read();
- QCOMPARE( signedResult1.isEmpty(), false );
-
- msg2.reset();
-
- msg2.setSigners( privKeyList );
- msg2.startSign(QCA::SecureMessage::Message);
- msg2.update( testText );
- msg2.end();
- msg2.waitForFinished(-1);
- QVERIFY( msg2.success() );
- QByteArray signedResult2 = msg2.read();
-
- QCOMPARE( signedResult2.isEmpty(), false );
-
- QCA::CMS cms;
- QCA::Certificate caCert = QCA::Certificate::fromPEMFile( "QcaTestRootCert.pem", &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
-
- QCA::CertificateCollection caCertCollection;
- caCertCollection.addCertificate(caCert);
-
- cms.setTrustedCertificates( caCertCollection );
- QCA::SecureMessage msg( &cms );
- QCOMPARE( msg.canClearsign(), false );
- QCOMPARE( msg.canSignAndEncrypt(), false );
- QCOMPARE( msg.type(), QCA::SecureMessage::CMS );
-
- msg.startVerify( );
- msg.update( signedResult1 );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QVERIFY( msg.verifySuccess() );
-
- msg.reset();
-
- msg.startVerify( );
- msg.update( signedResult2 );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QVERIFY( msg.verifySuccess() );
-
- msg.reset();
-
- msg.startVerify( );
- msg.update( signedResult2 );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QCOMPARE( msg.verifySuccess(), true );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate not supported for " + provider).toLocal8Bit());
+ } else if (!QCA::isSupported("cms", provider)) {
+ QWARN(QString("CMS not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult res;
+ QCA::SecureArray passPhrase = "start";
+ QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile("QcaTestClientKey.pem", passPhrase, &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+
+ QCA::Certificate pubCert = QCA::Certificate::fromPEMFile("QcaTestClientCert.pem", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+ QCOMPARE(pubCert.isNull(), false);
+
+ QCA::CertificateChain chain;
+ chain += pubCert;
+ QCA::SecureMessageKey secMsgKey;
+ secMsgKey.setX509CertificateChain(chain);
+ secMsgKey.setX509PrivateKey(privKey);
+
+ QCA::SecureMessageKeyList privKeyList;
+ privKeyList += secMsgKey;
+ QCA::CMS cms2;
+ cms2.setPrivateKeys(privKeyList);
+
+ QCA::SecureMessage msg2(&cms2);
+ msg2.setSigners(privKeyList);
+ QCOMPARE(msg2.canClearsign(), false);
+ QCOMPARE(msg2.canSignAndEncrypt(), false);
+ QCOMPARE(msg2.type(), QCA::SecureMessage::CMS);
+
+ QFETCH(QByteArray, testText);
+
+ msg2.startSign(QCA::SecureMessage::Message);
+ msg2.update(testText);
+ msg2.end();
+ msg2.waitForFinished(-1);
+ QVERIFY(msg2.success());
+ QByteArray signedResult1 = msg2.read();
+ QCOMPARE(signedResult1.isEmpty(), false);
+
+ msg2.reset();
+
+ msg2.setSigners(privKeyList);
+ msg2.startSign(QCA::SecureMessage::Message);
+ msg2.update(testText);
+ msg2.end();
+ msg2.waitForFinished(-1);
+ QVERIFY(msg2.success());
+ QByteArray signedResult2 = msg2.read();
+
+ QCOMPARE(signedResult2.isEmpty(), false);
+
+ QCA::CMS cms;
+ QCA::Certificate caCert = QCA::Certificate::fromPEMFile("QcaTestRootCert.pem", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+
+ QCA::CertificateCollection caCertCollection;
+ caCertCollection.addCertificate(caCert);
+
+ cms.setTrustedCertificates(caCertCollection);
+ QCA::SecureMessage msg(&cms);
+ QCOMPARE(msg.canClearsign(), false);
+ QCOMPARE(msg.canSignAndEncrypt(), false);
+ QCOMPARE(msg.type(), QCA::SecureMessage::CMS);
+
+ msg.startVerify();
+ msg.update(signedResult1);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QVERIFY(msg.verifySuccess());
+
+ msg.reset();
+
+ msg.startVerify();
+ msg.update(signedResult2);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QVERIFY(msg.verifySuccess());
+
+ msg.reset();
+
+ msg.startVerify();
+ msg.update(signedResult2);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QCOMPARE(msg.verifySuccess(), true);
+ }
}
}
void CMSut::signverify_message_invalid_data()
{
QTest::addColumn<QByteArray>("testText");
QTest::newRow("empty") << QByteArray("");
QTest::newRow("0") << QByteArray("0");
QTest::newRow("07") << QByteArray("07899847jkjjfasjaJKJLJkljklj&kjlj;/**-+.01");
QTest::newRow("dubious") << QByteArray("~!#**$#&&%^@#^&()");
}
-
// This one tests Message format
void CMSut::signverify_message_invalid()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate not supported for "+provider).toLocal8Bit() );
- else if( !QCA::isSupported( "cms", provider ) )
- QWARN( QString( "CMS not supported for "+provider).toLocal8Bit() );
- else {
- QCA::ConvertResult res;
- QCA::SecureArray passPhrase = "start";
- QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile( "QcaTestClientKey.pem", passPhrase, &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
-
- QCA::Certificate pubCert = QCA::Certificate::fromPEMFile( "QcaTestClientCert.pem", &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
- QCOMPARE( pubCert.isNull(), false );
-
- QCA::CertificateChain chain;
- chain += pubCert;
- QCA::SecureMessageKey secMsgKey;
- secMsgKey.setX509CertificateChain( chain );
- secMsgKey.setX509PrivateKey( privKey );
-
- QCA::SecureMessageKeyList privKeyList;
- privKeyList += secMsgKey;
- QCA::CMS cms2;
- cms2.setPrivateKeys( privKeyList );
-
- QCA::SecureMessage msg2( &cms2 );
- msg2.setSigners( privKeyList );
- QCOMPARE( msg2.canClearsign(), false );
- QCOMPARE( msg2.canSignAndEncrypt(), false );
- QCOMPARE( msg2.type(), QCA::SecureMessage::CMS );
-
- QFETCH( QByteArray, testText );
-
- msg2.startSign( QCA::SecureMessage::Message );
- msg2.update( testText );
- msg2.end();
- msg2.waitForFinished(-1);
- QVERIFY( msg2.success() );
- QByteArray signedResult1 = msg2.read();
- QCOMPARE( signedResult1.isEmpty(), false );
-
- QCA::CMS cms;
- QCA::Certificate caCert = QCA::Certificate::fromPEMFile( "QcaTestRootCert.pem", &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
-
- QCA::CertificateCollection caCertCollection;
- caCertCollection.addCertificate(caCert);
-
- cms.setTrustedCertificates( caCertCollection );
- QCA::SecureMessage msg( &cms );
- QCOMPARE( msg.canClearsign(), false );
- QCOMPARE( msg.canSignAndEncrypt(), false );
- QCOMPARE( msg.type(), QCA::SecureMessage::CMS );
-
- // This is just to break things
- // signedResult1[30] = signedResult1[30] + 1;
- signedResult1[signedResult1.size()-2] = 0x00;
-
- msg.startVerify( );
- msg.update( signedResult1 );
- msg.end();
-
- msg.waitForFinished(-1);
- QVERIFY( msg.wasSigned() );
- QVERIFY( msg.success() );
- QCOMPARE( msg.verifySuccess(), false );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate not supported for " + provider).toLocal8Bit());
+ } else if (!QCA::isSupported("cms", provider)) {
+ QWARN(QString("CMS not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::ConvertResult res;
+ QCA::SecureArray passPhrase = "start";
+ QCA::PrivateKey privKey = QCA::PrivateKey::fromPEMFile("QcaTestClientKey.pem", passPhrase, &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+
+ QCA::Certificate pubCert = QCA::Certificate::fromPEMFile("QcaTestClientCert.pem", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+ QCOMPARE(pubCert.isNull(), false);
+
+ QCA::CertificateChain chain;
+ chain += pubCert;
+ QCA::SecureMessageKey secMsgKey;
+ secMsgKey.setX509CertificateChain(chain);
+ secMsgKey.setX509PrivateKey(privKey);
+
+ QCA::SecureMessageKeyList privKeyList;
+ privKeyList += secMsgKey;
+ QCA::CMS cms2;
+ cms2.setPrivateKeys(privKeyList);
+
+ QCA::SecureMessage msg2(&cms2);
+ msg2.setSigners(privKeyList);
+ QCOMPARE(msg2.canClearsign(), false);
+ QCOMPARE(msg2.canSignAndEncrypt(), false);
+ QCOMPARE(msg2.type(), QCA::SecureMessage::CMS);
+
+ QFETCH(QByteArray, testText);
+
+ msg2.startSign(QCA::SecureMessage::Message);
+ msg2.update(testText);
+ msg2.end();
+ msg2.waitForFinished(-1);
+ QVERIFY(msg2.success());
+ QByteArray signedResult1 = msg2.read();
+ QCOMPARE(signedResult1.isEmpty(), false);
+
+ QCA::CMS cms;
+ QCA::Certificate caCert = QCA::Certificate::fromPEMFile("QcaTestRootCert.pem", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+
+ QCA::CertificateCollection caCertCollection;
+ caCertCollection.addCertificate(caCert);
+
+ cms.setTrustedCertificates(caCertCollection);
+ QCA::SecureMessage msg(&cms);
+ QCOMPARE(msg.canClearsign(), false);
+ QCOMPARE(msg.canSignAndEncrypt(), false);
+ QCOMPARE(msg.type(), QCA::SecureMessage::CMS);
+
+ // This is just to break things
+ // signedResult1[30] = signedResult1[30] + 1;
+ signedResult1[signedResult1.size() - 2] = 0x00;
+
+ msg.startVerify();
+ msg.update(signedResult1);
+ msg.end();
+
+ msg.waitForFinished(-1);
+ QVERIFY(msg.wasSigned());
+ QVERIFY(msg.success());
+ QCOMPARE(msg.verifySuccess(), false);
+ }
}
}
-
QTEST_MAIN(CMSut)
#include "cms.moc"
diff --git a/unittest/dsaunittest/dsaunittest.cpp b/unittest/dsaunittest/dsaunittest.cpp
index b5965076..c64ae9ea 100644
--- a/unittest/dsaunittest/dsaunittest.cpp
+++ b/unittest/dsaunittest/dsaunittest.cpp
@@ -1,130 +1,128 @@
/**
* Copyright (C) 2005, 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class DSAUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testdsa();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void DSAUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void DSAUnitTest::cleanupTestCase()
{
delete m_init;
}
void DSAUnitTest::testdsa()
{
- if(!QCA::isSupported("pkey") ||
- !QCA::PKey::supportedTypes().contains(QCA::PKey::DSA) ||
- !QCA::PKey::supportedIOTypes().contains(QCA::PKey::DSA))
- {
+ if (!QCA::isSupported("pkey") ||
+ !QCA::PKey::supportedTypes().contains(QCA::PKey::DSA) ||
+ !QCA::PKey::supportedIOTypes().contains(QCA::PKey::DSA)) {
#if QT_VERSION >= 0x050000
- QSKIP("DSA not supported!");
+ QSKIP("DSA not supported!");
#else
- QSKIP("DSA not supported!", SkipAll);
+ QSKIP("DSA not supported!", SkipAll);
#endif
- }
+ }
- if (!QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_1024))
- {
+ if (!QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_1024)) {
#if QT_VERSION >= 0x050000
- QSKIP("DSA_1024 discrete logarithm group sets not supported!");
+ QSKIP("DSA_1024 discrete logarithm group sets not supported!");
#else
- QSKIP("DSA_1024 discrete logarithm group sets not supported!", SkipAll);
+ QSKIP("DSA_1024 discrete logarithm group sets not supported!", SkipAll);
#endif
- }
-
- QCA::KeyGenerator keygen;
- QCOMPARE( keygen.isBusy(), false );
- QCOMPARE( keygen.blockingEnabled(), true );
- QCA::DLGroup group = keygen.createDLGroup(QCA::DSA_1024);
- QCOMPARE( group.isNull(), false );
-
- QCA::PrivateKey dsaKey = keygen.createDSA( group );
- QCOMPARE( dsaKey.isNull(), false );
- QCOMPARE( dsaKey.isRSA(), false );
- QCOMPARE( dsaKey.isDSA(), true );
- QCOMPARE( dsaKey.isDH(), false );
- QCOMPARE( dsaKey.isPrivate(), true );
- QCOMPARE( dsaKey.isPublic(), false );
- QCOMPARE( dsaKey.canSign(), true );
- QCOMPARE( dsaKey.canDecrypt(), false );
-
- QCOMPARE( dsaKey.bitSize(), 1024 );
- QCA::DSAPrivateKey dsaPrivKey = dsaKey.toDSA();
- QCOMPARE( dsaPrivKey.bitSize(), 1024 );
-
- QCA::SecureArray dsaDER = dsaKey.toDER();
- QCOMPARE( dsaDER.isEmpty(), false );
-
- QString dsaPEM = dsaKey.toPEM();
- QCOMPARE( dsaPEM.isEmpty(), false );
-
- QCA::ConvertResult checkResult;
- QCA::PrivateKey fromPEMkey = QCA::PrivateKey::fromPEM(dsaPEM, QCA::SecureArray(), &checkResult);
- QCOMPARE( checkResult, QCA::ConvertGood );
- QCOMPARE( fromPEMkey.isNull(), false );
- QCOMPARE( fromPEMkey.isRSA(), false );
- QCOMPARE( fromPEMkey.isDSA(), true );
- QCOMPARE( fromPEMkey.isDH(), false );
- QCOMPARE( fromPEMkey.isPrivate(), true );
- QCOMPARE( fromPEMkey.isPublic(), false );
- QVERIFY( dsaKey == fromPEMkey );
-
- QCA::PrivateKey fromDERkey = QCA::PrivateKey::fromDER(dsaDER, QCA::SecureArray(), &checkResult);
- QCOMPARE( checkResult, QCA::ConvertGood );
- QCOMPARE( fromDERkey.isNull(), false );
- QCOMPARE( fromDERkey.isRSA(), false );
- QCOMPARE( fromDERkey.isDSA(), true );
- QCOMPARE( fromDERkey.isDH(), false );
- QCOMPARE( fromDERkey.isPrivate(), true );
- QCOMPARE( fromDERkey.isPublic(), false );
- QVERIFY( dsaKey == fromDERkey );
+ }
+
+ QCA::KeyGenerator keygen;
+ QCOMPARE(keygen.isBusy(), false);
+ QCOMPARE(keygen.blockingEnabled(), true);
+ QCA::DLGroup group = keygen.createDLGroup(QCA::DSA_1024);
+ QCOMPARE(group.isNull(), false);
+
+ QCA::PrivateKey dsaKey = keygen.createDSA(group);
+ QCOMPARE(dsaKey.isNull(), false);
+ QCOMPARE(dsaKey.isRSA(), false);
+ QCOMPARE(dsaKey.isDSA(), true);
+ QCOMPARE(dsaKey.isDH(), false);
+ QCOMPARE(dsaKey.isPrivate(), true);
+ QCOMPARE(dsaKey.isPublic(), false);
+ QCOMPARE(dsaKey.canSign(), true);
+ QCOMPARE(dsaKey.canDecrypt(), false);
+
+ QCOMPARE(dsaKey.bitSize(), 1024);
+ QCA::DSAPrivateKey dsaPrivKey = dsaKey.toDSA();
+ QCOMPARE(dsaPrivKey.bitSize(), 1024);
+
+ QCA::SecureArray dsaDER = dsaKey.toDER();
+ QCOMPARE(dsaDER.isEmpty(), false);
+
+ QString dsaPEM = dsaKey.toPEM();
+ QCOMPARE(dsaPEM.isEmpty(), false);
+
+ QCA::ConvertResult checkResult;
+ QCA::PrivateKey fromPEMkey = QCA::PrivateKey::fromPEM(dsaPEM, QCA::SecureArray(), &checkResult);
+ QCOMPARE(checkResult, QCA::ConvertGood);
+ QCOMPARE(fromPEMkey.isNull(), false);
+ QCOMPARE(fromPEMkey.isRSA(), false);
+ QCOMPARE(fromPEMkey.isDSA(), true);
+ QCOMPARE(fromPEMkey.isDH(), false);
+ QCOMPARE(fromPEMkey.isPrivate(), true);
+ QCOMPARE(fromPEMkey.isPublic(), false);
+ QVERIFY(dsaKey == fromPEMkey);
+
+ QCA::PrivateKey fromDERkey = QCA::PrivateKey::fromDER(dsaDER, QCA::SecureArray(), &checkResult);
+ QCOMPARE(checkResult, QCA::ConvertGood);
+ QCOMPARE(fromDERkey.isNull(), false);
+ QCOMPARE(fromDERkey.isRSA(), false);
+ QCOMPARE(fromDERkey.isDSA(), true);
+ QCOMPARE(fromDERkey.isDH(), false);
+ QCOMPARE(fromDERkey.isPrivate(), true);
+ QCOMPARE(fromDERkey.isPublic(), false);
+ QVERIFY(dsaKey == fromDERkey);
}
QTEST_MAIN(DSAUnitTest)
#include "dsaunittest.moc"
diff --git a/unittest/filewatchunittest/filewatchunittest.cpp b/unittest/filewatchunittest/filewatchunittest.cpp
index abbdfd2f..58366208 100644
--- a/unittest/filewatchunittest/filewatchunittest.cpp
+++ b/unittest/filewatchunittest/filewatchunittest.cpp
@@ -1,97 +1,97 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "filewatchunittest.h"
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
void FileWatchUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void FileWatchUnitTest::cleanupTestCase()
{
delete m_init;
}
void FileWatchUnitTest::filewatchTest()
{
QWARN("Unittest will take about 1 minute. Please wait.");
QCA::FileWatch watcher;
- QCOMPARE( watcher.fileName(), QString() );
+ QCOMPARE(watcher.fileName(), QString());
- QSignalSpy spy( &watcher, SIGNAL(changed()) );
- QVERIFY( spy.isValid() );
- QCOMPARE( spy.count(), 0 );
+ QSignalSpy spy(&watcher, SIGNAL(changed()));
+ QVERIFY(spy.isValid());
+ QCOMPARE(spy.count(), 0);
QTemporaryFile *tempFile = new QTemporaryFile;
tempFile->open();
- watcher.setFileName( tempFile->fileName() );
- QCOMPARE( watcher.fileName(), tempFile->fileName() );
+ watcher.setFileName(tempFile->fileName());
+ QCOMPARE(watcher.fileName(), tempFile->fileName());
QTest::qWait(7000);
- QCOMPARE( spy.count(), 0 );
+ QCOMPARE(spy.count(), 0);
tempFile->close();
QTest::qWait(7000);
- QCOMPARE( spy.count(), 0 );
+ QCOMPARE(spy.count(), 0);
tempFile->open();
tempFile->write("foo");
tempFile->flush();
QTest::qWait(7000);
- QCOMPARE( spy.count(), 1 );
+ QCOMPARE(spy.count(), 1);
tempFile->close();
QTest::qWait(7000);
- QCOMPARE( spy.count(), 1 );
+ QCOMPARE(spy.count(), 1);
tempFile->open();
tempFile->write("foo");
tempFile->flush();
QTest::qWait(7000);
- QCOMPARE( spy.count(), 2 );
+ QCOMPARE(spy.count(), 2);
tempFile->write("bar");
tempFile->flush();
QTest::qWait(7000);
- QCOMPARE( spy.count(), 3 );
+ QCOMPARE(spy.count(), 3);
tempFile->close();
QTest::qWait(7000);
- QCOMPARE( spy.count(), 3 );
+ QCOMPARE(spy.count(), 3);
delete tempFile;
QTest::qWait(7000);
- QCOMPARE( spy.count(), 4 );
-
+ QCOMPARE(spy.count(), 4);
+
}
QTEST_MAIN(FileWatchUnitTest)
diff --git a/unittest/filewatchunittest/filewatchunittest.h b/unittest/filewatchunittest/filewatchunittest.h
index d2e622a3..87ba179a 100644
--- a/unittest/filewatchunittest/filewatchunittest.h
+++ b/unittest/filewatchunittest/filewatchunittest.h
@@ -1,43 +1,43 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef FILEWATCHUNITTEST_H
#define FILEWATCHUNITTEST_H
#include <QtCrypto>
#include <QtTest/QtTest>
class FileWatchUnitTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void filewatchTest();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
#endif
diff --git a/unittest/hashunittest/hashunittest.cpp b/unittest/hashunittest/hashunittest.cpp
index 0dd5330e..3c77b101 100644
--- a/unittest/hashunittest/hashunittest.cpp
+++ b/unittest/hashunittest/hashunittest.cpp
@@ -1,895 +1,899 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#include <QFile>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class HashUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void md2test_data();
void md2test();
void md4test_data();
void md4test();
void md5test_data();
void md5test();
void md5filetest();
void sha0test_data();
void sha0test();
void sha0longtest();
void sha1test_data();
void sha1test();
void sha1longtest();
void sha224test_data();
void sha224test();
void sha224longtest();
void sha256test_data();
void sha256test();
void sha256longtest();
void sha384test_data();
void sha384test();
void sha384longtest();
void sha512test_data();
void sha512test();
void sha512longtest();
void rmd160test_data();
void rmd160test();
void rmd160longtest();
void whirlpooltest_data();
void whirlpooltest();
void whirlpoollongtest();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void HashUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void HashUnitTest::cleanupTestCase()
{
QCA::unloadAllPlugins();
delete m_init;
}
void HashUnitTest::md2test_data()
{
// These are as specified in RFC 1319
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
QTest::newRow("md2()") << QByteArray("") << QString("8350e5a3e24c153df2275c9f80692773");
QTest::newRow("md2(a)") << QByteArray("a") << QString("32ec01ec4a6dac72c0ab96fb34c0b5d1");
QTest::newRow("md2(abc)") << QByteArray("abc")
- << QString("da853b0d3f88d99b30283a69e6ded6bb");
+ << QString("da853b0d3f88d99b30283a69e6ded6bb");
QTest::newRow("md2(messageDigest)") << QByteArray("message digest")
- << QString("ab4f496bfb2a530b219ff33031fe06b0");
+ << QString("ab4f496bfb2a530b219ff33031fe06b0");
QTest::newRow("md2([a-z])") << QByteArray("abcdefghijklmnopqrstuvwxyz")
- << QString("4e8ddff3650292ab5a4108c3aa47940b");
+ << QString("4e8ddff3650292ab5a4108c3aa47940b");
QTest::newRow("md2([A-z,0-9])") << QByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
- << QString("da33def2a42df13975352846c30338cd");
+ << QString("da33def2a42df13975352846c30338cd");
QTest::newRow("md2(nums)") << QByteArray("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
- << QString("d5976f79d83d3a0dc9806c3c66f3efd8");
+ << QString("d5976f79d83d3a0dc9806c3c66f3efd8");
}
void HashUnitTest::md2test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// no MD2 support for libgcrypt...
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("md2", provider))
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("md2", provider))
#if QT_VERSION >= 0x050000
- QSKIP(QString("MD2 not supported for "+provider).toLocal8Bit());
+ QSKIP(QString("MD2 not supported for " + provider).toLocal8Bit());
#else
- QSKIP(QString("MD2 not supported for "+provider).toLocal8Bit(), SkipSingle);
+ QSKIP(QString("MD2 not supported for " + provider).toLocal8Bit(), SkipSingle);
#endif
- QString hashResult = QCA::Hash("md2", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
+ QString hashResult = QCA::Hash("md2", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
}
}
void HashUnitTest::md4test_data()
{
// These are as specified in RFC 1320
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
QTest::newRow("md4()") << QByteArray("") << QString("31d6cfe0d16ae931b73c59d7e0c089c0");
QTest::newRow("md4(a)") << QByteArray("a") << QString("bde52cb31de33e46245e05fbdbd6fb24");
QTest::newRow("md4(abc)") << QByteArray("abc")
- << QString("a448017aaf21d8525fc10ae87aa6729d");
+ << QString("a448017aaf21d8525fc10ae87aa6729d");
QTest::newRow("md4(messageDigest)") << QByteArray("message digest")
- << QString("d9130a8164549fe818874806e1c7014b");
+ << QString("d9130a8164549fe818874806e1c7014b");
QTest::newRow("md4([a-z])") << QByteArray("abcdefghijklmnopqrstuvwxyz")
- << QString("d79e1c308aa5bbcdeea8ed63df412da9");
+ << QString("d79e1c308aa5bbcdeea8ed63df412da9");
QTest::newRow("md4([A-z,0-9])") << QByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
- << QString("043f8582f241db351ce627e153e7f0e4");
+ << QString("043f8582f241db351ce627e153e7f0e4");
QTest::newRow("md4(nums)") << QByteArray("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
- << QString("e33b4ddc9c38f2199c3e7b164fcc0536");
+ << QString("e33b4ddc9c38f2199c3e7b164fcc0536");
}
-
void HashUnitTest::md4test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
// No MD4 support for NSS?
// providersToTest.append("qca-nss");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("md4", provider))
- QWARN(QString("MD4 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("md4", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("md4", provider)) {
+ QWARN(QString("MD4 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("md4", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::md5test_data()
{
// These are as specified in RFC 1321
// They also match Australian Standard (AS) 2805.1.3.2-2000 Appendix A
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
QTest::newRow("md5()") << QByteArray("") << QString("d41d8cd98f00b204e9800998ecf8427e");
QTest::newRow("md5(a)") << QByteArray("a") << QString("0cc175b9c0f1b6a831c399e269772661");
QTest::newRow("md5(abc)") << QByteArray("abc")
- << QString("900150983cd24fb0d6963f7d28e17f72");
+ << QString("900150983cd24fb0d6963f7d28e17f72");
QTest::newRow("md5(messageDigest)") << QByteArray("message digest")
- << QString("f96b697d7cb7938d525a2f31aaf161d0");
+ << QString("f96b697d7cb7938d525a2f31aaf161d0");
QTest::newRow("md5([a-z])") << QByteArray("abcdefghijklmnopqrstuvwxyz")
- << QString("c3fcd3d76192e4007dfb496cca67e13b");
+ << QString("c3fcd3d76192e4007dfb496cca67e13b");
QTest::newRow("md5([A-z,0-9])") << QByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
- << QString("d174ab98d277d9f5a5611c2c9f419d9f");
+ << QString("d174ab98d277d9f5a5611c2c9f419d9f");
QTest::newRow("md5(nums)") << QByteArray("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
- << QString("57edf4a22be3c955ac49da2e2107b67a");
+ << QString("57edf4a22be3c955ac49da2e2107b67a");
}
void HashUnitTest::md5test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
providersToTest.append("default");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("md5", provider))
- QWARN(QString("MD5 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("md5", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("md5", provider)) {
+ QWARN(QString("MD5 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("md5", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
-
void HashUnitTest::md5filetest()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
providersToTest.append("default");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("md5", provider))
- QWARN(QString("MD5 not supported for "+provider).toLocal8Bit());
- else {
- QFile f1( "./data/empty" );
- if ( f1.open( QIODevice::ReadOnly ) ) {
- QCA::Hash hashObj("md5", provider);
- hashObj.update( &f1 );
- QCOMPARE( QString( QCA::arrayToHex( hashObj.final().toByteArray() ) ),
- QString( "d41d8cd98f00b204e9800998ecf8427e" ) );
- } else {
- QWARN( "./data/empty could not be opened - do you need to create it?");
- }
-
- QFile f2( "./data/twobytes" );
- if ( f2.open( QIODevice::ReadOnly ) ) {
- QCA::Hash hashObj("md5", provider);
- hashObj.update( &f2 );
- QCOMPARE( QString( QCA::arrayToHex( hashObj.final().toByteArray() ) ),
- QString( "5fc9808ed18e442ab4164c59f151e757" ) );
- } else {
- QWARN( "./data/twobytes could not be opened - do you need to download it?");
- }
-
-
- QFile f3( "./data/twohundredbytes" );
- if ( f3.open( QIODevice::ReadOnly ) ) {
- QCA::Hash hashObj("md5", provider);
- hashObj.update( &f3 );
- QCOMPARE( QString( QCA::arrayToHex( hashObj.final().toByteArray() ) ),
- QString( "b91c1f114d942520ecdf7e84e580cda3" ) );
- } else {
- QWARN( "./data/twohundredbytes could not be opened - do you need to download it?");
- }
-
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("md5", provider)) {
+ QWARN(QString("MD5 not supported for " + provider).toLocal8Bit());
+ } else {
+ QFile f1("./data/empty");
+ if (f1.open(QIODevice::ReadOnly)) {
+ QCA::Hash hashObj("md5", provider);
+ hashObj.update(&f1);
+ QCOMPARE(QString(QCA::arrayToHex(hashObj.final().toByteArray())),
+ QString("d41d8cd98f00b204e9800998ecf8427e"));
+ } else {
+ QWARN("./data/empty could not be opened - do you need to create it?");
+ }
+
+ QFile f2("./data/twobytes");
+ if (f2.open(QIODevice::ReadOnly)) {
+ QCA::Hash hashObj("md5", provider);
+ hashObj.update(&f2);
+ QCOMPARE(QString(QCA::arrayToHex(hashObj.final().toByteArray())),
+ QString("5fc9808ed18e442ab4164c59f151e757"));
+ } else {
+ QWARN("./data/twobytes could not be opened - do you need to download it?");
+ }
+
+ QFile f3("./data/twohundredbytes");
+ if (f3.open(QIODevice::ReadOnly)) {
+ QCA::Hash hashObj("md5", provider);
+ hashObj.update(&f3);
+ QCOMPARE(QString(QCA::arrayToHex(hashObj.final().toByteArray())),
+ QString("b91c1f114d942520ecdf7e84e580cda3"));
+ } else {
+ QWARN("./data/twohundredbytes could not be opened - do you need to download it?");
+ }
+
+ }
}
}
void HashUnitTest::sha0test_data()
{
// These are extracted from OpenOffice.org 1.1.2, in sal/workben/t_digest.c
// Check FIPS 180-1?
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
QTest::newRow("sha0(abc)") << QByteArray("abc") << QString("0164b8a914cd2a5e74c4f7ff082c4d97f1edf880");
QTest::newRow("sha0(abc)") << QByteArray("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
- << QString("d2516ee1acfa5baf33dfc1c471e438449ef134c8");
+ << QString("d2516ee1acfa5baf33dfc1c471e438449ef134c8");
}
void HashUnitTest::sha0test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// No SHA0 for botan, gcrypt or nss
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha0", provider))
- QWARN(QString("SHA0 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("sha0", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha0", provider)) {
+ QWARN(QString("SHA0 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("sha0", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::sha0longtest()
{
QByteArray fillerString;
fillerString.fill('a', 1000);
// This test extracted from OpenOffice.org 1.1.2, in sal/workben/t_digest.c
QStringList providersToTest;
providersToTest.append("qca-ossl");
// No SHA0 for botan, gcrypt or nss
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha0", provider))
- QWARN(QString("SHA0 not supported for "+provider).toLocal8Bit());
- else {
- QCA::Hash shaHash("sha0", provider);
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("3232affa48628a26653b5aaa44541fd90d690603" ) );
-
- shaHash.clear();
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("3232affa48628a26653b5aaa44541fd90d690603" ) );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha0", provider)) {
+ QWARN(QString("SHA0 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Hash shaHash("sha0", provider);
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("3232affa48628a26653b5aaa44541fd90d690603"));
+
+ shaHash.clear();
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("3232affa48628a26653b5aaa44541fd90d690603"));
+ }
}
}
void HashUnitTest::sha1test_data()
{
// These are as specified in FIPS 180-2. Matches RFC3174
// Some additions from Australian Standard (AS) 2805.13.3-2000
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
// FIPS 180-2, Appendix A.1
QTest::newRow("sha1(abc)") << QByteArray("abc") << QString("a9993e364706816aba3e25717850c26c9cd0d89d");
// FIPS 180-2, Appendix A.2
QTest::newRow("sha1(a-q)") << QByteArray("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
- << QString("84983e441c3bd26ebaae4aa1f95129e5e54670f1");
+ << QString("84983e441c3bd26ebaae4aa1f95129e5e54670f1");
// AS 2805.13.3-200 Appendix A
// also has some duplicates from FIPS 180-2
QTest::newRow("sha1()") << QByteArray("") << QString("da39a3ee5e6b4b0d3255bfef95601890afd80709");
QTest::newRow("sha1(a)") << QByteArray("a") << QString("86f7e437faa5a7fce15d1ddcb9eaeaea377667b8");
QTest::newRow("sha1(a-z)") << QByteArray("abcdefghijklmnopqrstuvwxyz")
- << QString("32d10c7b8cf96570ca04ce37f2a19d84240d3a89");
+ << QString("32d10c7b8cf96570ca04ce37f2a19d84240d3a89");
}
void HashUnitTest::sha1test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-botan");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
providersToTest.append("default");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha1", provider))
- QWARN(QString("SHA1 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("sha1", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha1", provider)) {
+ QWARN(QString("SHA1 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("sha1", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::sha1longtest()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-botan");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
providersToTest.append("default");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha1", provider))
- QWARN(QString("SHA1 not supported for "+provider).toLocal8Bit());
- else {
- // QTime t;
- // t.start();
- QByteArray fillerString;
- fillerString.fill('a', 1000);
-
- // This test extracted from OpenOffice.org 1.1.2, in sal/workben/t_digest.c
- // It basically reflects FIPS 180-2, Appendix A.3
- // Also as per AS 2805.13.3-2000 Appendix A
- QCA::Hash shaHash("sha1", provider);
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("34aa973cd4c4daa4f61eeb2bdbad27316534016f") );
-
- QFile f1( "./data/empty" );
- if ( f1.open( QIODevice::ReadOnly ) ) {
- QCA::Hash hashObj("sha1", provider);
- hashObj.update( &f1 );
- QCOMPARE( QString( QCA::arrayToHex( hashObj.final().toByteArray() ) ),
- QString( "da39a3ee5e6b4b0d3255bfef95601890afd80709" ) );
- } else {
- QWARN( "./data/empty could not be opened - do you need to create it?");
- }
-
- QFile f2( "./data/twobytes" );
- if ( f2.open( QIODevice::ReadOnly ) ) {
- QCA::Hash hashObj("sha1", provider);
- hashObj.update( &f2 );
- QCOMPARE( QString( QCA::arrayToHex( hashObj.final().toByteArray() ) ),
- QString( "efbd6de3c51ca16094391e837bf52f7452593e5c" ) );
- } else {
- QWARN( "./data/twobytes could not be opened - do you need to download it?");
- }
-
- QFile f3( "./data/twohundredbytes" );
- if ( f3.open( QIODevice::ReadOnly ) ) {
- QCA::Hash hashObj("sha1", provider);
- hashObj.update( &f3 );
- QCOMPARE( QString( QCA::arrayToHex( hashObj.final().toByteArray() ) ),
- QString( "d636519dfb18d913acbe69fc3ee5a4c7ac870297" ) );
- } else {
- QWARN( "./data/twohundredbytes could not be opened - do you need to download it?");
- }
-
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha1", provider)) {
+ QWARN(QString("SHA1 not supported for " + provider).toLocal8Bit());
+ } else {
+ // QTime t;
+ // t.start();
+ QByteArray fillerString;
+ fillerString.fill('a', 1000);
+
+ // This test extracted from OpenOffice.org 1.1.2, in sal/workben/t_digest.c
+ // It basically reflects FIPS 180-2, Appendix A.3
+ // Also as per AS 2805.13.3-2000 Appendix A
+ QCA::Hash shaHash("sha1", provider);
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("34aa973cd4c4daa4f61eeb2bdbad27316534016f"));
+
+ QFile f1("./data/empty");
+ if (f1.open(QIODevice::ReadOnly)) {
+ QCA::Hash hashObj("sha1", provider);
+ hashObj.update(&f1);
+ QCOMPARE(QString(QCA::arrayToHex(hashObj.final().toByteArray())),
+ QString("da39a3ee5e6b4b0d3255bfef95601890afd80709"));
+ } else {
+ QWARN("./data/empty could not be opened - do you need to create it?");
+ }
+
+ QFile f2("./data/twobytes");
+ if (f2.open(QIODevice::ReadOnly)) {
+ QCA::Hash hashObj("sha1", provider);
+ hashObj.update(&f2);
+ QCOMPARE(QString(QCA::arrayToHex(hashObj.final().toByteArray())),
+ QString("efbd6de3c51ca16094391e837bf52f7452593e5c"));
+ } else {
+ QWARN("./data/twobytes could not be opened - do you need to download it?");
+ }
+
+ QFile f3("./data/twohundredbytes");
+ if (f3.open(QIODevice::ReadOnly)) {
+ QCA::Hash hashObj("sha1", provider);
+ hashObj.update(&f3);
+ QCOMPARE(QString(QCA::arrayToHex(hashObj.final().toByteArray())),
+ QString("d636519dfb18d913acbe69fc3ee5a4c7ac870297"));
+ } else {
+ QWARN("./data/twohundredbytes could not be opened - do you need to download it?");
+ }
+
+ }
}
}
void HashUnitTest::sha224test_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
// These are as specified in FIPS 180-2, change notice 1
// FIPS 180-2, Appendix B.1
QTest::newRow("sha224(abc)") << QByteArray("abc") << QString("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7");
// FIPS 180-2, Appendix B.2
QTest::newRow("sha224(aq)") << QByteArray("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
- << QString("75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525");
+ << QString("75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525");
}
void HashUnitTest::sha224test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-ipp");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha224", provider))
- QWARN(QString("SHA224 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("sha224", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha224", provider)) {
+ QWARN(QString("SHA224 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("sha224", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
-
void HashUnitTest::sha224longtest()
{
QByteArray fillerString;
fillerString.fill('a', 1000);
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-ipp");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha224", provider))
- QWARN(QString("SHA224 not supported for "+provider).toLocal8Bit());
- else {
- QCA::Hash shaHash("sha224", provider);
-
- // This basically reflects FIPS 180-2, change notice 1, section 3
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67") );
-
- shaHash.clear();
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67") );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha224", provider)) {
+ QWARN(QString("SHA224 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Hash shaHash("sha224", provider);
+
+ // This basically reflects FIPS 180-2, change notice 1, section 3
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67"));
+
+ shaHash.clear();
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67"));
+ }
}
}
void HashUnitTest::sha256test_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
// These are as specified in FIPS 180-2
// FIPS 180-2, Appendix B.1
QTest::newRow("sha256(abc)") << QByteArray("abc") << QString("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
// FIPS 180-2, Appendix B.2
QTest::newRow("sha256(abc)") << QByteArray("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
- << QString("248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
+ << QString("248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1");
}
void HashUnitTest::sha256test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha256", provider))
- QWARN(QString("SHA256 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("sha256", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha256", provider)) {
+ QWARN(QString("SHA256 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("sha256", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::sha256longtest()
{
QByteArray fillerString;
fillerString.fill('a', 1000);
QStringList providersToTest;
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha256", provider))
- QWARN(QString("SHA256 not supported for "+provider).toLocal8Bit());
- else {
- QCA::Hash shaHash("sha256", provider);
-
- // This basically reflects FIPS 180-2, change notice 1, section 3
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0") );
-
-
- shaHash.clear();
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0") );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha256", provider)) {
+ QWARN(QString("SHA256 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Hash shaHash("sha256", provider);
+
+ // This basically reflects FIPS 180-2, change notice 1, section 3
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"));
+
+ shaHash.clear();
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"));
+ }
}
}
-
void HashUnitTest::sha384test_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
// These are as specified in FIPS 180-2, and from Aaron Gifford's SHA2 tests
// FIPS 180-2, Appendix B.1
QTest::newRow("sha384(abc)") << QByteArray("abc")
- << QString("cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7");
+ << QString("cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7");
// FIPS 180-2, Appendix B.2
QTest::newRow("sha384(a-u)") << QByteArray("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu")
- << QString("09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039");
+ << QString("09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039");
// Aaron Gifford, vector002.info
QTest::newRow("sha384(a-q)") << QByteArray("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
- << QString("3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b");
-
+ << QString("3391fdddfc8dc7393707a65b1b4709397cf8b1d162af05abfe8f450de5f36bc6b0455a8520bc4e6f5fe95b1fe3c8452b");
}
void HashUnitTest::sha384test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha384", provider))
- QWARN(QString("SHA384 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("sha384", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha384", provider)) {
+ QWARN(QString("SHA384 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("sha384", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::sha384longtest()
{
QByteArray fillerString;
fillerString.fill('a', 1000);
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha384", provider))
- QWARN(QString("SHA384 not supported for "+provider).toLocal8Bit());
- else {
- // QTime t;
- // t.start();
- QCA::Hash shaHash("sha384", provider);
-
- // This basically reflects FIPS 180-2, change notice 1, section 3
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985") );
-
-
- shaHash.clear();
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985") );
- // qDebug() << "SHA384: " << provider << " elapsed " << t.elapsed();
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha384", provider)) {
+ QWARN(QString("SHA384 not supported for " + provider).toLocal8Bit());
+ } else {
+ // QTime t;
+ // t.start();
+ QCA::Hash shaHash("sha384", provider);
+
+ // This basically reflects FIPS 180-2, change notice 1, section 3
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985"));
+
+ shaHash.clear();
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985"));
+ // qDebug() << "SHA384: " << provider << " elapsed " << t.elapsed();
+ }
}
}
-
// These are as specified in FIPS 180-2, and from Aaron Gifford's SHA2 tests
void HashUnitTest::sha512test_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
// FIPS 180-2, Appendix C.1
QTest::newRow("sha512(abc)") << QByteArray("abc")
- << QString("ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
+ << QString("ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f");
// FIPS 180-2, Appendix C.2
QTest::newRow("sha512(a-u)") << QByteArray("abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu")
- << QString("8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");
+ << QString("8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909");
// Aaron Gifford, vector002.info
QTest::newRow("sha512(a-q)") << QByteArray("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
- << QString("204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445");
+ << QString("204a8fc6dda82f0a0ced7beb8e08a41657c16ef468b228a8279be331a703c33596fd15c13b1b07f9aa1d3bea57789ca031ad85c7a71dd70354ec631238ca3445");
}
void HashUnitTest::sha512test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha512", provider))
- QWARN(QString("SHA512 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("sha512", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha512", provider)) {
+ QWARN(QString("SHA512 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("sha512", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::sha512longtest()
{
QByteArray fillerString;
fillerString.fill('a', 1000);
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
providersToTest.append("qca-ipp");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("sha512", provider))
- QWARN(QString("SHA512 not supported for "+provider).toLocal8Bit());
- else {
- QCA::Hash shaHash("sha512", provider);
-
- // This basically reflects FIPS 180-2, change notice 1, section 3
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b") );
-
- shaHash.clear();
- for (int i=0; i<1000; i++)
- shaHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(shaHash.final().toByteArray())),
- QString("e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b") );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("sha512", provider)) {
+ QWARN(QString("SHA512 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Hash shaHash("sha512", provider);
+
+ // This basically reflects FIPS 180-2, change notice 1, section 3
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"));
+
+ shaHash.clear();
+ for (int i = 0; i < 1000; i++) {
+ shaHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(shaHash.final().toByteArray())),
+ QString("e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"));
+ }
}
}
// These are as specified in http://www.esat.kuleuven.ac.be/~bosselae/ripemd160.html
// ISO/IEC 10118-3 costs a bit of money.
void HashUnitTest::rmd160test_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
QTest::newRow("rmd160()") << QByteArray("") << QString("9c1185a5c5e9fc54612808977ee8f548b2258d31");
QTest::newRow("rmd160(a)") << QByteArray("a") << QString("0bdc9d2d256b3ee9daae347be6f4dc835a467ffe");
QTest::newRow("rmd160(abc)") << QByteArray("abc") << QString("8eb208f7e05d987a9b044a8e98c6b087f15a0bfc");
QTest::newRow("rmd160(md)") << QByteArray("message digest") << QString("5d0689ef49d2fae572b881b123a85ffa21595f36");
QTest::newRow("rmd160(a-z)") << QByteArray("abcdefghijklmnopqrstuvwxyz") << QString("f71c27109c692c1b56bbdceb5b9d2865b3708dbc");
QTest::newRow("rmd160(a-q)") << QByteArray("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq")
- << QString("12a053384a9c0c88e405a06c27dcf49ada62eb2b");
+ << QString("12a053384a9c0c88e405a06c27dcf49ada62eb2b");
QTest::newRow("rmd160(A-9)") << QByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
- << QString("b0e20b6e3116640286ed3a87a5713079b21f5189");
+ << QString("b0e20b6e3116640286ed3a87a5713079b21f5189");
QTest::newRow("rmd160(1-0)") << QByteArray("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
- << QString("9b752e45573d4b39f4dbd3323cab82bf63326bfb");
+ << QString("9b752e45573d4b39f4dbd3323cab82bf63326bfb");
}
-
void HashUnitTest::rmd160test()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("ripemd160", provider))
- QWARN(QString("RIPEMD160 not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("ripemd160", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("ripemd160", provider)) {
+ QWARN(QString("RIPEMD160 not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("ripemd160", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::rmd160longtest()
{
QByteArray fillerString;
fillerString.fill('a', 1000);
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("ripemd160", provider))
- QWARN(QString("RIPEMD160 not supported for "+provider).toLocal8Bit());
- else {
- QCA::Hash rmdHash("ripemd160", provider);
-
- // This is the "million times 'a' test"
- for (int i=0; i<1000; i++)
- rmdHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
- QString("52783243c1697bdbe16d37f97f68f08325dc1528") );
-
- rmdHash.clear();
- for (int i=0; i<1000; i++)
- rmdHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
- QString("52783243c1697bdbe16d37f97f68f08325dc1528") );
-
- // This is the "8 rounds of 1234567890" test.
- // It also ensure that we can re-use hash objects correctly.
- static char bindata[] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
- QByteArray fillerArray( bindata, sizeof(bindata) ); // "1234567890"
- rmdHash.clear();
- for (int i=0; i<8; i++)
- rmdHash.update(fillerArray);
- QCOMPARE( QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
- QString("9b752e45573d4b39f4dbd3323cab82bf63326bfb") );
-
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("ripemd160", provider)) {
+ QWARN(QString("RIPEMD160 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Hash rmdHash("ripemd160", provider);
+
+ // This is the "million times 'a' test"
+ for (int i = 0; i < 1000; i++) {
+ rmdHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
+ QString("52783243c1697bdbe16d37f97f68f08325dc1528"));
+
+ rmdHash.clear();
+ for (int i = 0; i < 1000; i++) {
+ rmdHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
+ QString("52783243c1697bdbe16d37f97f68f08325dc1528"));
+
+ // This is the "8 rounds of 1234567890" test.
+ // It also ensure that we can re-use hash objects correctly.
+ static char bindata[] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
+ QByteArray fillerArray(bindata, sizeof(bindata)); // "1234567890"
+ rmdHash.clear();
+ for (int i = 0; i < 8; i++) {
+ rmdHash.update(fillerArray);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
+ QString("9b752e45573d4b39f4dbd3323cab82bf63326bfb"));
+
+ }
}
}
-
// These are from the documentation pack at http://paginas.terra.com.br/informatica/paulobarreto/WhirlpoolPage.html
void HashUnitTest::whirlpooltest_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QString>("expectedHash");
QTest::newRow("whirlpool()") << QByteArray("") << QString("19fa61d75522a4669b44e39c1d2e1726c530232130d407f89afee0964997f7a73e83be698b288febcf88e3e03c4f0757ea8964e59b63d93708b138cc42a66eb3");
QTest::newRow("whirlpool(a)") << QByteArray("a") << QString("8aca2602792aec6f11a67206531fb7d7f0dff59413145e6973c45001d0087b42d11bc645413aeff63a42391a39145a591a92200d560195e53b478584fdae231a");
QTest::newRow("whirlpool(abc)") << QByteArray("abc") << QString("4e2448a4c6f486bb16b6562c73b4020bf3043e3a731bce721ae1b303d97e6d4c7181eebdb6c57e277d0e34957114cbd6c797fc9d95d8b582d225292076d4eef5");
QTest::newRow("whirlpool(md)") << QByteArray("message digest") << QString("378c84a4126e2dc6e56dcc7458377aac838d00032230f53ce1f5700c0ffb4d3b8421557659ef55c106b4b52ac5a4aaa692ed920052838f3362e86dbd37a8903e");
QTest::newRow("whirlpool(a-k)") << QByteArray("abcdbcdecdefdefgefghfghighijhijk")
- << QString("2a987ea40f917061f5d6f0a0e4644f488a7a5a52deee656207c562f988e95c6916bdc8031bc5be1b7b947639fe050b56939baaa0adff9ae6745b7b181c3be3fd");
+ << QString("2a987ea40f917061f5d6f0a0e4644f488a7a5a52deee656207c562f988e95c6916bdc8031bc5be1b7b947639fe050b56939baaa0adff9ae6745b7b181c3be3fd");
QTest::newRow("whirlpool(a-z)") << QByteArray("abcdefghijklmnopqrstuvwxyz") << QString("f1d754662636ffe92c82ebb9212a484a8d38631ead4238f5442ee13b8054e41b08bf2a9251c30b6a0b8aae86177ab4a6f68f673e7207865d5d9819a3dba4eb3b");
QTest::newRow("whirlpool(A-9)") << QByteArray("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
- << QString("dc37e008cf9ee69bf11f00ed9aba26901dd7c28cdec066cc6af42e40f82f3a1e08eba26629129d8fb7cb57211b9281a65517cc879d7b962142c65f5a7af01467");
+ << QString("dc37e008cf9ee69bf11f00ed9aba26901dd7c28cdec066cc6af42e40f82f3a1e08eba26629129d8fb7cb57211b9281a65517cc879d7b962142c65f5a7af01467");
QTest::newRow("whirlpool(1-0)") << QByteArray("12345678901234567890123456789012345678901234567890123456789012345678901234567890")
- << QString("466ef18babb0154d25b9d38a6414f5c08784372bccb204d6549c4afadb6014294d5bd8df2a6c44e538cd047b2681a51a2c60481e88c5a20b2c2a80cf3a9a083b");
+ << QString("466ef18babb0154d25b9d38a6414f5c08784372bccb204d6549c4afadb6014294d5bd8df2a6c44e538cd047b2681a51a2c60481e88c5a20b2c2a80cf3a9a083b");
}
-
void HashUnitTest::whirlpooltest()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
QFETCH(QByteArray, input);
QFETCH(QString, expectedHash);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("whirlpool", provider))
- QWARN(QString("Whirlpool not supported for "+provider).toLocal8Bit());
- else {
- QString hashResult = QCA::Hash("whirlpool", provider).hashToString(input);
- QCOMPARE( hashResult, expectedHash );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("whirlpool", provider)) {
+ QWARN(QString("Whirlpool not supported for " + provider).toLocal8Bit());
+ } else {
+ QString hashResult = QCA::Hash("whirlpool", provider).hashToString(input);
+ QCOMPARE(hashResult, expectedHash);
+ }
}
}
void HashUnitTest::whirlpoollongtest()
{
QByteArray fillerString;
fillerString.fill('a', 1000);
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("whirlpool", provider))
- QWARN(QString("Whirlpool not supported for "+provider).toLocal8Bit());
- else {
- QCA::Hash rmdHash("whirlpool", provider);
-
- // This is the "million times 'a' test"
- for (int i=0; i<1000; i++)
- rmdHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
- QString("0c99005beb57eff50a7cf005560ddf5d29057fd86b20bfd62deca0f1ccea4af51fc15490eddc47af32bb2b66c34ff9ad8c6008ad677f77126953b226e4ed8b01") );
-
- rmdHash.clear();
- for (int i=0; i<1000; i++)
- rmdHash.update(fillerString);
- QCOMPARE( QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
- QString("0c99005beb57eff50a7cf005560ddf5d29057fd86b20bfd62deca0f1ccea4af51fc15490eddc47af32bb2b66c34ff9ad8c6008ad677f77126953b226e4ed8b01") );
-
- // This is the "8 rounds of 1234567890" test.
- // It also ensure that we can re-use hash objects correctly.
- static char bindata[] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
- QByteArray fillerArray( bindata, sizeof(bindata) ); // "1234567890"
- rmdHash.clear();
- for (int i=0; i<8; i++)
- rmdHash.update(fillerArray);
- QCOMPARE( QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
- QString("466ef18babb0154d25b9d38a6414f5c08784372bccb204d6549c4afadb6014294d5bd8df2a6c44e538cd047b2681a51a2c60481e88c5a20b2c2a80cf3a9a083b") );
-
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("whirlpool", provider)) {
+ QWARN(QString("Whirlpool not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Hash rmdHash("whirlpool", provider);
+
+ // This is the "million times 'a' test"
+ for (int i = 0; i < 1000; i++) {
+ rmdHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
+ QString("0c99005beb57eff50a7cf005560ddf5d29057fd86b20bfd62deca0f1ccea4af51fc15490eddc47af32bb2b66c34ff9ad8c6008ad677f77126953b226e4ed8b01"));
+
+ rmdHash.clear();
+ for (int i = 0; i < 1000; i++) {
+ rmdHash.update(fillerString);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
+ QString("0c99005beb57eff50a7cf005560ddf5d29057fd86b20bfd62deca0f1ccea4af51fc15490eddc47af32bb2b66c34ff9ad8c6008ad677f77126953b226e4ed8b01"));
+
+ // This is the "8 rounds of 1234567890" test.
+ // It also ensure that we can re-use hash objects correctly.
+ static char bindata[] = { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
+ QByteArray fillerArray(bindata, sizeof(bindata)); // "1234567890"
+ rmdHash.clear();
+ for (int i = 0; i < 8; i++) {
+ rmdHash.update(fillerArray);
+ }
+ QCOMPARE(QString(QCA::arrayToHex(rmdHash.final().toByteArray())),
+ QString("466ef18babb0154d25b9d38a6414f5c08784372bccb204d6549c4afadb6014294d5bd8df2a6c44e538cd047b2681a51a2c60481e88c5a20b2c2a80cf3a9a083b"));
+
+ }
}
}
-
QTEST_MAIN(HashUnitTest)
#include "hashunittest.moc"
diff --git a/unittest/hexunittest/hexunittest.cpp b/unittest/hexunittest/hexunittest.cpp
index 17bcb4a7..bba044f9 100644
--- a/unittest/hexunittest/hexunittest.cpp
+++ b/unittest/hexunittest/hexunittest.cpp
@@ -1,120 +1,120 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class HexUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testHexString_data();
void testHexString();
void testIncrementalUpdate();
void testBrokenInput();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void HexUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void HexUnitTest::cleanupTestCase()
{
delete m_init;
}
void HexUnitTest::testHexString_data()
{
QTest::addColumn<QString>("raw");
QTest::addColumn<QString>("encoded");
QTest::newRow("abcd") << QString("abcd") << QString("61626364");
QTest::newRow("ABCD") << QString("ABCD") << QString("41424344");
QTest::newRow("empty") << QString("") << QString("");
QTest::newRow("abcddef") << QString("abcddef") << QString("61626364646566");
QTest::newRow("empty too") << QString("\0") << QString(""); // Empty QString.
QTest::newRow("BEL") << QString("\a") << QString("07"); // BEL
QTest::newRow("BS") << QString("\b") << QString("08"); // BS
QTest::newRow("HT") << QString("\t") << QString("09"); // HT
QTest::newRow("LF") << QString("\n") << QString("0a"); // LF
QTest::newRow("VT") << QString("\v") << QString("0b"); // VT
QTest::newRow("FF") << QString("\f") << QString("0c"); // FF
QTest::newRow("CR") << QString("\r") << QString("0d"); // CR
QTest::newRow("bug126735") << QString("@ABCDEFGHIJKLMNO") << QString("404142434445464748494a4b4c4d4e4f");
}
void HexUnitTest::testHexString()
{
QCA::Hex hexObject;
QFETCH(QString, raw);
QFETCH(QString, encoded);
- QCOMPARE( hexObject.encodeString(raw), encoded);
- QCOMPARE( hexObject.decodeString(encoded), raw);
+ QCOMPARE(hexObject.encodeString(raw), encoded);
+ QCOMPARE(hexObject.decodeString(encoded), raw);
}
void HexUnitTest::testIncrementalUpdate()
{
QCA::Hex hexObject;
hexObject.setup(QCA::Encode);
hexObject.clear();
QCA::SecureArray result1 = hexObject.update(QCA::SecureArray("ab"));
- QVERIFY( hexObject.ok() );
- QCOMPARE( result1[0], '6' );
- QCOMPARE( result1[1], '1' );
- QCOMPARE( result1[2], '6' );
- QCOMPARE( result1[3], '2' );
+ QVERIFY(hexObject.ok());
+ QCOMPARE(result1[0], '6');
+ QCOMPARE(result1[1], '1');
+ QCOMPARE(result1[2], '6');
+ QCOMPARE(result1[3], '2');
QCA::SecureArray result2 = hexObject.update(QCA::SecureArray("cd"));
- QCOMPARE( hexObject.ok(), true );
- QCOMPARE( result2[0], '6' );
- QCOMPARE( result2[1], '3' );
- QCOMPARE( result2[2], '6' );
- QCOMPARE( result2[3], '4' );
- QCOMPARE( QCA::SecureArray(), QCA::SecureArray(hexObject.final()) );
- QCOMPARE( hexObject.ok(), true );
+ QCOMPARE(hexObject.ok(), true);
+ QCOMPARE(result2[0], '6');
+ QCOMPARE(result2[1], '3');
+ QCOMPARE(result2[2], '6');
+ QCOMPARE(result2[3], '4');
+ QCOMPARE(QCA::SecureArray(), QCA::SecureArray(hexObject.final()));
+ QCOMPARE(hexObject.ok(), true);
}
void HexUnitTest::testBrokenInput()
{
QCA::Hex hexObject;
hexObject.setup(QCA::Decode);
hexObject.update(QCA::SecureArray("-="));
QCOMPARE(hexObject.ok(), false);
}
QTEST_MAIN(HexUnitTest)
#include "hexunittest.moc"
diff --git a/unittest/kdfunittest/kdfunittest.cpp b/unittest/kdfunittest/kdfunittest.cpp
index 4683f6af..6a5c4902 100644
--- a/unittest/kdfunittest/kdfunittest.cpp
+++ b/unittest/kdfunittest/kdfunittest.cpp
@@ -1,536 +1,532 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class KDFUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void pbkdf1md2Tests_data();
void pbkdf1md2Tests();
void pbkdf1sha1Tests_data();
void pbkdf1sha1Tests();
- void pbkdf1sha1TimeTest();
+ void pbkdf1sha1TimeTest();
void pbkdf2Tests_data();
void pbkdf2Tests();
- void pbkdf2TimeTest();
+ void pbkdf2TimeTest();
void pbkdf2extraTests();
void hkdfTests_data();
void hkdfTests();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
-
void KDFUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void KDFUnitTest::cleanupTestCase()
{
delete m_init;
}
-
void KDFUnitTest::pbkdf1md2Tests_data()
{
QTest::addColumn<QString>("secret"); // usually a password or passphrase
QTest::addColumn<QString>("output"); // the key you get back
QTest::addColumn<QString>("salt"); // a salt or initialisation vector
QTest::addColumn<unsigned int>("outputLength"); // if the algo supports variable length keys, len
QTest::addColumn<unsigned int>("iterationCount"); // number of iterations
// These are from Botan's test suite
QTest::newRow("1") << QString("71616c7a73656774")
- << QString("7c1991f3f38a09d70cf3b1acadb70bc6")
- << QString("40cf117c3865e0cf")
- << static_cast<unsigned int>(16)
- << static_cast<unsigned int>(1000);
+ << QString("7c1991f3f38a09d70cf3b1acadb70bc6")
+ << QString("40cf117c3865e0cf")
+ << static_cast<unsigned int>(16)
+ << static_cast<unsigned int>(1000);
QTest::newRow("2") << QString("766e68617a6a66736978626f6d787175")
- << QString("677500eda9f0c5e96e0a11f90fb9")
- << QString("3a2484ce5d3e1b4d")
- << static_cast<unsigned int>(14)
- << static_cast<unsigned int>(1);
+ << QString("677500eda9f0c5e96e0a11f90fb9")
+ << QString("3a2484ce5d3e1b4d")
+ << static_cast<unsigned int>(14)
+ << static_cast<unsigned int>(1);
QTest::newRow("3") << QString("66686565746e657162646d7171716e797977696f716a666c6f6976636371756a")
- << QString("91a5b689156b441bf27dd2bdd276")
- << QString("5d838b0f4fa22bfa2157f9083d87f8752e0495bb2113012761ef11b66e87c3cb")
- << static_cast<unsigned int>(14)
- << static_cast<unsigned int>(15);
+ << QString("91a5b689156b441bf27dd2bdd276")
+ << QString("5d838b0f4fa22bfa2157f9083d87f8752e0495bb2113012761ef11b66e87c3cb")
+ << static_cast<unsigned int>(14)
+ << static_cast<unsigned int>(15);
QTest::newRow("4") << QString("736e6279696e6a7075696b7176787867726c6b66")
- << QString("49516935cc9f438bafa30ff038fb")
- << QString("f22d341361b47e3390107bd973fdc0d3e0bc02a3")
- << static_cast<unsigned int>(14)
- << static_cast<unsigned int>(2);
+ << QString("49516935cc9f438bafa30ff038fb")
+ << QString("f22d341361b47e3390107bd973fdc0d3e0bc02a3")
+ << static_cast<unsigned int>(14)
+ << static_cast<unsigned int>(2);
}
void KDFUnitTest::pbkdf1md2Tests()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// gcrypt doesn't do md2...
// providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
QFETCH(QString, secret);
QFETCH(QString, output);
QFETCH(QString, salt);
QFETCH(unsigned int, outputLength);
QFETCH(unsigned int, iterationCount);
-
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("pbkdf1(md2)", provider))
- QWARN(QString("PBKDF version 1 with MD2 not supported for "+provider).toLocal8Bit());
- else {
- QCA::SecureArray password = QCA::hexToArray( secret );
- QCA::InitializationVector iv( QCA::hexToArray( salt) );
- QCA::SymmetricKey key = QCA::PBKDF1("md2", provider).makeKey( password,
- iv,
- outputLength,
- iterationCount);
- QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("pbkdf1(md2)", provider)) {
+ QWARN(QString("PBKDF version 1 with MD2 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::SecureArray password = QCA::hexToArray(secret);
+ QCA::InitializationVector iv(QCA::hexToArray(salt));
+ QCA::SymmetricKey key = QCA::PBKDF1("md2", provider).makeKey(password,
+ iv,
+ outputLength,
+ iterationCount);
+ QCOMPARE(QCA::arrayToHex(key.toByteArray()), output);
+ }
}
}
void KDFUnitTest::pbkdf1sha1Tests_data()
{
QTest::addColumn<QString>("secret"); // usually a password or passphrase
QTest::addColumn<QString>("output"); // the key you get back
QTest::addColumn<QString>("salt"); // a salt or initialisation vector
QTest::addColumn<unsigned int>("outputLength"); // if the algo supports variable length keys, len
QTest::addColumn<unsigned int>("iterationCount"); // number of iterations
// These are from Botan's test suite
QTest::newRow("1") << QString("66746c6b6662786474626a62766c6c7662776977")
- << QString("768b277dc970f912dbdd3edad48ad2f065d25d")
- << QString("40ac5837560251c275af5e30a6a3074e57ced38e")
- << static_cast<unsigned int>(19)
- << static_cast<unsigned int>(6);
+ << QString("768b277dc970f912dbdd3edad48ad2f065d25d")
+ << QString("40ac5837560251c275af5e30a6a3074e57ced38e")
+ << static_cast<unsigned int>(19)
+ << static_cast<unsigned int>(6);
QTest::newRow("2") << QString("786e736f736d6b766867677a7370636e63706f63")
- << QString("4d90e846a4b6aaa02ac548014a00e97e506b2afb")
- << QString("7008a9dc1b9a81470a2360275c19dab77f716824")
- << static_cast<unsigned int>(20)
- << static_cast<unsigned int>(6);
+ << QString("4d90e846a4b6aaa02ac548014a00e97e506b2afb")
+ << QString("7008a9dc1b9a81470a2360275c19dab77f716824")
+ << static_cast<unsigned int>(20)
+ << static_cast<unsigned int>(6);
QTest::newRow("3") << QString("6f74696c71776c756b717473")
- << QString("71ed1a995e693efcd33155935e800037da74ea28")
- << QString("ccfc44c09339040e55d3f7f76ca6ef838fde928717241deb9ac1a4ef45a27711")
- << static_cast<unsigned int>(20)
- << static_cast<unsigned int>(2001);
+ << QString("71ed1a995e693efcd33155935e800037da74ea28")
+ << QString("ccfc44c09339040e55d3f7f76ca6ef838fde928717241deb9ac1a4ef45a27711")
+ << static_cast<unsigned int>(20)
+ << static_cast<unsigned int>(2001);
QTest::newRow("4") << QString("6b7a6e657166666c6274767374686e6663746166")
- << QString("f345fb8fbd880206b650266661f6")
- << QString("8108883fc04a01feb10661651516425dad1c93e0")
- << static_cast<unsigned int>(14)
- << static_cast<unsigned int>(10000);
+ << QString("f345fb8fbd880206b650266661f6")
+ << QString("8108883fc04a01feb10661651516425dad1c93e0")
+ << static_cast<unsigned int>(14)
+ << static_cast<unsigned int>(10000);
QTest::newRow("5") << QString("716b78686c7170656d7868796b6d7975636a626f")
- << QString("2d54dfed0c7ef7d20b0945ba414a")
- << QString("bc8bc53d4604977c3adb1d19c15e87b77a84c2f6")
- << static_cast<unsigned int>(14)
- << static_cast<unsigned int>(10000);
+ << QString("2d54dfed0c7ef7d20b0945ba414a")
+ << QString("bc8bc53d4604977c3adb1d19c15e87b77a84c2f6")
+ << static_cast<unsigned int>(14)
+ << static_cast<unsigned int>(10000);
}
void KDFUnitTest::pbkdf1sha1Tests()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
QFETCH(QString, secret);
QFETCH(QString, output);
QFETCH(QString, salt);
QFETCH(unsigned int, outputLength);
QFETCH(unsigned int, iterationCount);
-
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("pbkdf1(sha1)", provider))
- QWARN(QString("PBKDF version 1 with SHA1 not supported for "+provider).toLocal8Bit());
- else {
- QCA::SecureArray password = QCA::hexToArray( secret );
- QCA::InitializationVector iv( QCA::hexToArray( salt) );
- QCA::SymmetricKey key = QCA::PBKDF1("sha1", provider).makeKey( password,
- iv,
- outputLength,
- iterationCount);
- QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output );
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("pbkdf1(sha1)", provider)) {
+ QWARN(QString("PBKDF version 1 with SHA1 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::SecureArray password = QCA::hexToArray(secret);
+ QCA::InitializationVector iv(QCA::hexToArray(salt));
+ QCA::SymmetricKey key = QCA::PBKDF1("sha1", provider).makeKey(password,
+ iv,
+ outputLength,
+ iterationCount);
+ QCOMPARE(QCA::arrayToHex(key.toByteArray()), output);
+ }
}
}
void KDFUnitTest::pbkdf1sha1TimeTest()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-gcrypt");
-
- QCA::SecureArray password("secret");
- QCA::InitializationVector iv(QByteArray("salt"));
- unsigned int outputLength = 20;
- int timeInterval = 200;
- unsigned int iterationCount;
-
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("pbkdf1(sha1)", provider)) {
- QString warning("PBKDF version 1 with SHA1 not supported for %1");
- QWARN(warning.arg(provider).toStdString().c_str());
- } else {
- QCA::SymmetricKey key1(QCA::PBKDF1("sha1", provider).makeKey(password,
- iv,
- outputLength,
- timeInterval,
- &iterationCount));
-
- QCA::SymmetricKey key2(QCA::PBKDF1("sha1", provider).makeKey(password,
- iv,
- outputLength,
- iterationCount));
-
- QCOMPARE( key1, key2 );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-gcrypt");
+
+ QCA::SecureArray password("secret");
+ QCA::InitializationVector iv(QByteArray("salt"));
+ unsigned int outputLength = 20;
+ int timeInterval = 200;
+ unsigned int iterationCount;
+
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("pbkdf1(sha1)", provider)) {
+ QString warning("PBKDF version 1 with SHA1 not supported for %1");
+ QWARN(warning.arg(provider).toStdString().c_str());
+ } else {
+ QCA::SymmetricKey key1(QCA::PBKDF1("sha1", provider).makeKey(password,
+ iv,
+ outputLength,
+ timeInterval,
+ &iterationCount));
+
+ QCA::SymmetricKey key2(QCA::PBKDF1("sha1", provider).makeKey(password,
+ iv,
+ outputLength,
+ iterationCount));
+
+ QCOMPARE(key1, key2);
+ }
+ }
}
void KDFUnitTest::pbkdf2Tests_data()
{
QTest::addColumn<QString>("secret"); // usually a password or passphrase
QTest::addColumn<QString>("output"); // the key you get back
QTest::addColumn<QString>("salt"); // a salt or initialisation vector
QTest::addColumn<unsigned int>("outputLength"); // if the algo supports variable length keys, len
QTest::addColumn<unsigned int>("iterationCount"); // number of iterations
// These are from Botan's test suite
QTest::newRow("1") << QString("6a79756571677872736367676c707864796b6366")
- << QString("df6d9d72872404bf73e708cf3b7d")
- << QString("9b56e55328a4c97a250738f8dba1b992e8a1b508")
- << static_cast<unsigned int>(14)
- << static_cast<unsigned int>(10000);
+ << QString("df6d9d72872404bf73e708cf3b7d")
+ << QString("9b56e55328a4c97a250738f8dba1b992e8a1b508")
+ << static_cast<unsigned int>(14)
+ << static_cast<unsigned int>(10000);
QTest::newRow("2") << QString("61717271737a6e7a76767a67746b73616d6d676f")
- << QString("fa13f40af1ade2a30f2fffd66fc8a659ef95e6388c1682fc0fe4d15a70109517a32942e39c371440")
- << QString("57487813cdd2220dfc485d932a2979ee8769ea8b")
- << static_cast<unsigned int>(40)
- << static_cast<unsigned int>(101);
+ << QString("fa13f40af1ade2a30f2fffd66fc8a659ef95e6388c1682fc0fe4d15a70109517a32942e39c371440")
+ << QString("57487813cdd2220dfc485d932a2979ee8769ea8b")
+ << static_cast<unsigned int>(40)
+ << static_cast<unsigned int>(101);
QTest::newRow("3") << QString("6c7465786d666579796c6d6c62727379696b6177")
- << QString("027afadd48f4be8dcc4f")
- << QString("ed1f39a0a7f3889aaf7e60743b3bc1cc2c738e60")
- << static_cast<unsigned int>(10)
- << static_cast<unsigned int>(1000);
+ << QString("027afadd48f4be8dcc4f")
+ << QString("ed1f39a0a7f3889aaf7e60743b3bc1cc2c738e60")
+ << static_cast<unsigned int>(10)
+ << static_cast<unsigned int>(1000);
QTest::newRow("4") << QString("6378676e7972636772766c6c796c6f6c736a706f")
- << QString("7c0d009fc91b48cb6d19bafbfccff3e2ccabfe725eaa234e56bde1d551c132f2")
- << QString("94ac88200743fb0f6ac51be62166cbef08d94c15")
- << static_cast<unsigned int>(32)
- << static_cast<unsigned int>(1);
+ << QString("7c0d009fc91b48cb6d19bafbfccff3e2ccabfe725eaa234e56bde1d551c132f2")
+ << QString("94ac88200743fb0f6ac51be62166cbef08d94c15")
+ << static_cast<unsigned int>(32)
+ << static_cast<unsigned int>(1);
QTest::newRow("5") << QString("7871796668727865686965646c6865776e76626a")
- << QString("4661301d3517ca4443a6a607b32b2a63f69996299df75db75f1e0b98dd0eb7d8")
- << QString("24a1a50b17d63ee8394b69fc70887f4f94883d68")
- << static_cast<unsigned int>(32)
- << static_cast<unsigned int>(5);
+ << QString("4661301d3517ca4443a6a607b32b2a63f69996299df75db75f1e0b98dd0eb7d8")
+ << QString("24a1a50b17d63ee8394b69fc70887f4f94883d68")
+ << static_cast<unsigned int>(32)
+ << static_cast<unsigned int>(5);
QTest::newRow("6") << QString("616e6461716b706a7761627663666e706e6a6b6c")
- << QString("82fb44a521448d5aac94b5158ead1e4dcd7363081a747b9f7626752bda2d")
- << QString("9316c80801623cc2734af74bec42cf4dbaa3f6d5")
- << static_cast<unsigned int>(30)
- << static_cast<unsigned int>(100);
+ << QString("82fb44a521448d5aac94b5158ead1e4dcd7363081a747b9f7626752bda2d")
+ << QString("9316c80801623cc2734af74bec42cf4dbaa3f6d5")
+ << static_cast<unsigned int>(30)
+ << static_cast<unsigned int>(100);
QTest::newRow("7") << QString("687361767679766f636c6f79757a746c736e6975")
- << QString("f8ec2b0ac817896ac8189d787c6424ed24a6d881436687a4629802c0ecce")
- << QString("612cc61df3cf2bdb36e10c4d8c9d73192bddee05")
- << static_cast<unsigned int>(30)
- << static_cast<unsigned int>(100);
+ << QString("f8ec2b0ac817896ac8189d787c6424ed24a6d881436687a4629802c0ecce")
+ << QString("612cc61df3cf2bdb36e10c4d8c9d73192bddee05")
+ << static_cast<unsigned int>(30)
+ << static_cast<unsigned int>(100);
QTest::newRow("8") << QString("6561696d72627a70636f706275736171746b6d77")
- << QString("c9a0b2622f13916036e29e7462e206e8ba5b50ce9212752eb8ea2a4aa7b40a4cc1bf")
- << QString("45248f9d0cebcb86a18243e76c972a1f3b36772a")
- << static_cast<unsigned int>(34)
- << static_cast<unsigned int>(100);
+ << QString("c9a0b2622f13916036e29e7462e206e8ba5b50ce9212752eb8ea2a4aa7b40a4cc1bf")
+ << QString("45248f9d0cebcb86a18243e76c972a1f3b36772a")
+ << static_cast<unsigned int>(34)
+ << static_cast<unsigned int>(100);
QTest::newRow("9") << QString("67777278707178756d7364736d626d6866686d666463766c63766e677a6b6967")
- << QString("4c9db7ba24955225d5b845f65ef24ef1b0c6e86f2e39c8ddaa4b8abd26082d1f350381fadeaeb560dc447afc68a6b47e6ea1e7412f6cf7b2d82342fccd11d3b4")
- << QString("a39b76c6eec8374a11493ad08c246a3e40dfae5064f4ee3489c273646178")
- << static_cast<unsigned int>(64)
- << static_cast<unsigned int>(1000);
+ << QString("4c9db7ba24955225d5b845f65ef24ef1b0c6e86f2e39c8ddaa4b8abd26082d1f350381fadeaeb560dc447afc68a6b47e6ea1e7412f6cf7b2d82342fccd11d3b4")
+ << QString("a39b76c6eec8374a11493ad08c246a3e40dfae5064f4ee3489c273646178")
+ << static_cast<unsigned int>(64)
+ << static_cast<unsigned int>(1000);
}
void KDFUnitTest::pbkdf2Tests()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
QFETCH(QString, secret);
QFETCH(QString, output);
QFETCH(QString, salt);
QFETCH(unsigned int, outputLength);
QFETCH(unsigned int, iterationCount);
-
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("pbkdf2(sha1)", provider))
- QWARN(QString("PBKDF version 2 with SHA1 not supported for "+provider).toLocal8Bit());
- else {
- QCA::SecureArray password = QCA::hexToArray( secret );
- QCA::InitializationVector iv( QCA::hexToArray( salt) );
- QCA::SymmetricKey key = QCA::PBKDF2("sha1", provider).makeKey( password,
- iv,
- outputLength,
- iterationCount);
- QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output );
-
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("pbkdf2(sha1)", provider)) {
+ QWARN(QString("PBKDF version 2 with SHA1 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::SecureArray password = QCA::hexToArray(secret);
+ QCA::InitializationVector iv(QCA::hexToArray(salt));
+ QCA::SymmetricKey key = QCA::PBKDF2("sha1", provider).makeKey(password,
+ iv,
+ outputLength,
+ iterationCount);
+ QCOMPARE(QCA::arrayToHex(key.toByteArray()), output);
+
+ }
}
}
void KDFUnitTest::pbkdf2TimeTest()
{
- QStringList providersToTest;
- providersToTest.append("qca-ossl");
- providersToTest.append("qca-botan");
- providersToTest.append("qca-gcrypt");
-
- QCA::SecureArray password("secret");
- QCA::InitializationVector iv(QByteArray("salt"));
- unsigned int outputLength = 20;
- int timeInterval = 200;
- unsigned int iterationCount;
-
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("pbkdf2(sha1)", provider)) {
- QString warning("PBKDF version 2 with SHA1 not supported for %1");
- QWARN(warning.arg(provider).toStdString().c_str());
- } else {
- QCA::SymmetricKey key1(QCA::PBKDF2("sha1", provider).makeKey(password,
- iv,
- outputLength,
- timeInterval,
- &iterationCount));
-
- QCA::SymmetricKey key2(QCA::PBKDF2("sha1", provider).makeKey(password,
- iv,
- outputLength,
- iterationCount));
-
- QCOMPARE( key1, key2 );
- }
- }
+ QStringList providersToTest;
+ providersToTest.append("qca-ossl");
+ providersToTest.append("qca-botan");
+ providersToTest.append("qca-gcrypt");
+
+ QCA::SecureArray password("secret");
+ QCA::InitializationVector iv(QByteArray("salt"));
+ unsigned int outputLength = 20;
+ int timeInterval = 200;
+ unsigned int iterationCount;
+
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("pbkdf2(sha1)", provider)) {
+ QString warning("PBKDF version 2 with SHA1 not supported for %1");
+ QWARN(warning.arg(provider).toStdString().c_str());
+ } else {
+ QCA::SymmetricKey key1(QCA::PBKDF2("sha1", provider).makeKey(password,
+ iv,
+ outputLength,
+ timeInterval,
+ &iterationCount));
+
+ QCA::SymmetricKey key2(QCA::PBKDF2("sha1", provider).makeKey(password,
+ iv,
+ outputLength,
+ iterationCount));
+
+ QCOMPARE(key1, key2);
+ }
+ }
}
void KDFUnitTest::pbkdf2extraTests()
{
QStringList providersToTest;
// providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("pbkdf2(sha1)", provider))
- QWARN(QString("PBKDF version 2 with SHA1 not supported for "+provider).toLocal8Bit());
- else {
- // Not sure where this one came from...
- {
- QCA::InitializationVector salt(QCA::SecureArray("what do ya want for nothing?"));
- QCA::SecureArray password("Jefe");
- int iterations = 1000;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "6349e09cb6b8c1485cfa9780ee3264df" ) );
- }
-
- // RFC3962, Appendix B
- {
- QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn"));
- QCA::SecureArray password("password");
- int iterations = 1;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "cdedb5281bb2f801565a1122b2563515" ) );
- passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837" ) );
- }
-
- // RFC3962, Appendix B
- {
- QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn"));
- QCA::SecureArray password("password");
- int iterations = 2;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "01dbee7f4a9e243e988b62c73cda935d" ) );
- passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86" ) );
- }
-
- // RFC3962, Appendix B
- {
- QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn"));
- QCA::SecureArray password("password");
- int iterations = 1200;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "5c08eb61fdf71e4e4ec3cf6ba1f5512b" ) );
- passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13" ) );
- }
-
- // RFC3211 and RFC3962, Appendix B
- {
- QCA::InitializationVector salt(QCA::hexToArray("1234567878563412"));
- QCA::SecureArray password("password");
- int iterations = 5;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "d1daa78615f287e6a1c8b120d7062a49" ) );
- passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee" ) );
- passwordOut = QCA::PBKDF2().makeKey (password, salt, 8, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "d1daa78615f287e6" ) );
- }
-
- // RFC3962, Appendix B
- {
- QCA::InitializationVector salt(QCA::SecureArray("pass phrase equals block size"));
- QCA::SecureArray password("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
- int iterations = 1200;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "139c30c0966bc32ba55fdbf212530ac9" ) );
- passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1" ) );
- }
-
- // RFC3962, Appendix B
- {
- try {
- QCA::InitializationVector salt(QCA::SecureArray("pass phrase exceeds block size"));
- QCA::SecureArray password("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
- int iterations = 1200;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "9ccad6d468770cd51b10e6a68721be61" ) );
- passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a" ) );
- } catch(std::exception &) {
- if (provider == "qca-botan")
- qDebug() << "You should use a later version of Botan";
- else
- QFAIL("exception");
- }
- }
-
- // RFC3962, Appendix B
- {
- QCA::InitializationVector salt(QCA::SecureArray("EXAMPLE.COMpianist"));
- QCA::SecureArray password(QCA::hexToArray("f09d849e"));
- int iterations = 50;
- QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 16, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()), QString( "6b9cf26d45455a43a5b8bb276a403b39" ) );
- passwordOut = QCA::PBKDF2("sha1", provider).makeKey (password, salt, 32, iterations);
- QCOMPARE( QCA::arrayToHex(passwordOut.toByteArray()),
- QString( "6b9cf26d45455a43a5b8bb276a403b39e7fe37a0c41e02c281ff3069e1e94f52" ) );
- }
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("pbkdf2(sha1)", provider)) {
+ QWARN(QString("PBKDF version 2 with SHA1 not supported for " + provider).toLocal8Bit());
+ } else {
+ // Not sure where this one came from...
+ {
+ QCA::InitializationVector salt(QCA::SecureArray("what do ya want for nothing?"));
+ QCA::SecureArray password("Jefe");
+ int iterations = 1000;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("6349e09cb6b8c1485cfa9780ee3264df"));
+ }
+
+ // RFC3962, Appendix B
+ {
+ QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn"));
+ QCA::SecureArray password("password");
+ int iterations = 1;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("cdedb5281bb2f801565a1122b2563515"));
+ passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 32, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("cdedb5281bb2f801565a1122b25635150ad1f7a04bb9f3a333ecc0e2e1f70837"));
+ }
+
+ // RFC3962, Appendix B
+ {
+ QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn"));
+ QCA::SecureArray password("password");
+ int iterations = 2;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("01dbee7f4a9e243e988b62c73cda935d"));
+ passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 32, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("01dbee7f4a9e243e988b62c73cda935da05378b93244ec8f48a99e61ad799d86"));
+ }
+
+ // RFC3962, Appendix B
+ {
+ QCA::InitializationVector salt(QCA::SecureArray("ATHENA.MIT.EDUraeburn"));
+ QCA::SecureArray password("password");
+ int iterations = 1200;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("5c08eb61fdf71e4e4ec3cf6ba1f5512b"));
+ passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 32, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("5c08eb61fdf71e4e4ec3cf6ba1f5512ba7e52ddbc5e5142f708a31e2e62b1e13"));
+ }
+
+ // RFC3211 and RFC3962, Appendix B
+ {
+ QCA::InitializationVector salt(QCA::hexToArray("1234567878563412"));
+ QCA::SecureArray password("password");
+ int iterations = 5;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("d1daa78615f287e6a1c8b120d7062a49"));
+ passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 32, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("d1daa78615f287e6a1c8b120d7062a493f98d203e6be49a6adf4fa574b6e64ee"));
+ passwordOut = QCA::PBKDF2().makeKey(password, salt, 8, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("d1daa78615f287e6"));
+ }
+
+ // RFC3962, Appendix B
+ {
+ QCA::InitializationVector salt(QCA::SecureArray("pass phrase equals block size"));
+ QCA::SecureArray password("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
+ int iterations = 1200;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("139c30c0966bc32ba55fdbf212530ac9"));
+ passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 32, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("139c30c0966bc32ba55fdbf212530ac9c5ec59f1a452f5cc9ad940fea0598ed1"));
+ }
+
+ // RFC3962, Appendix B
+ {
+ try {
+ QCA::InitializationVector salt(QCA::SecureArray("pass phrase exceeds block size"));
+ QCA::SecureArray password("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
+ int iterations = 1200;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("9ccad6d468770cd51b10e6a68721be61"));
+ passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 32, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("9ccad6d468770cd51b10e6a68721be611a8b4d282601db3b36be9246915ec82a"));
+ } catch (std::exception &) {
+ if (provider == "qca-botan") {
+ qDebug() << "You should use a later version of Botan";
+ } else {
+ QFAIL("exception");
+ }
+ }
+ }
+
+ // RFC3962, Appendix B
+ {
+ QCA::InitializationVector salt(QCA::SecureArray("EXAMPLE.COMpianist"));
+ QCA::SecureArray password(QCA::hexToArray("f09d849e"));
+ int iterations = 50;
+ QCA::SymmetricKey passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 16, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()), QString("6b9cf26d45455a43a5b8bb276a403b39"));
+ passwordOut = QCA::PBKDF2("sha1", provider).makeKey(password, salt, 32, iterations);
+ QCOMPARE(QCA::arrayToHex(passwordOut.toByteArray()),
+ QString("6b9cf26d45455a43a5b8bb276a403b39e7fe37a0c41e02c281ff3069e1e94f52"));
+ }
+ }
}
}
void KDFUnitTest::hkdfTests_data()
{
QTest::addColumn<QString>("secret"); // usually a password or passphrase
QTest::addColumn<QString>("salt"); // a salt or initialisation vector
QTest::addColumn<QString>("info"); // an additional info
QTest::addColumn<QString>("output"); // the key you get back
// RFC 5869, Appendix A
QTest::newRow("1") << QString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
- << QString("000102030405060708090a0b0c")
- << QString("f0f1f2f3f4f5f6f7f8f9")
- << QString("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865");
+ << QString("000102030405060708090a0b0c")
+ << QString("f0f1f2f3f4f5f6f7f8f9")
+ << QString("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865");
QTest::newRow("2") << QString("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f404142434445464748494a4b4c4d4e4f")
- << QString("606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf")
- << QString("b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
- << QString("b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87");
+ << QString("606162636465666768696a6b6c6d6e6f707172737475767778797a7b7c7d7e7f808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9fa0a1a2a3a4a5a6a7a8a9aaabacadaeaf")
+ << QString("b0b1b2b3b4b5b6b7b8b9babbbcbdbebfc0c1c2c3c4c5c6c7c8c9cacbcccdcecfd0d1d2d3d4d5d6d7d8d9dadbdcdddedfe0e1e2e3e4e5e6e7e8e9eaebecedeeeff0f1f2f3f4f5f6f7f8f9fafbfcfdfeff")
+ << QString("b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71cc30c58179ec3e87c14c01d5c1f3434f1d87");
QTest::newRow("3") << QString("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b")
- << QString()
- << QString()
- << QString("8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8");
+ << QString()
+ << QString()
+ << QString("8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8");
}
void KDFUnitTest::hkdfTests()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
//providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
QFETCH(QString, secret);
QFETCH(QString, salt);
QFETCH(QString, info);
QFETCH(QString, output);
- foreach(QString provider, providersToTest) {
- if(!QCA::isSupported("hkdf(sha256)", provider))
- QWARN(QString("HKDF with SHA256 not supported for "+provider).toLocal8Bit());
- else {
- QCA::SecureArray password = QCA::hexToArray( secret );
- QCA::InitializationVector saltv( QCA::hexToArray( salt ) );
- QCA::InitializationVector infov( QCA::hexToArray( info ) );
- QCA::SymmetricKey key = QCA::HKDF("sha256", provider).makeKey( password,
- saltv,
- infov,
- output.size() / 2 );
- QCOMPARE( QCA::arrayToHex( key.toByteArray() ), output );
-
- }
+ foreach (QString provider, providersToTest) {
+ if (!QCA::isSupported("hkdf(sha256)", provider)) {
+ QWARN(QString("HKDF with SHA256 not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::SecureArray password = QCA::hexToArray(secret);
+ QCA::InitializationVector saltv(QCA::hexToArray(salt));
+ QCA::InitializationVector infov(QCA::hexToArray(info));
+ QCA::SymmetricKey key = QCA::HKDF("sha256", provider).makeKey(password,
+ saltv,
+ infov,
+ output.size() / 2);
+ QCOMPARE(QCA::arrayToHex(key.toByteArray()), output);
+
+ }
}
}
QTEST_MAIN(KDFUnitTest)
#include "kdfunittest.moc"
diff --git a/unittest/keybundle/keybundle.cpp b/unittest/keybundle/keybundle.cpp
index 8e6de8c1..4bac37a3 100644
--- a/unittest/keybundle/keybundle.cpp
+++ b/unittest/keybundle/keybundle.cpp
@@ -1,198 +1,199 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class KeyBundleTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void nullBundle();
void fromFile();
void names();
void certChain();
void privKey();
void createBundle();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void KeyBundleTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void KeyBundleTest::cleanupTestCase()
{
QCA::unloadAllPlugins();
delete m_init;
}
void KeyBundleTest::nullBundle()
{
QCA::KeyBundle nullBundle;
- QVERIFY( nullBundle.isNull() );
- QCOMPARE( nullBundle.name(), QString() );
- QVERIFY( nullBundle.certificateChain().isEmpty() );
- QVERIFY( nullBundle.privateKey().isNull() );
+ QVERIFY(nullBundle.isNull());
+ QCOMPARE(nullBundle.name(), QString());
+ QVERIFY(nullBundle.certificateChain().isEmpty());
+ QVERIFY(nullBundle.privateKey().isNull());
QCA::KeyBundle nullCopy = nullBundle;
- QVERIFY( nullCopy.isNull() );
- QCOMPARE( nullCopy.name(), QString() );
- QVERIFY( nullCopy.certificateChain().isEmpty() );
- QVERIFY( nullCopy.privateKey().isNull() );
-
- QCA::KeyBundle nullAssigned( nullCopy );
- QVERIFY( nullAssigned.isNull() );
- QCOMPARE( nullAssigned.name(), QString() );
- QVERIFY( nullAssigned.certificateChain().isEmpty() );
- QVERIFY( nullAssigned.privateKey().isNull() );
+ QVERIFY(nullCopy.isNull());
+ QCOMPARE(nullCopy.name(), QString());
+ QVERIFY(nullCopy.certificateChain().isEmpty());
+ QVERIFY(nullCopy.privateKey().isNull());
+
+ QCA::KeyBundle nullAssigned(nullCopy);
+ QVERIFY(nullAssigned.isNull());
+ QCOMPARE(nullAssigned.name(), QString());
+ QVERIFY(nullAssigned.certificateChain().isEmpty());
+ QVERIFY(nullAssigned.privateKey().isNull());
}
void KeyBundleTest::fromFile()
{
- if ( QCA::isSupported("pkcs12") ) {
- // "start" is the passphrase, but you wouldn't normally
- // code it in like this
- QCA::KeyBundle userBundle( "user2good.p12", "start" );
- QCOMPARE( userBundle.isNull(), false );
- QCOMPARE( userBundle.name(), QString() );
- QCOMPARE( userBundle.certificateChain().isEmpty(), false );
- QCOMPARE( userBundle.privateKey().isNull(), false );
-
- QCA::KeyBundle userBundleCopy = userBundle;
- QCOMPARE( userBundleCopy.isNull(), false );
- QCOMPARE( userBundleCopy.name(), QString() );
- QCOMPARE( userBundleCopy.certificateChain().isEmpty(), false );
- QCOMPARE( userBundleCopy.privateKey().isNull(), false );
-
- QCA::KeyBundle userBundleAssign( userBundleCopy );
- QCOMPARE( userBundleAssign.isNull(), false );
- QCOMPARE( userBundleAssign.name(), QString() );
- QCOMPARE( userBundleAssign.certificateChain().isEmpty(), false );
- QCOMPARE( userBundleAssign.privateKey().isNull(), false );
+ if (QCA::isSupported("pkcs12")) {
+ // "start" is the passphrase, but you wouldn't normally
+ // code it in like this
+ QCA::KeyBundle userBundle("user2good.p12", "start");
+ QCOMPARE(userBundle.isNull(), false);
+ QCOMPARE(userBundle.name(), QString());
+ QCOMPARE(userBundle.certificateChain().isEmpty(), false);
+ QCOMPARE(userBundle.privateKey().isNull(), false);
+
+ QCA::KeyBundle userBundleCopy = userBundle;
+ QCOMPARE(userBundleCopy.isNull(), false);
+ QCOMPARE(userBundleCopy.name(), QString());
+ QCOMPARE(userBundleCopy.certificateChain().isEmpty(), false);
+ QCOMPARE(userBundleCopy.privateKey().isNull(), false);
+
+ QCA::KeyBundle userBundleAssign(userBundleCopy);
+ QCOMPARE(userBundleAssign.isNull(), false);
+ QCOMPARE(userBundleAssign.name(), QString());
+ QCOMPARE(userBundleAssign.certificateChain().isEmpty(), false);
+ QCOMPARE(userBundleAssign.privateKey().isNull(), false);
}
}
void KeyBundleTest::names()
{
- if ( QCA::isSupported("pkcs12") ) {
- QCA::KeyBundle serverBundle( "servergood2.p12", "start" );
- QCOMPARE( serverBundle.isNull(), false );
- QCOMPARE( serverBundle.name(), QString() );
+ if (QCA::isSupported("pkcs12")) {
+ QCA::KeyBundle serverBundle("servergood2.p12", "start");
+ QCOMPARE(serverBundle.isNull(), false);
+ QCOMPARE(serverBundle.name(), QString());
- serverBundle.setName( "Some Server Bundle" );
- QCOMPARE( serverBundle.name(), QString( "Some Server Bundle" ) );
+ serverBundle.setName("Some Server Bundle");
+ QCOMPARE(serverBundle.name(), QString("Some Server Bundle"));
}
}
void KeyBundleTest::certChain()
{
- if ( QCA::isSupported("pkcs12") ) {
- QCA::KeyBundle serverBundle( "servergood2.p12", "start" );
- QCOMPARE( serverBundle.isNull(), false );
- QCOMPARE( serverBundle.certificateChain().size(), 1 );
+ if (QCA::isSupported("pkcs12")) {
+ QCA::KeyBundle serverBundle("servergood2.p12", "start");
+ QCOMPARE(serverBundle.isNull(), false);
+ QCOMPARE(serverBundle.certificateChain().size(), 1);
}
}
void KeyBundleTest::privKey()
{
- if ( QCA::isSupported("pkcs12") ) {
- QCA::KeyBundle serverBundle( "servergood2.p12", "start" );
- QCOMPARE( serverBundle.isNull(), false );
- QCOMPARE( serverBundle.privateKey().isNull(), false );
+ if (QCA::isSupported("pkcs12")) {
+ QCA::KeyBundle serverBundle("servergood2.p12", "start");
+ QCOMPARE(serverBundle.isNull(), false);
+ QCOMPARE(serverBundle.privateKey().isNull(), false);
}
}
void KeyBundleTest::createBundle()
{
QCA::KeyBundle *newBundle = new QCA::KeyBundle;
- QVERIFY( newBundle->isNull() );
+ QVERIFY(newBundle->isNull());
- if ( !QCA::isSupported( "certificate" ) )
+ if (!QCA::isSupported("certificate")) {
return;
+ }
- QCA::Certificate ca( "RootCA2cert.pem" );
- QCOMPARE( ca.isNull(), false );
+ QCA::Certificate ca("RootCA2cert.pem");
+ QCOMPARE(ca.isNull(), false);
- QCA::Certificate primary( "user2goodcert.pem" );
- QCOMPARE( primary.isNull(), false );
+ QCA::Certificate primary("user2goodcert.pem");
+ QCOMPARE(primary.isNull(), false);
- QCA::PrivateKey key( "user2goodkey.pem" );
- QCOMPARE( key.isNull(), false );
+ QCA::PrivateKey key("user2goodkey.pem");
+ QCOMPARE(key.isNull(), false);
- QCA::CertificateChain chain( primary );
- chain.append( ca );
+ QCA::CertificateChain chain(primary);
+ chain.append(ca);
- newBundle->setCertificateChainAndKey( chain, key );
- newBundle->setName( "My New Key Bundle" );
+ newBundle->setCertificateChainAndKey(chain, key);
+ newBundle->setName("My New Key Bundle");
- QCOMPARE( newBundle->certificateChain(), chain );
- QCOMPARE( newBundle->privateKey(), key );
- QCOMPARE( newBundle->name(), QString( "My New Key Bundle" ) );
+ QCOMPARE(newBundle->certificateChain(), chain);
+ QCOMPARE(newBundle->privateKey(), key);
+ QCOMPARE(newBundle->name(), QString("My New Key Bundle"));
// Try round tripping the bundle
- foreach( const QCA::Provider *thisProvider, QCA::providers() ) {
- QString provider = thisProvider->name();
- if (QCA::isSupported( "pkcs12", provider ) ) {
- qDebug() << "Testing " << provider;
- QByteArray bundleArray = newBundle->toArray( "reel secrut", provider );
- QCOMPARE( bundleArray.isNull(), false );
-
- QCA::ConvertResult res;
- QCA::KeyBundle bundleFromArray = QCA::KeyBundle::fromArray( bundleArray, "reel secrut", &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
- QCOMPARE( bundleFromArray.isNull(), false );
- QCOMPARE( bundleFromArray.name(), QString( "My New Key Bundle" ) );
- QCOMPARE( bundleFromArray.certificateChain(), chain );
- QCOMPARE( bundleFromArray.privateKey(), key );
-
- QTemporaryFile tempFile;
- QVERIFY( tempFile.open() );
-
- bool result = newBundle->toFile( tempFile.fileName(), "file passphrase", provider );
- QVERIFY( result );
-
- QCA::KeyBundle bundleFromFile = QCA::KeyBundle::fromFile( tempFile.fileName(), "file passphrase", &res, provider );
- QCOMPARE( res, QCA::ConvertGood );
- QCOMPARE( bundleFromFile.isNull(), false );
- QCOMPARE( bundleFromFile.name(), QString( "My New Key Bundle" ) );
- QCOMPARE( bundleFromFile.certificateChain(), chain );
- QCOMPARE( bundleFromFile.privateKey(), key );
- }
+ foreach (const QCA::Provider *thisProvider, QCA::providers()) {
+ QString provider = thisProvider->name();
+ if (QCA::isSupported("pkcs12", provider)) {
+ qDebug() << "Testing " << provider;
+ QByteArray bundleArray = newBundle->toArray("reel secrut", provider);
+ QCOMPARE(bundleArray.isNull(), false);
+
+ QCA::ConvertResult res;
+ QCA::KeyBundle bundleFromArray = QCA::KeyBundle::fromArray(bundleArray, "reel secrut", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+ QCOMPARE(bundleFromArray.isNull(), false);
+ QCOMPARE(bundleFromArray.name(), QString("My New Key Bundle"));
+ QCOMPARE(bundleFromArray.certificateChain(), chain);
+ QCOMPARE(bundleFromArray.privateKey(), key);
+
+ QTemporaryFile tempFile;
+ QVERIFY(tempFile.open());
+
+ bool result = newBundle->toFile(tempFile.fileName(), "file passphrase", provider);
+ QVERIFY(result);
+
+ QCA::KeyBundle bundleFromFile = QCA::KeyBundle::fromFile(tempFile.fileName(), "file passphrase", &res, provider);
+ QCOMPARE(res, QCA::ConvertGood);
+ QCOMPARE(bundleFromFile.isNull(), false);
+ QCOMPARE(bundleFromFile.name(), QString("My New Key Bundle"));
+ QCOMPARE(bundleFromFile.certificateChain(), chain);
+ QCOMPARE(bundleFromFile.privateKey(), key);
+ }
}
}
QTEST_MAIN(KeyBundleTest)
#include "keybundle.moc"
diff --git a/unittest/keygenunittest/keygenunittest.cpp b/unittest/keygenunittest/keygenunittest.cpp
index 8e249514..33a3412d 100644
--- a/unittest/keygenunittest/keygenunittest.cpp
+++ b/unittest/keygenunittest/keygenunittest.cpp
@@ -1,170 +1,166 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class KeyGenUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testRSA();
void testDSA();
void testDH();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void KeyGenUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void KeyGenUnitTest::cleanupTestCase()
{
delete m_init;
}
-
void KeyGenUnitTest::testRSA()
{
QCA::KeyGenerator keygen;
- QCOMPARE( keygen.isBusy(), false );
- QCOMPARE( keygen.blockingEnabled(), true );
+ QCOMPARE(keygen.isBusy(), false);
+ QCOMPARE(keygen.blockingEnabled(), true);
- if(!QCA::isSupported("pkey") ||
- !QCA::PKey::supportedTypes().contains(QCA::PKey::RSA) ||
- !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA))
+ if (!QCA::isSupported("pkey") ||
+ !QCA::PKey::supportedTypes().contains(QCA::PKey::RSA) ||
+ !QCA::PKey::supportedIOTypes().contains(QCA::PKey::RSA))
#if QT_VERSION >= 0x050000
QSKIP("RSA not supported!");
#else
QSKIP("RSA not supported!", SkipAll);
#endif
- QCA::PrivateKey priv1 = keygen.createRSA( 1024, 65537 );
+ QCA::PrivateKey priv1 = keygen.createRSA(1024, 65537);
QCA::RSAPrivateKey rsa1 = priv1.toRSA();
- QCOMPARE( rsa1.isNull(), false );
- QCOMPARE( rsa1.e(), QCA::BigInteger(65537) );
- QCOMPARE( rsa1.bitSize(), 1024);
+ QCOMPARE(rsa1.isNull(), false);
+ QCOMPARE(rsa1.e(), QCA::BigInteger(65537));
+ QCOMPARE(rsa1.bitSize(), 1024);
- priv1 = keygen.createRSA( 512, 17 );
+ priv1 = keygen.createRSA(512, 17);
rsa1 = priv1.toRSA();
- QCOMPARE( rsa1.isNull(), false );
- QCOMPARE( rsa1.e(), QCA::BigInteger(17) );
- QCOMPARE( rsa1.bitSize(), 512);
+ QCOMPARE(rsa1.isNull(), false);
+ QCOMPARE(rsa1.e(), QCA::BigInteger(17));
+ QCOMPARE(rsa1.bitSize(), 512);
- priv1 = keygen.createRSA( 512, 3 );
+ priv1 = keygen.createRSA(512, 3);
rsa1 = priv1.toRSA();
- QCOMPARE( rsa1.isNull(), false );
- QCOMPARE( rsa1.e(), QCA::BigInteger(3) );
- QCOMPARE( rsa1.bitSize(), 512);
+ QCOMPARE(rsa1.isNull(), false);
+ QCOMPARE(rsa1.e(), QCA::BigInteger(3));
+ QCOMPARE(rsa1.bitSize(), 512);
}
void KeyGenUnitTest::testDSA()
{
QCA::KeyGenerator keygen;
- QCOMPARE( keygen.isBusy(), false );
- QCOMPARE( keygen.blockingEnabled(), true );
+ QCOMPARE(keygen.isBusy(), false);
+ QCOMPARE(keygen.blockingEnabled(), true);
- if(!QCA::isSupported("pkey") ||
- !QCA::PKey::supportedTypes().contains(QCA::PKey::DSA) ||
- !QCA::PKey::supportedIOTypes().contains(QCA::PKey::DSA))
+ if (!QCA::isSupported("pkey") ||
+ !QCA::PKey::supportedTypes().contains(QCA::PKey::DSA) ||
+ !QCA::PKey::supportedIOTypes().contains(QCA::PKey::DSA))
#if QT_VERSION >= 0x050000
- QSKIP("DSA not supported!");
+ QSKIP("DSA not supported!");
#else
- QSKIP("DSA not supported!", SkipAll);
+ QSKIP("DSA not supported!", SkipAll);
#endif
- QCA::DLGroup group;
- QCA::PrivateKey priv2;
- QCA::DSAPrivateKey dsa1;
-
- if (QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_512))
- {
- group = keygen.createDLGroup( QCA::DSA_512 );
- priv2 = keygen.createDSA( group );
- dsa1 = priv2.toDSA();
- QCOMPARE( dsa1.isNull(), false );
- QCOMPARE( dsa1.bitSize(), 512 );
- }
-
- if (QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_768))
- {
- group = keygen.createDLGroup( QCA::DSA_768 );
- priv2 = keygen.createDSA( group );
- dsa1 = priv2.toDSA();
- QCOMPARE( dsa1.isNull(), false );
- QCOMPARE( dsa1.bitSize(), 768 );
- }
-
- if (QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_1024))
- {
- group = keygen.createDLGroup( QCA::DSA_1024 );
- priv2 = keygen.createDSA( group );
- dsa1 = priv2.toDSA();
- QCOMPARE( dsa1.isNull(), false );
- QCOMPARE( dsa1.bitSize(), 1024 );
- }
+ QCA::DLGroup group;
+ QCA::PrivateKey priv2;
+ QCA::DSAPrivateKey dsa1;
+
+ if (QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_512)) {
+ group = keygen.createDLGroup(QCA::DSA_512);
+ priv2 = keygen.createDSA(group);
+ dsa1 = priv2.toDSA();
+ QCOMPARE(dsa1.isNull(), false);
+ QCOMPARE(dsa1.bitSize(), 512);
+ }
+
+ if (QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_768)) {
+ group = keygen.createDLGroup(QCA::DSA_768);
+ priv2 = keygen.createDSA(group);
+ dsa1 = priv2.toDSA();
+ QCOMPARE(dsa1.isNull(), false);
+ QCOMPARE(dsa1.bitSize(), 768);
+ }
+
+ if (QCA::DLGroup::supportedGroupSets().contains(QCA::DSA_1024)) {
+ group = keygen.createDLGroup(QCA::DSA_1024);
+ priv2 = keygen.createDSA(group);
+ dsa1 = priv2.toDSA();
+ QCOMPARE(dsa1.isNull(), false);
+ QCOMPARE(dsa1.bitSize(), 1024);
+ }
}
void KeyGenUnitTest::testDH()
{
QCA::KeyGenerator keygen;
- QCOMPARE( keygen.isBusy(), false );
- QCOMPARE( keygen.blockingEnabled(), true );
+ QCOMPARE(keygen.isBusy(), false);
+ QCOMPARE(keygen.blockingEnabled(), true);
- if(!QCA::isSupported("pkey") ||
- !QCA::PKey::supportedTypes().contains(QCA::PKey::DH) ||
- !QCA::PKey::supportedIOTypes().contains(QCA::PKey::DH))
+ if (!QCA::isSupported("pkey") ||
+ !QCA::PKey::supportedTypes().contains(QCA::PKey::DH) ||
+ !QCA::PKey::supportedIOTypes().contains(QCA::PKey::DH))
#if QT_VERSION >= 0x050000
- QSKIP("DH not supported!");
+ QSKIP("DH not supported!");
#else
- QSKIP("DH not supported!", SkipAll);
+ QSKIP("DH not supported!", SkipAll);
#endif
- QCA::DLGroup group = keygen.createDLGroup( QCA::IETF_1024 );
- QCA::PrivateKey priv3 = keygen.createDH( group );
+ QCA::DLGroup group = keygen.createDLGroup(QCA::IETF_1024);
+ QCA::PrivateKey priv3 = keygen.createDH(group);
QCA::DHPrivateKey dh1 = priv3.toDH();
- QCOMPARE( dh1.isNull(), false );
- QCOMPARE( dh1.bitSize(), 1024 );
+ QCOMPARE(dh1.isNull(), false);
+ QCOMPARE(dh1.bitSize(), 1024);
- group = keygen.createDLGroup( QCA::IETF_2048 );
- priv3 = keygen.createDH( group );
+ group = keygen.createDLGroup(QCA::IETF_2048);
+ priv3 = keygen.createDH(group);
dh1 = priv3.toDH();
- QCOMPARE( dh1.isNull(), false );
- QCOMPARE( dh1.bitSize(), 2048 );
+ QCOMPARE(dh1.isNull(), false);
+ QCOMPARE(dh1.bitSize(), 2048);
}
QTEST_MAIN(KeyGenUnitTest)
#include "keygenunittest.moc"
diff --git a/unittest/keylengthunittest/keylengthunittest.cpp b/unittest/keylengthunittest/keylengthunittest.cpp
index 6f871469..73cf0c0c 100644
--- a/unittest/keylengthunittest/keylengthunittest.cpp
+++ b/unittest/keylengthunittest/keylengthunittest.cpp
@@ -1,79 +1,79 @@
/**
* Copyright (C) 2004, 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#include <limits>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class KeyLengthUnitTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void doTest();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void KeyLengthUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void KeyLengthUnitTest::cleanupTestCase()
{
QCA::unloadAllPlugins();
delete m_init;
}
void KeyLengthUnitTest::doTest()
{
- QCA::KeyLength keylen1( 0, 0, 0 );
- QCOMPARE( keylen1.minimum(), 0 );
- QCOMPARE( keylen1.maximum(), 0 );
- QCOMPARE( keylen1.multiple(), 0 );
+ QCA::KeyLength keylen1(0, 0, 0);
+ QCOMPARE(keylen1.minimum(), 0);
+ QCOMPARE(keylen1.maximum(), 0);
+ QCOMPARE(keylen1.multiple(), 0);
- QCA::KeyLength keylen2( 3, 40, 1 );
- QCOMPARE( keylen2.minimum(), 3 );
- QCOMPARE( keylen2.maximum(), 40 );
- QCOMPARE( keylen2.multiple(), 1 );
+ QCA::KeyLength keylen2(3, 40, 1);
+ QCOMPARE(keylen2.minimum(), 3);
+ QCOMPARE(keylen2.maximum(), 40);
+ QCOMPARE(keylen2.multiple(), 1);
- QCA::KeyLength keylen3( 1, INT_MAX, 1 );
- QCOMPARE( keylen3.minimum(), 1 );
- QCOMPARE( keylen3.maximum(), INT_MAX );
- QCOMPARE( keylen3.multiple(), 1 );
+ QCA::KeyLength keylen3(1, INT_MAX, 1);
+ QCOMPARE(keylen3.minimum(), 1);
+ QCOMPARE(keylen3.maximum(), INT_MAX);
+ QCOMPARE(keylen3.multiple(), 1);
}
QTEST_MAIN(KeyLengthUnitTest)
#include "keylengthunittest.moc"
diff --git a/unittest/keystore/keystore.cpp b/unittest/keystore/keystore.cpp
index 114dcb4a..7052d1ac 100644
--- a/unittest/keystore/keystore.cpp
+++ b/unittest/keystore/keystore.cpp
@@ -1,76 +1,76 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class KeyStore : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void nullKeystore();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void KeyStore::initTestCase()
{
m_init = new QCA::Initializer;
}
void KeyStore::cleanupTestCase()
{
QCA::unloadAllPlugins();
delete m_init;
}
void KeyStore::nullKeystore()
{
QCA::KeyStoreManager manager;
- if ( QCA::isSupported( "keystore" ) ) {
- QCA::KeyStore nullStore( QString( "null store" ), &manager );
- QVERIFY( nullStore.isValid() );
+ if (QCA::isSupported("keystore")) {
+ QCA::KeyStore nullStore(QString("null store"), &manager);
+ QVERIFY(nullStore.isValid());
- QVERIFY( nullStore.entryList().isEmpty() );
+ QVERIFY(nullStore.entryList().isEmpty());
- QCOMPARE( nullStore.type(), QCA::KeyStore::User);
+ QCOMPARE(nullStore.type(), QCA::KeyStore::User);
- QCOMPARE( nullStore.id(), QString( "null store" ) );
- QCOMPARE( nullStore.holdsTrustedCertificates(), false );
- QCOMPARE( nullStore.holdsIdentities(), false );
- QCOMPARE( nullStore.holdsPGPPublicKeys(), false );
+ QCOMPARE(nullStore.id(), QString("null store"));
+ QCOMPARE(nullStore.holdsTrustedCertificates(), false);
+ QCOMPARE(nullStore.holdsIdentities(), false);
+ QCOMPARE(nullStore.holdsPGPPublicKeys(), false);
}
}
QTEST_MAIN(KeyStore)
#include "keystore.moc"
diff --git a/unittest/logger/loggerunittest.cpp b/unittest/logger/loggerunittest.cpp
index 26f9d96a..efd649ad 100644
--- a/unittest/logger/loggerunittest.cpp
+++ b/unittest/logger/loggerunittest.cpp
@@ -1,292 +1,291 @@
/**
* Copyright (C) 2007 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class LoggerUnitTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void basicSetup();
void logText1();
void logText2();
void logBlob();
void logLevel();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
class NullLogger : public QCA::AbstractLogDevice
{
public:
- NullLogger() : QCA::AbstractLogDevice( "null logger" )
+ NullLogger() : QCA::AbstractLogDevice("null logger")
{}
~NullLogger()
{}
};
class LastLogger : public QCA::AbstractLogDevice
{
public:
- LastLogger() : QCA::AbstractLogDevice( "last logger" )
+ LastLogger() : QCA::AbstractLogDevice("last logger")
{}
~LastLogger()
{}
- void logTextMessage( const QString &message, enum QCA::Logger::Severity severity )
+ void logTextMessage(const QString &message, enum QCA::Logger::Severity severity)
{
m_lastMessage = message;
m_messageSeverity = severity;
}
QString lastMessage() const
{
return m_lastMessage;
}
- void logBinaryMessage( const QByteArray &blob, enum QCA::Logger::Severity severity )
+ void logBinaryMessage(const QByteArray &blob, enum QCA::Logger::Severity severity)
{
m_lastBlob = blob;
m_blobSeverity = severity;
}
QByteArray lastBlob() const
{
return m_lastBlob;
}
QCA::Logger::Severity lastMessageSeverity() const
{
return m_messageSeverity;
}
QCA::Logger::Severity lastBlobSeverity() const
{
return m_blobSeverity;
}
private:
QString m_lastMessage;
QByteArray m_lastBlob;
QCA::Logger::Severity m_messageSeverity;
QCA::Logger::Severity m_blobSeverity;
};
void LoggerUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void LoggerUnitTest::cleanupTestCase()
{
QCA::unloadAllPlugins();
delete m_init;
}
void LoggerUnitTest::basicSetup()
{
QCA::Logger *logSystem = QCA::logger();
- QCOMPARE( logSystem->currentLogDevices().count(), 0 );
+ QCOMPARE(logSystem->currentLogDevices().count(), 0);
- logSystem->setLevel (QCA::Logger::Debug);
- QCOMPARE( logSystem->level (), QCA::Logger::Debug );
+ logSystem->setLevel(QCA::Logger::Debug);
+ QCOMPARE(logSystem->level(), QCA::Logger::Debug);
NullLogger *nullLogger = new NullLogger;
- logSystem->registerLogDevice( nullLogger );
- QCOMPARE( logSystem->currentLogDevices().count(), 1 );
- QVERIFY( logSystem->currentLogDevices().contains( "null logger" ) );
- logSystem->unregisterLogDevice( "null logger" );
- QCOMPARE( logSystem->currentLogDevices().count(), 0 );
+ logSystem->registerLogDevice(nullLogger);
+ QCOMPARE(logSystem->currentLogDevices().count(), 1);
+ QVERIFY(logSystem->currentLogDevices().contains("null logger"));
+ logSystem->unregisterLogDevice("null logger");
+ QCOMPARE(logSystem->currentLogDevices().count(), 0);
delete nullLogger;
}
void LoggerUnitTest::logText1()
{
QCA::Logger *logSystem = QCA::logger();
- logSystem->logTextMessage( "Sending with no recipients" );
+ logSystem->logTextMessage("Sending with no recipients");
LastLogger *lastlogger = new LastLogger;
- logSystem->registerLogDevice( lastlogger );
- QCOMPARE( logSystem->currentLogDevices().count(), 1 );
- QVERIFY( logSystem->currentLogDevices().contains( "last logger" ) );
+ logSystem->registerLogDevice(lastlogger);
+ QCOMPARE(logSystem->currentLogDevices().count(), 1);
+ QVERIFY(logSystem->currentLogDevices().contains("last logger"));
- logSystem->logTextMessage( "Sending to system, checking for log device" );
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending to system, checking for log device" ) );
- QCOMPARE( lastlogger->lastMessageSeverity(), QCA::Logger::Information );
+ logSystem->logTextMessage("Sending to system, checking for log device");
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending to system, checking for log device"));
+ QCOMPARE(lastlogger->lastMessageSeverity(), QCA::Logger::Information);
- logSystem->logTextMessage( "Sending at Error severity", QCA::Logger::Error );
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending at Error severity" ) );
- QCOMPARE( lastlogger->lastMessageSeverity(), QCA::Logger::Error );
+ logSystem->logTextMessage("Sending at Error severity", QCA::Logger::Error);
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending at Error severity"));
+ QCOMPARE(lastlogger->lastMessageSeverity(), QCA::Logger::Error);
LastLogger *lastlogger2 = new LastLogger;
- logSystem->registerLogDevice( lastlogger2 );
- QCOMPARE( logSystem->currentLogDevices().count(), 2 );
- QVERIFY( logSystem->currentLogDevices().contains( "last logger" ) );
+ logSystem->registerLogDevice(lastlogger2);
+ QCOMPARE(logSystem->currentLogDevices().count(), 2);
+ QVERIFY(logSystem->currentLogDevices().contains("last logger"));
- logSystem->logTextMessage( "Sending to system, checking for two log devices" );
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending to system, checking for two log devices" ) );
- QCOMPARE( lastlogger->lastMessageSeverity(), QCA::Logger::Information );
- QCOMPARE( lastlogger2->lastMessage(),
- QString( "Sending to system, checking for two log devices" ) );
- QCOMPARE( lastlogger2->lastMessageSeverity(), QCA::Logger::Information );
+ logSystem->logTextMessage("Sending to system, checking for two log devices");
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending to system, checking for two log devices"));
+ QCOMPARE(lastlogger->lastMessageSeverity(), QCA::Logger::Information);
+ QCOMPARE(lastlogger2->lastMessage(),
+ QString("Sending to system, checking for two log devices"));
+ QCOMPARE(lastlogger2->lastMessageSeverity(), QCA::Logger::Information);
- logSystem->unregisterLogDevice( "last logger" ); // this will remove them both
+ logSystem->unregisterLogDevice("last logger"); // this will remove them both
- QCOMPARE( logSystem->currentLogDevices().count(), 0 );
+ QCOMPARE(logSystem->currentLogDevices().count(), 0);
delete lastlogger;
delete lastlogger2;
}
-
// same as above, but use convenience routine.
void LoggerUnitTest::logText2()
{
- QCA_logTextMessage ( "Sending with no recipients", QCA::Logger::Notice );
+ QCA_logTextMessage("Sending with no recipients", QCA::Logger::Notice);
LastLogger *lastlogger = new LastLogger;
QCA::Logger *logSystem = QCA::logger();
- logSystem->registerLogDevice( lastlogger );
- QCOMPARE( logSystem->currentLogDevices().count(), 1 );
- QVERIFY( logSystem->currentLogDevices().contains( "last logger" ) );
+ logSystem->registerLogDevice(lastlogger);
+ QCOMPARE(logSystem->currentLogDevices().count(), 1);
+ QVERIFY(logSystem->currentLogDevices().contains("last logger"));
- QCA_logTextMessage ( "Sending to system, checking for log device", QCA::Logger::Information );
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending to system, checking for log device" ) );
- QCOMPARE( lastlogger->lastMessageSeverity(), QCA::Logger::Information );
+ QCA_logTextMessage("Sending to system, checking for log device", QCA::Logger::Information);
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending to system, checking for log device"));
+ QCOMPARE(lastlogger->lastMessageSeverity(), QCA::Logger::Information);
- QCA_logTextMessage ( "Sending at Error severity", QCA::Logger::Error );
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending at Error severity" ) );
- QCOMPARE( lastlogger->lastMessageSeverity(), QCA::Logger::Error );
+ QCA_logTextMessage("Sending at Error severity", QCA::Logger::Error);
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending at Error severity"));
+ QCOMPARE(lastlogger->lastMessageSeverity(), QCA::Logger::Error);
LastLogger *lastlogger2 = new LastLogger;
- logSystem->registerLogDevice( lastlogger2 );
- QCOMPARE( logSystem->currentLogDevices().count(), 2 );
- QVERIFY( logSystem->currentLogDevices().contains( "last logger" ) );
+ logSystem->registerLogDevice(lastlogger2);
+ QCOMPARE(logSystem->currentLogDevices().count(), 2);
+ QVERIFY(logSystem->currentLogDevices().contains("last logger"));
- QCA_logTextMessage ( "Sending to system, checking for two log devices", QCA::Logger::Information );
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending to system, checking for two log devices" ) );
- QCOMPARE( lastlogger->lastMessageSeverity(), QCA::Logger::Information );
- QCOMPARE( lastlogger2->lastMessage(),
- QString( "Sending to system, checking for two log devices" ) );
- QCOMPARE( lastlogger2->lastMessageSeverity(), QCA::Logger::Information );
+ QCA_logTextMessage("Sending to system, checking for two log devices", QCA::Logger::Information);
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending to system, checking for two log devices"));
+ QCOMPARE(lastlogger->lastMessageSeverity(), QCA::Logger::Information);
+ QCOMPARE(lastlogger2->lastMessage(),
+ QString("Sending to system, checking for two log devices"));
+ QCOMPARE(lastlogger2->lastMessageSeverity(), QCA::Logger::Information);
- logSystem->unregisterLogDevice( "last logger" ); // this will remove them both
+ logSystem->unregisterLogDevice("last logger"); // this will remove them both
- QCOMPARE( logSystem->currentLogDevices().count(), 0 );
+ QCOMPARE(logSystem->currentLogDevices().count(), 0);
delete lastlogger;
delete lastlogger2;
}
void LoggerUnitTest::logBlob()
{
QCA::Logger *logSystem = QCA::logger();
- QCOMPARE( logSystem->currentLogDevices().count(), 0 );
+ QCOMPARE(logSystem->currentLogDevices().count(), 0);
- QByteArray test( "abcd\x34" );
- logSystem->logBinaryMessage( test );
+ QByteArray test("abcd\x34");
+ logSystem->logBinaryMessage(test);
LastLogger *lastlogger = new LastLogger;
- logSystem->registerLogDevice( lastlogger );
- QCOMPARE( logSystem->currentLogDevices().count(), 1 );
- QVERIFY( logSystem->currentLogDevices().contains( "last logger" ) );
+ logSystem->registerLogDevice(lastlogger);
+ QCOMPARE(logSystem->currentLogDevices().count(), 1);
+ QVERIFY(logSystem->currentLogDevices().contains("last logger"));
- logSystem->logBinaryMessage( test );
- QCOMPARE( lastlogger->lastBlob(), test );
- QCOMPARE( lastlogger->lastBlobSeverity(), QCA::Logger::Information );
+ logSystem->logBinaryMessage(test);
+ QCOMPARE(lastlogger->lastBlob(), test);
+ QCOMPARE(lastlogger->lastBlobSeverity(), QCA::Logger::Information);
- logSystem->logBinaryMessage( test, QCA::Logger::Critical );
- QCOMPARE( lastlogger->lastBlob(), test );
- QCOMPARE( lastlogger->lastBlobSeverity(), QCA::Logger::Critical );
+ logSystem->logBinaryMessage(test, QCA::Logger::Critical);
+ QCOMPARE(lastlogger->lastBlob(), test);
+ QCOMPARE(lastlogger->lastBlobSeverity(), QCA::Logger::Critical);
LastLogger *lastlogger2 = new LastLogger;
- logSystem->registerLogDevice( lastlogger2 );
- QCOMPARE( logSystem->currentLogDevices().count(), 2 );
- QVERIFY( logSystem->currentLogDevices().contains( "last logger" ) );
+ logSystem->registerLogDevice(lastlogger2);
+ QCOMPARE(logSystem->currentLogDevices().count(), 2);
+ QVERIFY(logSystem->currentLogDevices().contains("last logger"));
test += test;
- logSystem->logBinaryMessage( test );
- QCOMPARE( lastlogger->lastBlob(), test );
- QCOMPARE( lastlogger->lastBlobSeverity(), QCA::Logger::Information );
- QCOMPARE( lastlogger2->lastBlob(), test );
- QCOMPARE( lastlogger2->lastBlobSeverity(), QCA::Logger::Information );
+ logSystem->logBinaryMessage(test);
+ QCOMPARE(lastlogger->lastBlob(), test);
+ QCOMPARE(lastlogger->lastBlobSeverity(), QCA::Logger::Information);
+ QCOMPARE(lastlogger2->lastBlob(), test);
+ QCOMPARE(lastlogger2->lastBlobSeverity(), QCA::Logger::Information);
- logSystem->unregisterLogDevice( "last logger" ); // this will remove them both
+ logSystem->unregisterLogDevice("last logger"); // this will remove them both
- QCOMPARE( logSystem->currentLogDevices().count(), 0 );
+ QCOMPARE(logSystem->currentLogDevices().count(), 0);
delete lastlogger;
delete lastlogger2;
}
void LoggerUnitTest::logLevel()
{
QCA::Logger *logSystem = QCA::logger();
LastLogger *lastlogger = new LastLogger;
- logSystem->registerLogDevice( lastlogger );
+ logSystem->registerLogDevice(lastlogger);
- logSystem->setLevel (QCA::Logger::Error);
- QCOMPARE( logSystem->level (), QCA::Logger::Error );
+ logSystem->setLevel(QCA::Logger::Error);
+ QCOMPARE(logSystem->level(), QCA::Logger::Error);
- QCA_logTextMessage ( "Sending to system, checking that it is filtered out", QCA::Logger::Information );
+ QCA_logTextMessage("Sending to system, checking that it is filtered out", QCA::Logger::Information);
QEXPECT_FAIL("", "Should fail", Continue);
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending to system, checking that it is filtered out" ) );
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending to system, checking that it is filtered out"));
- QCA_logTextMessage ( "Sending to system, checking that it is not filtered out", QCA::Logger::Error );
- QCOMPARE( lastlogger->lastMessage(),
- QString( "Sending to system, checking that it is not filtered out" ) );
+ QCA_logTextMessage("Sending to system, checking that it is not filtered out", QCA::Logger::Error);
+ QCOMPARE(lastlogger->lastMessage(),
+ QString("Sending to system, checking that it is not filtered out"));
- logSystem->setLevel (QCA::Logger::Debug);
+ logSystem->setLevel(QCA::Logger::Debug);
delete lastlogger;
}
QTEST_MAIN(LoggerUnitTest)
#include "loggerunittest.moc"
diff --git a/unittest/macunittest/macunittest.cpp b/unittest/macunittest/macunittest.cpp
index e4f1ef5b..40ba3093 100644
--- a/unittest/macunittest/macunittest.cpp
+++ b/unittest/macunittest/macunittest.cpp
@@ -1,620 +1,637 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class MACUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void HMACMD5();
void HMACSHA1();
void HMACSHA256();
void HMACSHA224();
void HMACSHA384();
void HMACSHA512();
void HMACRMD160();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
-
void MACUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void MACUnitTest::cleanupTestCase()
{
delete m_init;
}
void MACUnitTest::HMACMD5()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "hmac(md5)", provider ) )
- QWARN( QString( "HMAC(MD5) not supported for "+provider).toLocal8Bit() );
- else {
- QCA::MessageAuthenticationCode md5hmacLenTest( "hmac(md5)", QCA::SymmetricKey(), provider );
- QCOMPARE( md5hmacLenTest.validKeyLength( 0 ), true );
- QCOMPARE( md5hmacLenTest.validKeyLength( 1 ), true );
- QCOMPARE( md5hmacLenTest.validKeyLength( 848888 ), true );
- QCOMPARE( md5hmacLenTest.validKeyLength( -2 ), false );
-
- // These tests are from RFC2202, Section 2.
- // The first three are also in the Appendix to RFC2104
- QCA::MessageAuthenticationCode md5hmac1( "hmac(md5)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key1( QCA::SecureArray( "Jefe" ) );
- md5hmac1.setup( key1 );
- QCA::SecureArray data1( "what do ya want for nothing?" );
- md5hmac1.update( data1 );
- QCOMPARE( QCA::arrayToHex( md5hmac1.final().toByteArray() ), QString( "750c783e6ab0b503eaa86e310a5db738" ) );
-
- QCA::MessageAuthenticationCode md5hmac2( "hmac(md5)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key2( QCA::hexToArray( "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" ) );
- md5hmac2.setup( key2 );
- QCA::SecureArray data2 = QCA::SecureArray( "Hi There" );
- md5hmac2.update( data2 );
- QCOMPARE( QCA::arrayToHex( md5hmac2.final().toByteArray() ), QString( "9294727a3638bb1c13f48ef8158bfc9d" ) );
-
- // test reuse
- md5hmac2.clear();
- QCA::SymmetricKey key3( QCA::hexToArray( "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" ) );
- md5hmac2.setup ( key3 );
- QCA::SecureArray data3( 50 );
- for ( int i = 0; i < data3.size(); i++ )
- data3[ i ] = (char)0xDD;
- md5hmac2.update( data3 );
- QCOMPARE( QCA::arrayToHex( md5hmac2.final().toByteArray() ), QString( "56be34521d144c88dbb8c733f0e8b3f6" ) );
-
- QCA::SymmetricKey key4( QCA::hexToArray( "0102030405060708090a0b0c0d0e0f10111213141516171819") );
- QCA::MessageAuthenticationCode md5hmac4( "hmac(md5)", key4, provider );
- QCA::SecureArray data4( 50 );
- for (int i = 0; i < data4.size(); i++ )
- data4[ i ] = (char)0xcd;
- md5hmac4.update( data4 );
- QCOMPARE( QCA::arrayToHex( md5hmac4.final().toByteArray() ), QString( "697eaf0aca3a3aea3a75164746ffaa79" ) );
-
- QCA::MessageAuthenticationCode md5hmac5( "hmac(md5)", QCA::SecureArray() );
- QCA::SymmetricKey key5( QCA::hexToArray( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ) );
- md5hmac5.setup( key5 );
- QCA::SecureArray data5( "Test With Truncation" );
- md5hmac5.update( data5 );
- QCOMPARE( QCA::arrayToHex( md5hmac5.final().toByteArray() ), QString( "56461ef2342edc00f9bab995690efd4c" ) );
-
- QCA::MessageAuthenticationCode md5hmac6( "hmac(md5)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key6( 80 );
- for (int i = 0; i < key6.size(); i++)
- key6[ i ] = (char)0xaa;
- md5hmac6.setup( key6 );
- QCA::SecureArray data6( "Test Using Larger Than Block-Size Key - Hash Key First" );
- md5hmac6.update( data6 );
- QCOMPARE( QCA::arrayToHex( md5hmac6.final().toByteArray() ), QString( "6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd" ) );
-
- md5hmac6.clear(); // reuse the same key
- QCA::SecureArray data7( "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data" );
- md5hmac6.update( data7 );
- QCOMPARE( QCA::arrayToHex( md5hmac6.final().toByteArray() ), QString( "6f630fad67cda0ee1fb1f562db3aa53e" ) );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("hmac(md5)", provider)) {
+ QWARN(QString("HMAC(MD5) not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::MessageAuthenticationCode md5hmacLenTest("hmac(md5)", QCA::SymmetricKey(), provider);
+ QCOMPARE(md5hmacLenTest.validKeyLength(0), true);
+ QCOMPARE(md5hmacLenTest.validKeyLength(1), true);
+ QCOMPARE(md5hmacLenTest.validKeyLength(848888), true);
+ QCOMPARE(md5hmacLenTest.validKeyLength(-2), false);
+
+ // These tests are from RFC2202, Section 2.
+ // The first three are also in the Appendix to RFC2104
+ QCA::MessageAuthenticationCode md5hmac1("hmac(md5)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key1(QCA::SecureArray("Jefe"));
+ md5hmac1.setup(key1);
+ QCA::SecureArray data1("what do ya want for nothing?");
+ md5hmac1.update(data1);
+ QCOMPARE(QCA::arrayToHex(md5hmac1.final().toByteArray()), QString("750c783e6ab0b503eaa86e310a5db738"));
+
+ QCA::MessageAuthenticationCode md5hmac2("hmac(md5)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key2(QCA::hexToArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
+ md5hmac2.setup(key2);
+ QCA::SecureArray data2 = QCA::SecureArray("Hi There");
+ md5hmac2.update(data2);
+ QCOMPARE(QCA::arrayToHex(md5hmac2.final().toByteArray()), QString("9294727a3638bb1c13f48ef8158bfc9d"));
+
+ // test reuse
+ md5hmac2.clear();
+ QCA::SymmetricKey key3(QCA::hexToArray("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
+ md5hmac2.setup(key3);
+ QCA::SecureArray data3(50);
+ for (int i = 0; i < data3.size(); i++) {
+ data3[ i ] = (char)0xDD;
+ }
+ md5hmac2.update(data3);
+ QCOMPARE(QCA::arrayToHex(md5hmac2.final().toByteArray()), QString("56be34521d144c88dbb8c733f0e8b3f6"));
+
+ QCA::SymmetricKey key4(QCA::hexToArray("0102030405060708090a0b0c0d0e0f10111213141516171819"));
+ QCA::MessageAuthenticationCode md5hmac4("hmac(md5)", key4, provider);
+ QCA::SecureArray data4(50);
+ for (int i = 0; i < data4.size(); i++) {
+ data4[ i ] = (char)0xcd;
+ }
+ md5hmac4.update(data4);
+ QCOMPARE(QCA::arrayToHex(md5hmac4.final().toByteArray()), QString("697eaf0aca3a3aea3a75164746ffaa79"));
+
+ QCA::MessageAuthenticationCode md5hmac5("hmac(md5)", QCA::SecureArray());
+ QCA::SymmetricKey key5(QCA::hexToArray("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"));
+ md5hmac5.setup(key5);
+ QCA::SecureArray data5("Test With Truncation");
+ md5hmac5.update(data5);
+ QCOMPARE(QCA::arrayToHex(md5hmac5.final().toByteArray()), QString("56461ef2342edc00f9bab995690efd4c"));
+
+ QCA::MessageAuthenticationCode md5hmac6("hmac(md5)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key6(80);
+ for (int i = 0; i < key6.size(); i++) {
+ key6[ i ] = (char)0xaa;
+ }
+ md5hmac6.setup(key6);
+ QCA::SecureArray data6("Test Using Larger Than Block-Size Key - Hash Key First");
+ md5hmac6.update(data6);
+ QCOMPARE(QCA::arrayToHex(md5hmac6.final().toByteArray()), QString("6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd"));
+
+ md5hmac6.clear(); // reuse the same key
+ QCA::SecureArray data7("Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data");
+ md5hmac6.update(data7);
+ QCOMPARE(QCA::arrayToHex(md5hmac6.final().toByteArray()), QString("6f630fad67cda0ee1fb1f562db3aa53e"));
+ }
}
}
-
void MACUnitTest::HMACSHA256()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "hmac(sha256)", provider ) )
- QWARN( QString( "HMAC(SHA256) not supported for "+provider).toLocal8Bit() );
- else {
- QCA::MessageAuthenticationCode hmacLenTest( "hmac(sha256)", QCA::SymmetricKey(), provider );
- QCOMPARE( hmacLenTest.validKeyLength( 0 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 1 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 848888 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( -2 ), false );
-
- QCA::MessageAuthenticationCode hmac1( "hmac(sha256)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key1( QCA::SecureArray( "Jefe" ) );
- hmac1.setup( key1 );
- QCA::SecureArray data1( "what do ya want for nothing?" );
- hmac1.update( data1 );
- QCOMPARE( QCA::arrayToHex( hmac1.final().toByteArray() ),
- QString( "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" ) );
-
- QCA::MessageAuthenticationCode hmac2( "hmac(sha256)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key2( QCA::hexToArray( "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" ) );
- hmac2.setup( key2 );
- QCA::SecureArray data2 = QCA::SecureArray( "Hi There" );
- hmac2.update( data2 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" ) );
-
- // test reuse
- hmac2.clear();
- QCA::SymmetricKey key3( QCA::hexToArray( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) );
- hmac2.setup ( key3 );
- QCA::SecureArray data3( 50 );
- for ( int i = 0; i < data3.size(); i++ )
- data3[ i ] = (char)0xDD;
- hmac2.update( data3 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe" ) );
-
- QCA::SymmetricKey key4( QCA::hexToArray( "0102030405060708090a0b0c0d0e0f10111213141516171819") );
- QCA::MessageAuthenticationCode hmac4( "hmac(sha256)", key4, provider );
- QCA::SecureArray data4( 50 );
- for (int i = 0; i < data4.size(); i++ )
- data4[ i ] = (char)0xcd;
- hmac4.update( data4 );
- QCOMPARE( QCA::arrayToHex( hmac4.final().toByteArray() ),
- QString( "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b" ) );
-
- QCA::MessageAuthenticationCode hmac5( "hmac(sha256)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key5( QCA::hexToArray( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ) );
- hmac5.setup( key5 );
- QCA::SecureArray data5( "Test With Truncation" );
- hmac5.update( data5 );
- QString resultWithTrunc = QCA::arrayToHex( hmac5.final().toByteArray() );
- resultWithTrunc.resize(32);
- QCOMPARE( resultWithTrunc, QString( "a3b6167473100ee06e0c796c2955552b" ) );
-
- QCA::MessageAuthenticationCode hmac6( "hmac(sha256)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key6( 131 );
- for (int i = 0; i < key6.size(); i++)
- key6[ i ] = (char)0xaa;
- hmac6.setup( key6 );
- QCA::SecureArray data6( "Test Using Larger Than Block-Size Key - Hash Key First" );
- hmac6.update( data6 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" ) );
-
- hmac6.clear(); // reuse the same key
- QCA::SecureArray data7( "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm." );
- hmac6.update( data7 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2" ) );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("hmac(sha256)", provider)) {
+ QWARN(QString("HMAC(SHA256) not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::MessageAuthenticationCode hmacLenTest("hmac(sha256)", QCA::SymmetricKey(), provider);
+ QCOMPARE(hmacLenTest.validKeyLength(0), true);
+ QCOMPARE(hmacLenTest.validKeyLength(1), true);
+ QCOMPARE(hmacLenTest.validKeyLength(848888), true);
+ QCOMPARE(hmacLenTest.validKeyLength(-2), false);
+
+ QCA::MessageAuthenticationCode hmac1("hmac(sha256)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key1(QCA::SecureArray("Jefe"));
+ hmac1.setup(key1);
+ QCA::SecureArray data1("what do ya want for nothing?");
+ hmac1.update(data1);
+ QCOMPARE(QCA::arrayToHex(hmac1.final().toByteArray()),
+ QString("5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"));
+
+ QCA::MessageAuthenticationCode hmac2("hmac(sha256)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key2(QCA::hexToArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
+ hmac2.setup(key2);
+ QCA::SecureArray data2 = QCA::SecureArray("Hi There");
+ hmac2.update(data2);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"));
+
+ // test reuse
+ hmac2.clear();
+ QCA::SymmetricKey key3(QCA::hexToArray("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ hmac2.setup(key3);
+ QCA::SecureArray data3(50);
+ for (int i = 0; i < data3.size(); i++) {
+ data3[ i ] = (char)0xDD;
+ }
+ hmac2.update(data3);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe"));
+
+ QCA::SymmetricKey key4(QCA::hexToArray("0102030405060708090a0b0c0d0e0f10111213141516171819"));
+ QCA::MessageAuthenticationCode hmac4("hmac(sha256)", key4, provider);
+ QCA::SecureArray data4(50);
+ for (int i = 0; i < data4.size(); i++) {
+ data4[ i ] = (char)0xcd;
+ }
+ hmac4.update(data4);
+ QCOMPARE(QCA::arrayToHex(hmac4.final().toByteArray()),
+ QString("82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b"));
+
+ QCA::MessageAuthenticationCode hmac5("hmac(sha256)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key5(QCA::hexToArray("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"));
+ hmac5.setup(key5);
+ QCA::SecureArray data5("Test With Truncation");
+ hmac5.update(data5);
+ QString resultWithTrunc = QCA::arrayToHex(hmac5.final().toByteArray());
+ resultWithTrunc.resize(32);
+ QCOMPARE(resultWithTrunc, QString("a3b6167473100ee06e0c796c2955552b"));
+
+ QCA::MessageAuthenticationCode hmac6("hmac(sha256)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key6(131);
+ for (int i = 0; i < key6.size(); i++) {
+ key6[ i ] = (char)0xaa;
+ }
+ hmac6.setup(key6);
+ QCA::SecureArray data6("Test Using Larger Than Block-Size Key - Hash Key First");
+ hmac6.update(data6);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"));
+
+ hmac6.clear(); // reuse the same key
+ QCA::SecureArray data7("This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.");
+ hmac6.update(data7);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"));
+ }
}
}
void MACUnitTest::HMACSHA224()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "hmac(sha224)", provider ) )
- QWARN( QString( "HMAC(SHA224) not supported for "+provider).toLocal8Bit() );
- else {
- QCA::MessageAuthenticationCode hmacLenTest( "hmac(sha224)", QCA::SymmetricKey(), provider );
- QCOMPARE( hmacLenTest.validKeyLength( 0 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 1 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 848888 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( -2 ), false );
-
- QCA::MessageAuthenticationCode hmac1( "hmac(sha224)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key1( QCA::SecureArray( "Jefe" ) );
- hmac1.setup( key1 );
- QCA::SecureArray data1( "what do ya want for nothing?" );
- hmac1.update( data1 );
- QCOMPARE( QCA::arrayToHex( hmac1.final().toByteArray() ),
- QString( "a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44" ) );
-
- QCA::MessageAuthenticationCode hmac2( "hmac(sha224)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key2( QCA::hexToArray( "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" ) );
- hmac2.setup( key2 );
- QCA::SecureArray data2 = QCA::SecureArray( "Hi There" );
- hmac2.update( data2 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22" ) );
-
- // test reuse
- hmac2.clear();
- QCA::SymmetricKey key3( QCA::hexToArray( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) );
- hmac2.setup ( key3 );
- QCA::SecureArray data3( 50 );
- for ( int i = 0; i < data3.size(); i++ )
- data3[ i ] = (char)0xDD;
- hmac2.update( data3 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea" ) );
-
- QCA::SymmetricKey key4( QCA::hexToArray( "0102030405060708090a0b0c0d0e0f10111213141516171819") );
- QCA::MessageAuthenticationCode hmac4( "hmac(sha224)", key4, provider );
- QCA::SecureArray data4( 50 );
- for (int i = 0; i < data4.size(); i++ )
- data4[ i ] = (char)0xcd;
- hmac4.update( data4 );
- QCOMPARE( QCA::arrayToHex( hmac4.final().toByteArray() ),
- QString( "6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a" ) );
-
- QCA::MessageAuthenticationCode hmac5( "hmac(sha224)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key5( QCA::hexToArray( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ) );
- hmac5.setup( key5 );
- QCA::SecureArray data5( "Test With Truncation" );
- hmac5.update( data5 );
- QString resultWithTrunc = QCA::arrayToHex( hmac5.final().toByteArray() );
- resultWithTrunc.resize(32);
- QCOMPARE( resultWithTrunc, QString( "0e2aea68a90c8d37c988bcdb9fca6fa8" ) );
-
- QCA::MessageAuthenticationCode hmac6( "hmac(sha224)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key6( 131 );
- for (int i = 0; i < key6.size(); i++)
- key6[ i ] = (char)0xaa;
- hmac6.setup( key6 );
- QCA::SecureArray data6( "Test Using Larger Than Block-Size Key - Hash Key First" );
- hmac6.update( data6 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e" ) );
-
- hmac6.clear(); // reuse the same key
- QCA::SecureArray data7( "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm." );
- hmac6.update( data7 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1" ) );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("hmac(sha224)", provider)) {
+ QWARN(QString("HMAC(SHA224) not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::MessageAuthenticationCode hmacLenTest("hmac(sha224)", QCA::SymmetricKey(), provider);
+ QCOMPARE(hmacLenTest.validKeyLength(0), true);
+ QCOMPARE(hmacLenTest.validKeyLength(1), true);
+ QCOMPARE(hmacLenTest.validKeyLength(848888), true);
+ QCOMPARE(hmacLenTest.validKeyLength(-2), false);
+
+ QCA::MessageAuthenticationCode hmac1("hmac(sha224)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key1(QCA::SecureArray("Jefe"));
+ hmac1.setup(key1);
+ QCA::SecureArray data1("what do ya want for nothing?");
+ hmac1.update(data1);
+ QCOMPARE(QCA::arrayToHex(hmac1.final().toByteArray()),
+ QString("a30e01098bc6dbbf45690f3a7e9e6d0f8bbea2a39e6148008fd05e44"));
+
+ QCA::MessageAuthenticationCode hmac2("hmac(sha224)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key2(QCA::hexToArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
+ hmac2.setup(key2);
+ QCA::SecureArray data2 = QCA::SecureArray("Hi There");
+ hmac2.update(data2);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("896fb1128abbdf196832107cd49df33f47b4b1169912ba4f53684b22"));
+
+ // test reuse
+ hmac2.clear();
+ QCA::SymmetricKey key3(QCA::hexToArray("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ hmac2.setup(key3);
+ QCA::SecureArray data3(50);
+ for (int i = 0; i < data3.size(); i++) {
+ data3[ i ] = (char)0xDD;
+ }
+ hmac2.update(data3);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("7fb3cb3588c6c1f6ffa9694d7d6ad2649365b0c1f65d69d1ec8333ea"));
+
+ QCA::SymmetricKey key4(QCA::hexToArray("0102030405060708090a0b0c0d0e0f10111213141516171819"));
+ QCA::MessageAuthenticationCode hmac4("hmac(sha224)", key4, provider);
+ QCA::SecureArray data4(50);
+ for (int i = 0; i < data4.size(); i++) {
+ data4[ i ] = (char)0xcd;
+ }
+ hmac4.update(data4);
+ QCOMPARE(QCA::arrayToHex(hmac4.final().toByteArray()),
+ QString("6c11506874013cac6a2abc1bb382627cec6a90d86efc012de7afec5a"));
+
+ QCA::MessageAuthenticationCode hmac5("hmac(sha224)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key5(QCA::hexToArray("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"));
+ hmac5.setup(key5);
+ QCA::SecureArray data5("Test With Truncation");
+ hmac5.update(data5);
+ QString resultWithTrunc = QCA::arrayToHex(hmac5.final().toByteArray());
+ resultWithTrunc.resize(32);
+ QCOMPARE(resultWithTrunc, QString("0e2aea68a90c8d37c988bcdb9fca6fa8"));
+
+ QCA::MessageAuthenticationCode hmac6("hmac(sha224)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key6(131);
+ for (int i = 0; i < key6.size(); i++) {
+ key6[ i ] = (char)0xaa;
+ }
+ hmac6.setup(key6);
+ QCA::SecureArray data6("Test Using Larger Than Block-Size Key - Hash Key First");
+ hmac6.update(data6);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("95e9a0db962095adaebe9b2d6f0dbce2d499f112f2d2b7273fa6870e"));
+
+ hmac6.clear(); // reuse the same key
+ QCA::SecureArray data7("This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.");
+ hmac6.update(data7);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("3a854166ac5d9f023f54d517d0b39dbd946770db9c2b95c9f6f565d1"));
+ }
}
}
void MACUnitTest::HMACSHA384()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "hmac(sha384)", provider ) )
- QWARN( QString( "HMAC(SHA384) not supported for "+provider).toLocal8Bit() );
- else {
- QCA::MessageAuthenticationCode hmacLenTest( "hmac(sha384)", QCA::SymmetricKey(), provider );
- QCOMPARE( hmacLenTest.validKeyLength( 0 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 1 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 848888 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( -2 ), false );
-
- QCA::MessageAuthenticationCode hmac1( "hmac(sha384)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key1( QCA::SecureArray( "Jefe" ) );
- hmac1.setup( key1 );
- QCA::SecureArray data1( "what do ya want for nothing?" );
- hmac1.update( data1 );
- QCOMPARE( QCA::arrayToHex( hmac1.final().toByteArray() ),
- QString( "af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5e69e2c78b3239ecfab21649" ) );
-
- QCA::MessageAuthenticationCode hmac2( "hmac(sha384)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key2( QCA::hexToArray( "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" ) );
- hmac2.setup( key2 );
- QCA::SecureArray data2 = QCA::SecureArray( "Hi There" );
- hmac2.update( data2 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6" ) );
-
- // test reuse
- hmac2.clear();
- QCA::SymmetricKey key3( QCA::hexToArray( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) );
- hmac2.setup ( key3 );
- QCA::SecureArray data3( 50 );
- for ( int i = 0; i < data3.size(); i++ )
- data3[ i ] = (char)0xDD;
- hmac2.update( data3 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc13814b94e3ab6e101a34f27" ) );
-
- QCA::SymmetricKey key4( QCA::hexToArray( "0102030405060708090a0b0c0d0e0f10111213141516171819") );
- QCA::MessageAuthenticationCode hmac4( "hmac(sha384)", key4, provider );
- QCA::SecureArray data4( 50 );
- for (int i = 0; i < data4.size(); i++ )
- data4[ i ] = (char)0xcd;
- hmac4.update( data4 );
- QCOMPARE( QCA::arrayToHex( hmac4.final().toByteArray() ),
- QString( "3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c4a7d679ccf8a386c674cffb" ) );
-
- QCA::MessageAuthenticationCode hmac5( "hmac(sha384)", QCA::SecureArray(), provider );
- QCA::SymmetricKey key5( QCA::hexToArray( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ) );
- hmac5.setup( key5 );
- QCA::SecureArray data5( "Test With Truncation" );
- hmac5.update( data5 );
- QString resultWithTrunc = QCA::arrayToHex( hmac5.final().toByteArray() );
- resultWithTrunc.resize(32);
- QCOMPARE( resultWithTrunc, QString( "3abf34c3503b2a23a46efc619baef897" ) );
-
- QCA::MessageAuthenticationCode hmac6( "hmac(sha384)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key6( 131 );
- for (int i = 0; i < key6.size(); i++)
- key6[ i ] = (char)0xaa;
- hmac6.setup( key6 );
- QCA::SecureArray data6( "Test Using Larger Than Block-Size Key - Hash Key First" );
- hmac6.update( data6 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4030fe8296248df163f44952" ) );
-
- hmac6.clear(); // reuse the same key
- QCA::SecureArray data7( "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm." );
- hmac6.update( data7 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e799176d3860e6110c46523e" ) );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("hmac(sha384)", provider)) {
+ QWARN(QString("HMAC(SHA384) not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::MessageAuthenticationCode hmacLenTest("hmac(sha384)", QCA::SymmetricKey(), provider);
+ QCOMPARE(hmacLenTest.validKeyLength(0), true);
+ QCOMPARE(hmacLenTest.validKeyLength(1), true);
+ QCOMPARE(hmacLenTest.validKeyLength(848888), true);
+ QCOMPARE(hmacLenTest.validKeyLength(-2), false);
+
+ QCA::MessageAuthenticationCode hmac1("hmac(sha384)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key1(QCA::SecureArray("Jefe"));
+ hmac1.setup(key1);
+ QCA::SecureArray data1("what do ya want for nothing?");
+ hmac1.update(data1);
+ QCOMPARE(QCA::arrayToHex(hmac1.final().toByteArray()),
+ QString("af45d2e376484031617f78d2b58a6b1b9c7ef464f5a01b47e42ec3736322445e8e2240ca5e69e2c78b3239ecfab21649"));
+
+ QCA::MessageAuthenticationCode hmac2("hmac(sha384)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key2(QCA::hexToArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
+ hmac2.setup(key2);
+ QCA::SecureArray data2 = QCA::SecureArray("Hi There");
+ hmac2.update(data2);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("afd03944d84895626b0825f4ab46907f15f9dadbe4101ec682aa034c7cebc59cfaea9ea9076ede7f4af152e8b2fa9cb6"));
+
+ // test reuse
+ hmac2.clear();
+ QCA::SymmetricKey key3(QCA::hexToArray("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ hmac2.setup(key3);
+ QCA::SecureArray data3(50);
+ for (int i = 0; i < data3.size(); i++) {
+ data3[ i ] = (char)0xDD;
+ }
+ hmac2.update(data3);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("88062608d3e6ad8a0aa2ace014c8a86f0aa635d947ac9febe83ef4e55966144b2a5ab39dc13814b94e3ab6e101a34f27"));
+
+ QCA::SymmetricKey key4(QCA::hexToArray("0102030405060708090a0b0c0d0e0f10111213141516171819"));
+ QCA::MessageAuthenticationCode hmac4("hmac(sha384)", key4, provider);
+ QCA::SecureArray data4(50);
+ for (int i = 0; i < data4.size(); i++) {
+ data4[ i ] = (char)0xcd;
+ }
+ hmac4.update(data4);
+ QCOMPARE(QCA::arrayToHex(hmac4.final().toByteArray()),
+ QString("3e8a69b7783c25851933ab6290af6ca77a9981480850009cc5577c6e1f573b4e6801dd23c4a7d679ccf8a386c674cffb"));
+
+ QCA::MessageAuthenticationCode hmac5("hmac(sha384)", QCA::SecureArray(), provider);
+ QCA::SymmetricKey key5(QCA::hexToArray("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"));
+ hmac5.setup(key5);
+ QCA::SecureArray data5("Test With Truncation");
+ hmac5.update(data5);
+ QString resultWithTrunc = QCA::arrayToHex(hmac5.final().toByteArray());
+ resultWithTrunc.resize(32);
+ QCOMPARE(resultWithTrunc, QString("3abf34c3503b2a23a46efc619baef897"));
+
+ QCA::MessageAuthenticationCode hmac6("hmac(sha384)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key6(131);
+ for (int i = 0; i < key6.size(); i++) {
+ key6[ i ] = (char)0xaa;
+ }
+ hmac6.setup(key6);
+ QCA::SecureArray data6("Test Using Larger Than Block-Size Key - Hash Key First");
+ hmac6.update(data6);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("4ece084485813e9088d2c63a041bc5b44f9ef1012a2b588f3cd11f05033ac4c60c2ef6ab4030fe8296248df163f44952"));
+
+ hmac6.clear(); // reuse the same key
+ QCA::SecureArray data7("This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.");
+ hmac6.update(data7);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("6617178e941f020d351e2f254e8fd32c602420feb0b8fb9adccebb82461e99c5a678cc31e799176d3860e6110c46523e"));
+ }
}
}
void MACUnitTest::HMACSHA512()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "hmac(sha512)", provider ) )
- QWARN( QString( "HMAC(SHA512) not supported for "+provider).toLocal8Bit() );
- else {
- QCA::MessageAuthenticationCode hmacLenTest( "hmac(sha512)", QCA::SymmetricKey(), provider );
- QCOMPARE( hmacLenTest.validKeyLength( 0 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 1 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( 848888 ), true );
- QCOMPARE( hmacLenTest.validKeyLength( -2 ), false );
-
- QCA::MessageAuthenticationCode hmac1( "hmac(sha512)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key1( QCA::SecureArray( "Jefe" ) );
- hmac1.setup( key1 );
- QCA::SecureArray data1( "what do ya want for nothing?" );
- hmac1.update( data1 );
- QCOMPARE( QCA::arrayToHex( hmac1.final().toByteArray() ),
- QString( "164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737" ) );
-
- QCA::MessageAuthenticationCode hmac2( "hmac(sha512)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key2( QCA::hexToArray( "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" ) );
- hmac2.setup( key2 );
- QCA::SecureArray data2 = QCA::SecureArray( "Hi There" );
- hmac2.update( data2 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854" ) );
-
- // test reuse
- hmac2.clear();
- QCA::SymmetricKey key3( QCA::hexToArray( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) );
- hmac2.setup ( key3 );
- QCA::SecureArray data3( 50 );
- for ( int i = 0; i < data3.size(); i++ )
- data3[ i ] = (char)0xDD;
- hmac2.update( data3 );
- QCOMPARE( QCA::arrayToHex( hmac2.final().toByteArray() ),
- QString( "fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb" ) );
-
- QCA::SymmetricKey key4( QCA::hexToArray( "0102030405060708090a0b0c0d0e0f10111213141516171819") );
- QCA::MessageAuthenticationCode hmac4( "hmac(sha512)", key4, provider );
- QCA::SecureArray data4( 50 );
- for (int i = 0; i < data4.size(); i++ )
- data4[ i ] = (char)0xcd;
- hmac4.update( data4 );
- QCOMPARE( QCA::arrayToHex( hmac4.final().toByteArray() ),
- QString( "b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd" ) );
-
- QCA::MessageAuthenticationCode hmac5( "hmac(sha512)", QCA::SecureArray(), provider );
- QCA::SymmetricKey key5( QCA::hexToArray( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ) );
- hmac5.setup( key5 );
- QCA::SecureArray data5( "Test With Truncation" );
- hmac5.update( data5 );
- QString resultWithTrunc = QCA::arrayToHex( hmac5.final().toByteArray() );
- resultWithTrunc.resize(32);
- QCOMPARE( resultWithTrunc, QString( "415fad6271580a531d4179bc891d87a6" ) );
-
- QCA::MessageAuthenticationCode hmac6( "hmac(sha512)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key6( 131 );
- for (int i = 0; i < key6.size(); i++)
- key6[ i ] = (char)0xaa;
- hmac6.setup( key6 );
- QCA::SecureArray data6( "Test Using Larger Than Block-Size Key - Hash Key First" );
- hmac6.update( data6 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598" ) );
-
- hmac6.clear(); // reuse the same key
- QCA::SecureArray data7( "This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm." );
- hmac6.update( data7 );
- QCOMPARE( QCA::arrayToHex( hmac6.final().toByteArray() ),
- QString( "e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58" ) );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("hmac(sha512)", provider)) {
+ QWARN(QString("HMAC(SHA512) not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::MessageAuthenticationCode hmacLenTest("hmac(sha512)", QCA::SymmetricKey(), provider);
+ QCOMPARE(hmacLenTest.validKeyLength(0), true);
+ QCOMPARE(hmacLenTest.validKeyLength(1), true);
+ QCOMPARE(hmacLenTest.validKeyLength(848888), true);
+ QCOMPARE(hmacLenTest.validKeyLength(-2), false);
+
+ QCA::MessageAuthenticationCode hmac1("hmac(sha512)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key1(QCA::SecureArray("Jefe"));
+ hmac1.setup(key1);
+ QCA::SecureArray data1("what do ya want for nothing?");
+ hmac1.update(data1);
+ QCOMPARE(QCA::arrayToHex(hmac1.final().toByteArray()),
+ QString("164b7a7bfcf819e2e395fbe73b56e0a387bd64222e831fd610270cd7ea2505549758bf75c05a994a6d034f65f8f0e6fdcaeab1a34d4a6b4b636e070a38bce737"));
+
+ QCA::MessageAuthenticationCode hmac2("hmac(sha512)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key2(QCA::hexToArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
+ hmac2.setup(key2);
+ QCA::SecureArray data2 = QCA::SecureArray("Hi There");
+ hmac2.update(data2);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("87aa7cdea5ef619d4ff0b4241a1d6cb02379f4e2ce4ec2787ad0b30545e17cdedaa833b7d6b8a702038b274eaea3f4e4be9d914eeb61f1702e696c203a126854"));
+
+ // test reuse
+ hmac2.clear();
+ QCA::SymmetricKey key3(QCA::hexToArray("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ hmac2.setup(key3);
+ QCA::SecureArray data3(50);
+ for (int i = 0; i < data3.size(); i++) {
+ data3[ i ] = (char)0xDD;
+ }
+ hmac2.update(data3);
+ QCOMPARE(QCA::arrayToHex(hmac2.final().toByteArray()),
+ QString("fa73b0089d56a284efb0f0756c890be9b1b5dbdd8ee81a3655f83e33b2279d39bf3e848279a722c806b485a47e67c807b946a337bee8942674278859e13292fb"));
+
+ QCA::SymmetricKey key4(QCA::hexToArray("0102030405060708090a0b0c0d0e0f10111213141516171819"));
+ QCA::MessageAuthenticationCode hmac4("hmac(sha512)", key4, provider);
+ QCA::SecureArray data4(50);
+ for (int i = 0; i < data4.size(); i++) {
+ data4[ i ] = (char)0xcd;
+ }
+ hmac4.update(data4);
+ QCOMPARE(QCA::arrayToHex(hmac4.final().toByteArray()),
+ QString("b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"));
+
+ QCA::MessageAuthenticationCode hmac5("hmac(sha512)", QCA::SecureArray(), provider);
+ QCA::SymmetricKey key5(QCA::hexToArray("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"));
+ hmac5.setup(key5);
+ QCA::SecureArray data5("Test With Truncation");
+ hmac5.update(data5);
+ QString resultWithTrunc = QCA::arrayToHex(hmac5.final().toByteArray());
+ resultWithTrunc.resize(32);
+ QCOMPARE(resultWithTrunc, QString("415fad6271580a531d4179bc891d87a6"));
+
+ QCA::MessageAuthenticationCode hmac6("hmac(sha512)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key6(131);
+ for (int i = 0; i < key6.size(); i++) {
+ key6[ i ] = (char)0xaa;
+ }
+ hmac6.setup(key6);
+ QCA::SecureArray data6("Test Using Larger Than Block-Size Key - Hash Key First");
+ hmac6.update(data6);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("80b24263c7c1a3ebb71493c1dd7be8b49b46d1f41b4aeec1121b013783f8f3526b56d037e05f2598bd0fd2215d6a1e5295e64f73f63f0aec8b915a985d786598"));
+
+ hmac6.clear(); // reuse the same key
+ QCA::SecureArray data7("This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.");
+ hmac6.update(data7);
+ QCOMPARE(QCA::arrayToHex(hmac6.final().toByteArray()),
+ QString("e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"));
+ }
}
}
void MACUnitTest::HMACSHA1()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "hmac(sha1)", provider ) )
- QWARN( QString( "HMAC(SHA1) not supported for "+provider).toLocal8Bit() );
- else {
- QCA::MessageAuthenticationCode sha1hmacLenTest( "hmac(sha1)", QCA::SymmetricKey(), provider );
- QCOMPARE( sha1hmacLenTest.validKeyLength( 0 ), true );
- QCOMPARE( sha1hmacLenTest.validKeyLength( 1 ), true );
- QCOMPARE( sha1hmacLenTest.validKeyLength( 848888 ), true );
- QCOMPARE( sha1hmacLenTest.validKeyLength( -2 ), false );
-
- // These tests are from RFC2202, Section 3.
- QCA::MessageAuthenticationCode test1( "hmac(sha1)", QCA::SecureArray() );
- QCA::SymmetricKey key1( QCA::hexToArray( "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" ) );
- test1.setup( key1 );
- QCA::SecureArray data1( "Hi There" );
- test1.update( data1 );
- QCOMPARE( QCA::arrayToHex( test1.final().toByteArray() ), QString( "b617318655057264e28bc0b6fb378c8ef146be00" ) );
-
- QCA::MessageAuthenticationCode test2( "hmac(sha1)", QCA::SymmetricKey(), provider);
- QCA::SymmetricKey key2( QCA::SecureArray( "Jefe" ) );
- test2.setup( key2 );
- QCA::SecureArray data2( "what do ya want for nothing?" );
- test2.update( data2 );
- QCOMPARE( QCA::arrayToHex( test2.final().toByteArray() ), QString( "effcdf6ae5eb2fa2d27416d5f184df9c259a7c79" ) );
-
- QCA::MessageAuthenticationCode test3( "hmac(sha1)", QCA::SymmetricKey(), provider);
- QCA::SymmetricKey key3( QCA::hexToArray( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) );
- test3.setup( key3 );
- QCA::SecureArray data3( 50 );
- for ( int i = 0; i < data3.size(); i++ )
- data3[ i ] = (char)0xDD;
- test3.update( data3 );
- QCOMPARE( QCA::arrayToHex( test3.final().toByteArray() ), QString( "125d7342b9ac11cd91a39af48aa17b4f63f175d3" ) );
-
- QCA::MessageAuthenticationCode test4( "hmac(sha1)", QCA::SymmetricKey(), provider);
- QCA::SymmetricKey key4( QCA::hexToArray( "0102030405060708090a0b0c0d0e0f10111213141516171819" ) );
- test4.setup( key4 );
- QCA::SecureArray data4( 50 );
- for ( int i = 0; i < data4.size(); i++ )
- data4[ i ] = (char)0xcd;
- test4.update( data4 );
- QCOMPARE( QCA::arrayToHex( test4.final().toByteArray() ), QString( "4c9007f4026250c6bc8414f9bf50c86c2d7235da" ) );
-
- QCA::MessageAuthenticationCode test5( "hmac(sha1)", QCA::SymmetricKey(), provider);
- QCA::SymmetricKey key5 ( QCA::hexToArray( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ) );
- test5.setup( key5 );
- QCA::SecureArray data5( "Test With Truncation" );
- test5.update( data5 );
- QCOMPARE( QCA::arrayToHex( test5.final().toByteArray() ), QString( "4c1a03424b55e07fe7f27be1d58bb9324a9a5a04" ) );
-
- QCA::MessageAuthenticationCode test6( "hmac(sha1)", QCA::SymmetricKey(), provider);
- QCA::SymmetricKey key6( 80 );
- for ( int i = 0; i < key6.size(); i++ )
- key6[i] = (char)0xAA;
- test6.setup( key6 );
- QCA::SecureArray data6( "Test Using Larger Than Block-Size Key - Hash Key First" );
- test6.update( data6 );
- QCOMPARE( QCA::arrayToHex( test6.final().toByteArray() ), QString( "aa4ae5e15272d00e95705637ce8a3b55ed402112" ) );
-
- test6.clear(); // this should reuse the same key
- QCA::SecureArray data7( "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data" );
- test6.update( data7 );
- QCOMPARE( QCA::arrayToHex( test6.final().toByteArray() ), QString( "e8e99d0f45237d786d6bbaa7965c7808bbff1a91" ) );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("hmac(sha1)", provider)) {
+ QWARN(QString("HMAC(SHA1) not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::MessageAuthenticationCode sha1hmacLenTest("hmac(sha1)", QCA::SymmetricKey(), provider);
+ QCOMPARE(sha1hmacLenTest.validKeyLength(0), true);
+ QCOMPARE(sha1hmacLenTest.validKeyLength(1), true);
+ QCOMPARE(sha1hmacLenTest.validKeyLength(848888), true);
+ QCOMPARE(sha1hmacLenTest.validKeyLength(-2), false);
+
+ // These tests are from RFC2202, Section 3.
+ QCA::MessageAuthenticationCode test1("hmac(sha1)", QCA::SecureArray());
+ QCA::SymmetricKey key1(QCA::hexToArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
+ test1.setup(key1);
+ QCA::SecureArray data1("Hi There");
+ test1.update(data1);
+ QCOMPARE(QCA::arrayToHex(test1.final().toByteArray()), QString("b617318655057264e28bc0b6fb378c8ef146be00"));
+
+ QCA::MessageAuthenticationCode test2("hmac(sha1)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key2(QCA::SecureArray("Jefe"));
+ test2.setup(key2);
+ QCA::SecureArray data2("what do ya want for nothing?");
+ test2.update(data2);
+ QCOMPARE(QCA::arrayToHex(test2.final().toByteArray()), QString("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79"));
+
+ QCA::MessageAuthenticationCode test3("hmac(sha1)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key3(QCA::hexToArray("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ test3.setup(key3);
+ QCA::SecureArray data3(50);
+ for (int i = 0; i < data3.size(); i++) {
+ data3[ i ] = (char)0xDD;
+ }
+ test3.update(data3);
+ QCOMPARE(QCA::arrayToHex(test3.final().toByteArray()), QString("125d7342b9ac11cd91a39af48aa17b4f63f175d3"));
+
+ QCA::MessageAuthenticationCode test4("hmac(sha1)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key4(QCA::hexToArray("0102030405060708090a0b0c0d0e0f10111213141516171819"));
+ test4.setup(key4);
+ QCA::SecureArray data4(50);
+ for (int i = 0; i < data4.size(); i++) {
+ data4[ i ] = (char)0xcd;
+ }
+ test4.update(data4);
+ QCOMPARE(QCA::arrayToHex(test4.final().toByteArray()), QString("4c9007f4026250c6bc8414f9bf50c86c2d7235da"));
+
+ QCA::MessageAuthenticationCode test5("hmac(sha1)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key5(QCA::hexToArray("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"));
+ test5.setup(key5);
+ QCA::SecureArray data5("Test With Truncation");
+ test5.update(data5);
+ QCOMPARE(QCA::arrayToHex(test5.final().toByteArray()), QString("4c1a03424b55e07fe7f27be1d58bb9324a9a5a04"));
+
+ QCA::MessageAuthenticationCode test6("hmac(sha1)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key6(80);
+ for (int i = 0; i < key6.size(); i++) {
+ key6[i] = (char)0xAA;
+ }
+ test6.setup(key6);
+ QCA::SecureArray data6("Test Using Larger Than Block-Size Key - Hash Key First");
+ test6.update(data6);
+ QCOMPARE(QCA::arrayToHex(test6.final().toByteArray()), QString("aa4ae5e15272d00e95705637ce8a3b55ed402112"));
+
+ test6.clear(); // this should reuse the same key
+ QCA::SecureArray data7("Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data");
+ test6.update(data7);
+ QCOMPARE(QCA::arrayToHex(test6.final().toByteArray()), QString("e8e99d0f45237d786d6bbaa7965c7808bbff1a91"));
+ }
}
}
void MACUnitTest::HMACRMD160()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
providersToTest.append("qca-gcrypt");
providersToTest.append("qca-botan");
providersToTest.append("qca-nss");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "hmac(ripemd160)", provider ) )
- QWARN( QString( "HMAC(RIPEMD160) not supported for "+provider).toLocal8Bit() );
- else {
- QCA::MessageAuthenticationCode ripemd160hmacLenTest( "hmac(ripemd160)", QCA::SymmetricKey(), provider );
- QCOMPARE( ripemd160hmacLenTest.validKeyLength( 0 ), true );
- QCOMPARE( ripemd160hmacLenTest.validKeyLength( 1 ), true );
- QCOMPARE( ripemd160hmacLenTest.validKeyLength( 848888 ), true );
- QCOMPARE( ripemd160hmacLenTest.validKeyLength( -2 ), false );
-
- // These tests are from RFC2286, Section 2.
- QCA::MessageAuthenticationCode test1( "hmac(ripemd160)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key1 ( QCA::hexToArray( "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b" ) );
- test1.setup( key1 );
- QCA::SecureArray data1( "Hi There" );
- test1.update( data1 );
- QCOMPARE( QCA::arrayToHex( test1.final().toByteArray() ), QString( "24cb4bd67d20fc1a5d2ed7732dcc39377f0a5668" ) );
-
- QCA::MessageAuthenticationCode test2( "hmac(ripemd160)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key2( QCA::SecureArray( "Jefe" ) );
- test2.setup( key2 );
- QCA::SecureArray data2( "what do ya want for nothing?" );
- test2.update( data2 );
- QCOMPARE( QCA::arrayToHex( test2.final().toByteArray() ), QString( "dda6c0213a485a9e24f4742064a7f033b43c4069" ) );
-
- QCA::MessageAuthenticationCode test3( "hmac(ripemd160)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key3( QCA::hexToArray( "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" ) );
- test3.setup( key3 );
- QCA::SecureArray data3( 50 );
- for ( int i = 0; i < data3.size(); i++ )
- data3[ i ] = (char)0xDD;
- test3.update( data3 );
- QCOMPARE( QCA::arrayToHex( test3.final().toByteArray() ), QString( "b0b105360de759960ab4f35298e116e295d8e7c1" ) );
-
- QCA::SymmetricKey key4( QCA::hexToArray( "0102030405060708090a0b0c0d0e0f10111213141516171819" ) );
- QCA::MessageAuthenticationCode test4( "hmac(ripemd160)", key4, provider );
- QCA::SecureArray data4( 50 );
- for ( int i = 0; i < data4.size(); i++ )
- data4[ i ] = (char)0xcd;
- test4.update( data4 );
- QCOMPARE( QCA::arrayToHex( test4.final().toByteArray() ), QString( "d5ca862f4d21d5e610e18b4cf1beb97a4365ecf4" ) );
-
- QCA::MessageAuthenticationCode test5( "hmac(ripemd160)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key5 ( QCA::hexToArray( "0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c" ) );
- test5.setup( key5 );
- QCA::SecureArray data5( "Test With Truncation" );
- test5.update( data5 );
- QCOMPARE( QCA::arrayToHex( test5.final().toByteArray() ), QString( "7619693978f91d90539ae786500ff3d8e0518e39" ) );
-
- QCA::MessageAuthenticationCode test6( "hmac(ripemd160)", QCA::SymmetricKey(), provider );
- QCA::SymmetricKey key6( 80 );
- for ( int i = 0; i < key6.size(); i++ )
- key6[i] = (char)0xAA;
- test6.setup( key6 );
- QCA::SecureArray data6( "Test Using Larger Than Block-Size Key - Hash Key First" );
- test6.update( data6 );
- QCOMPARE( QCA::arrayToHex( test6.final().toByteArray() ), QString( "6466ca07ac5eac29e1bd523e5ada7605b791fd8b" ) );
-
- test6.clear(); // reuse the key
- QCA::SecureArray data7( "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data" );
- test6.update( data7 );
- QCOMPARE( QCA::arrayToHex( test6.final().toByteArray() ), QString( "69ea60798d71616cce5fd0871e23754cd75d5a0a" ) );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("hmac(ripemd160)", provider)) {
+ QWARN(QString("HMAC(RIPEMD160) not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::MessageAuthenticationCode ripemd160hmacLenTest("hmac(ripemd160)", QCA::SymmetricKey(), provider);
+ QCOMPARE(ripemd160hmacLenTest.validKeyLength(0), true);
+ QCOMPARE(ripemd160hmacLenTest.validKeyLength(1), true);
+ QCOMPARE(ripemd160hmacLenTest.validKeyLength(848888), true);
+ QCOMPARE(ripemd160hmacLenTest.validKeyLength(-2), false);
+
+ // These tests are from RFC2286, Section 2.
+ QCA::MessageAuthenticationCode test1("hmac(ripemd160)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key1(QCA::hexToArray("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"));
+ test1.setup(key1);
+ QCA::SecureArray data1("Hi There");
+ test1.update(data1);
+ QCOMPARE(QCA::arrayToHex(test1.final().toByteArray()), QString("24cb4bd67d20fc1a5d2ed7732dcc39377f0a5668"));
+
+ QCA::MessageAuthenticationCode test2("hmac(ripemd160)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key2(QCA::SecureArray("Jefe"));
+ test2.setup(key2);
+ QCA::SecureArray data2("what do ya want for nothing?");
+ test2.update(data2);
+ QCOMPARE(QCA::arrayToHex(test2.final().toByteArray()), QString("dda6c0213a485a9e24f4742064a7f033b43c4069"));
+
+ QCA::MessageAuthenticationCode test3("hmac(ripemd160)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key3(QCA::hexToArray("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
+ test3.setup(key3);
+ QCA::SecureArray data3(50);
+ for (int i = 0; i < data3.size(); i++) {
+ data3[ i ] = (char)0xDD;
+ }
+ test3.update(data3);
+ QCOMPARE(QCA::arrayToHex(test3.final().toByteArray()), QString("b0b105360de759960ab4f35298e116e295d8e7c1"));
+
+ QCA::SymmetricKey key4(QCA::hexToArray("0102030405060708090a0b0c0d0e0f10111213141516171819"));
+ QCA::MessageAuthenticationCode test4("hmac(ripemd160)", key4, provider);
+ QCA::SecureArray data4(50);
+ for (int i = 0; i < data4.size(); i++) {
+ data4[ i ] = (char)0xcd;
+ }
+ test4.update(data4);
+ QCOMPARE(QCA::arrayToHex(test4.final().toByteArray()), QString("d5ca862f4d21d5e610e18b4cf1beb97a4365ecf4"));
+
+ QCA::MessageAuthenticationCode test5("hmac(ripemd160)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key5(QCA::hexToArray("0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c"));
+ test5.setup(key5);
+ QCA::SecureArray data5("Test With Truncation");
+ test5.update(data5);
+ QCOMPARE(QCA::arrayToHex(test5.final().toByteArray()), QString("7619693978f91d90539ae786500ff3d8e0518e39"));
+
+ QCA::MessageAuthenticationCode test6("hmac(ripemd160)", QCA::SymmetricKey(), provider);
+ QCA::SymmetricKey key6(80);
+ for (int i = 0; i < key6.size(); i++) {
+ key6[i] = (char)0xAA;
+ }
+ test6.setup(key6);
+ QCA::SecureArray data6("Test Using Larger Than Block-Size Key - Hash Key First");
+ test6.update(data6);
+ QCOMPARE(QCA::arrayToHex(test6.final().toByteArray()), QString("6466ca07ac5eac29e1bd523e5ada7605b791fd8b"));
+
+ test6.clear(); // reuse the key
+ QCA::SecureArray data7("Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data");
+ test6.update(data7);
+ QCOMPARE(QCA::arrayToHex(test6.final().toByteArray()), QString("69ea60798d71616cce5fd0871e23754cd75d5a0a"));
+ }
}
}
QTEST_MAIN(MACUnitTest)
#include "macunittest.moc"
-
-
diff --git a/unittest/metatype/metatype.cpp b/unittest/metatype/metatype.cpp
index f21e1f9d..9325efcc 100644
--- a/unittest/metatype/metatype.cpp
+++ b/unittest/metatype/metatype.cpp
@@ -1,194 +1,209 @@
/**
* Copyright (C) 2007 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#include <limits>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class TestClass1 : public QObject
{
Q_OBJECT
public:
TestClass1() { };
~TestClass1() { };
- TestClass1(const TestClass1 & ):QObject( 0 ) { };
+ TestClass1(const TestClass1 &): QObject(0) { };
public slots:
void voidMethod() { };
- QString qstringMethod() { return QString(); };
- bool boolMethod( const QString & ) { return true; };
- QString returnArg( const QString &s ) { return s; };
- QByteArray returnArg( const QByteArray &a ) { return a; };
- QString returnRepeatArg( const QString &s ) { return QString( s+s ); };
- QString tenArgs( const QString &s, int, int, int, int, int, int, int, int, int)
+ QString qstringMethod()
{
- return QString( s );
+ return QString();
};
- QString elevenArgs( const QString &s, int, int, int, int, int, int, int, int, int, int)
+ bool boolMethod(const QString &)
{
- return QString( s );
+ return true;
+ };
+ QString returnArg(const QString &s)
+ {
+ return s;
+ };
+ QByteArray returnArg(const QByteArray &a)
+ {
+ return a;
+ };
+ QString returnRepeatArg(const QString &s)
+ {
+ return QString(s + s);
+ };
+ QString tenArgs(const QString &s, int, int, int, int, int, int, int, int, int)
+ {
+ return QString(s);
+ };
+ QString elevenArgs(const QString &s, int, int, int, int, int, int, int, int, int, int)
+ {
+ return QString(s);
};
};
-Q_DECLARE_METATYPE( TestClass1 )
+Q_DECLARE_METATYPE(TestClass1)
class MetaTypeUnitTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void returnTypeTest();
void invokeMethodTest();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void MetaTypeUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void MetaTypeUnitTest::cleanupTestCase()
{
QCA::unloadAllPlugins();
delete m_init;
}
void MetaTypeUnitTest::returnTypeTest()
{
TestClass1 testClass1;
QList<QByteArray> args;
// returns a null type name because that is what void does...
#if QT_VERSION >= 0x050000
- QCOMPARE( QByteArray( "void" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "voidMethod" ), args ) );
+ QCOMPARE(QByteArray("void"), QCA::methodReturnType(testClass1.metaObject(), QByteArray("voidMethod"), args));
#else
- QCOMPARE( QByteArray(), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "voidMethod" ), args ) );
+ QCOMPARE(QByteArray(), QCA::methodReturnType(testClass1.metaObject(), QByteArray("voidMethod"), args));
#endif
- QCOMPARE( QByteArray( "QString" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "qstringMethod" ), args ) );
+ QCOMPARE(QByteArray("QString"), QCA::methodReturnType(testClass1.metaObject(), QByteArray("qstringMethod"), args));
// returns a null type, because args don't match
- QCOMPARE( QByteArray( "" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "boolMethod" ), args ) );
+ QCOMPARE(QByteArray(""), QCA::methodReturnType(testClass1.metaObject(), QByteArray("boolMethod"), args));
args << "QString";
- QCOMPARE( QByteArray( "QString" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "returnArg" ), args ) );
- QCOMPARE( QByteArray( "bool" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "boolMethod" ), args ) );
+ QCOMPARE(QByteArray("QString"), QCA::methodReturnType(testClass1.metaObject(), QByteArray("returnArg"), args));
+ QCOMPARE(QByteArray("bool"), QCA::methodReturnType(testClass1.metaObject(), QByteArray("boolMethod"), args));
args.clear();
args << "QByteArray";
- QCOMPARE( QByteArray( "QByteArray" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "returnArg" ), args ) );
+ QCOMPARE(QByteArray("QByteArray"), QCA::methodReturnType(testClass1.metaObject(), QByteArray("returnArg"), args));
args.clear();
args << "QString" << "int" << "int" << "int" << "int" << "int" << "int" << "int" << "int";
// wrong number of arguments - has 9, needs 10
- QCOMPARE( QByteArray( "" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "tenArgs" ), args ) );
+ QCOMPARE(QByteArray(""), QCA::methodReturnType(testClass1.metaObject(), QByteArray("tenArgs"), args));
// match
args << "int";
- QCOMPARE( QByteArray( "QString" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "tenArgs" ), args ) );
+ QCOMPARE(QByteArray("QString"), QCA::methodReturnType(testClass1.metaObject(), QByteArray("tenArgs"), args));
args << "int";
- QCOMPARE( QByteArray( "QString" ), QCA::methodReturnType( testClass1.metaObject(), QByteArray( "elevenArgs" ), args ) );
+ QCOMPARE(QByteArray("QString"), QCA::methodReturnType(testClass1.metaObject(), QByteArray("elevenArgs"), args));
}
void MetaTypeUnitTest::invokeMethodTest()
{
TestClass1 *testClass1 = new TestClass1;
QVariantList args;
bool ret;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "voidMethod" ), args, 0 );
- QVERIFY( ret );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("voidMethod"), args, 0);
+ QVERIFY(ret);
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "noSuchMethod" ), args, 0 );
- QVERIFY( ret == false );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("noSuchMethod"), args, 0);
+ QVERIFY(ret == false);
QVariant stringRes;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "qstringMethod" ), args, &stringRes );
- QVERIFY( ret );
- QVERIFY( stringRes.isValid() );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("qstringMethod"), args, &stringRes);
+ QVERIFY(ret);
+ QVERIFY(stringRes.isValid());
- QVariant result ( false );
+ QVariant result(false);
QString fakeArg;
args << fakeArg;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "boolMethod" ), args, &result );
- QVERIFY( ret );
- QCOMPARE( result.toBool(), true );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("boolMethod"), args, &result);
+ QVERIFY(ret);
+ QCOMPARE(result.toBool(), true);
result = QByteArray();
args.clear();
- QByteArray myArray( "array" );
+ QByteArray myArray("array");
args << myArray;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "returnArg" ), args, &result );
- QVERIFY( ret );
- QCOMPARE( result.toByteArray(), myArray );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("returnArg"), args, &result);
+ QVERIFY(ret);
+ QCOMPARE(result.toByteArray(), myArray);
result = QString();
args.clear();
- QString myString( "test words" );
+ QString myString("test words");
args << myString;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "returnArg" ), args, &result );
- QVERIFY( ret );
- QCOMPARE( result.toString(), myString );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("returnArg"), args, &result);
+ QVERIFY(ret);
+ QCOMPARE(result.toString(), myString);
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "returnRepeatArg" ), args, &result );
- QVERIFY( ret );
- QCOMPARE( result.toString(), myString + myString );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("returnRepeatArg"), args, &result);
+ QVERIFY(ret);
+ QCOMPARE(result.toString(), myString + myString);
// 9 arguments - no matching method
- result = QString( "unchanged" );
+ result = QString("unchanged");
args << 0 << 0 << 0 << 0 << 0 << 0 << 0 << 0;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "tenArgs" ), args, &result );
- QVERIFY( ret == false );
- QCOMPARE( result.toString(), QString( "unchanged" ) );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("tenArgs"), args, &result);
+ QVERIFY(ret == false);
+ QCOMPARE(result.toString(), QString("unchanged"));
// 10 args
args << 0;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "tenArgs" ), args, &result );
- QVERIFY( ret );
- QCOMPARE( result.toString(), myString );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("tenArgs"), args, &result);
+ QVERIFY(ret);
+ QCOMPARE(result.toString(), myString);
// 11 args
- result = QString( "unchanged" );
+ result = QString("unchanged");
args << 0;
- ret = QCA::invokeMethodWithVariants( testClass1, QByteArray( "elevenArgs" ), args, &result );
- QVERIFY( ret == false );
- QCOMPARE( result.toString(), QString( "unchanged" ) );
+ ret = QCA::invokeMethodWithVariants(testClass1, QByteArray("elevenArgs"), args, &result);
+ QVERIFY(ret == false);
+ QCOMPARE(result.toString(), QString("unchanged"));
delete testClass1;
}
QTEST_MAIN(MetaTypeUnitTest)
#include "metatype.moc"
diff --git a/unittest/pgpunittest/pgpunittest.cpp b/unittest/pgpunittest/pgpunittest.cpp
index 16ed5fd0..15dc3565 100644
--- a/unittest/pgpunittest/pgpunittest.cpp
+++ b/unittest/pgpunittest/pgpunittest.cpp
@@ -1,928 +1,923 @@
/**
* Copyright (C) 2006-2007 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#include <stdlib.h>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
// qt did not introduce qputenv until 4.4, so we'll keep a copy here for 4.2
// compat
-bool my_qputenv(const char *varName, const QByteArray& value)
+bool my_qputenv(const char *varName, const QByteArray &value)
{
#if defined(_MSC_VER) && _MSC_VER >= 1400
return _putenv_s(varName, value.constData()) == 0;
#else
QByteArray buffer(varName);
buffer += "=";
buffer += value;
return putenv(qstrdup(buffer.constData())) == 0;
#endif
}
static int qca_setenv(const char *name, const char *value, int overwrite)
{
- if (!overwrite && !qgetenv(name).isNull()) return 0;
+ if (!overwrite && !qgetenv(name).isNull()) {
+ return 0;
+ }
- if(my_qputenv(name, QByteArray(value)))
- return 0; // success
- else
- return 1; // error
+ if (my_qputenv(name, QByteArray(value))) {
+ return 0; // success
+ } else {
+ return 1; // error
+ }
}
// Note; in a real application you get this from a user, but this
// is a useful trick for a unit test.
// See the qcatool application or keyloader and eventhandler examples
// for how to do this properly.
class PGPPassphraseProvider: public QObject
{
Q_OBJECT
public:
PGPPassphraseProvider(QObject *parent = 0) : QObject(parent)
{
- connect(&m_handler, SIGNAL(eventReady(int, const QCA::Event &)),
- SLOT(eh_eventReady(int, const QCA::Event &)));
- m_handler.start();
+ connect(&m_handler, SIGNAL(eventReady(int,QCA::Event)),
+ SLOT(eh_eventReady(int,QCA::Event)));
+ m_handler.start();
}
private slots:
void eh_eventReady(int id, const QCA::Event &event)
{
- if(event.type() == QCA::Event::Password)
- {
- QCA::SecureArray pass("start");
- m_handler.submitPassword(id, pass);
- }
- else
- {
- m_handler.reject(id);
+ if (event.type() == QCA::Event::Password) {
+ QCA::SecureArray pass("start");
+ m_handler.submitPassword(id, pass);
+ } else {
+ m_handler.reject(id);
}
}
private:
QCA::EventHandler m_handler;
};
class PGPPassphraseProviderThread : public QCA::SyncThread
{
Q_OBJECT
public:
~PGPPassphraseProviderThread()
{
- stop();
+ stop();
}
protected:
void atStart()
{
- prov = new PGPPassphraseProvider;
+ prov = new PGPPassphraseProvider;
}
void atEnd()
{
- delete prov;
+ delete prov;
}
private:
PGPPassphraseProvider *prov;
};
-
class PgpUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testKeyRing();
void testMessageSign();
void testClearsign();
void testDetachedSign();
void testSignaturesWithExpiredSubkeys();
void testEncryptionWithExpiredSubkeys();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void PgpUnitTest::initTestCase()
{
// instead of initializing qca once, we will initialize it for every
// test case. this is the only way to get the keystore subsystem
// to reload, which we need to do if we want qca-gnupg to respect
// changes to $GNUPGHOME.
//m_init = new QCA::Initializer;
// Change current directory to executable directory
// it is need to find keys*_work directories
- if (!QCoreApplication::applicationDirPath().isEmpty())
+ if (!QCoreApplication::applicationDirPath().isEmpty()) {
QDir::setCurrent(QCoreApplication::applicationDirPath());
+ }
}
void PgpUnitTest::cleanupTestCase()
{
//delete m_init;
}
void PgpUnitTest::testKeyRing()
{
QCA::Initializer *qcaInit = new QCA::Initializer;
// We test a small keyring - I downloaded a publically available one from
- QByteArray oldGNUPGHOME = qgetenv( "GNUPGHOME" );
+ QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
// the Amsterdam Internet Exchange.
- if ( qca_setenv( "GNUPGHOME", "./keys1_work", 1 ) != 0 )
- {
- QFAIL( "Expected to be able to set the GNUPGHOME environment variable, but couldn't" );
+ if (qca_setenv("GNUPGHOME", "./keys1_work", 1) != 0) {
+ QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
}
// activate the KeyStoreManager
QCA::KeyStoreManager::start();
- if ( QCA::isSupported( QStringList( QString( "keystorelist" ) ),
- QString( "qca-gnupg" ) ) )
- {
+ if (QCA::isSupported(QStringList(QString("keystorelist")),
+ QString("qca-gnupg"))) {
QCA::KeyStoreManager keyManager(this);
- keyManager.waitForBusyFinished();
- QStringList storeIds = keyManager.keyStores();
- QVERIFY( storeIds.contains( "qca-gnupg" ) );
-
- QCA::KeyStore pgpStore( QString("qca-gnupg"), &keyManager );
- QVERIFY( pgpStore.isValid() );
- QCOMPARE( pgpStore.name(), QString( "GnuPG Keyring" ) );
- QCOMPARE( pgpStore.type(), QCA::KeyStore::PGPKeyring );
- QCOMPARE( pgpStore.id(), QString( "qca-gnupg" ) );
- QCOMPARE( pgpStore.isReadOnly(), false );
- QCOMPARE( pgpStore.holdsTrustedCertificates(), false );
- QCOMPARE( pgpStore.holdsIdentities(), true );
- QCOMPARE( pgpStore.holdsPGPPublicKeys(), true );
+ keyManager.waitForBusyFinished();
+ QStringList storeIds = keyManager.keyStores();
+ QVERIFY(storeIds.contains("qca-gnupg"));
+
+ QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
+ QVERIFY(pgpStore.isValid());
+ QCOMPARE(pgpStore.name(), QString("GnuPG Keyring"));
+ QCOMPARE(pgpStore.type(), QCA::KeyStore::PGPKeyring);
+ QCOMPARE(pgpStore.id(), QString("qca-gnupg"));
+ QCOMPARE(pgpStore.isReadOnly(), false);
+ QCOMPARE(pgpStore.holdsTrustedCertificates(), false);
+ QCOMPARE(pgpStore.holdsIdentities(), true);
+ QCOMPARE(pgpStore.holdsPGPPublicKeys(), true);
QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
- QCOMPARE( keylist.count(), 6 );
+ QCOMPARE(keylist.count(), 6);
QStringList nameList;
- foreach( const QCA::KeyStoreEntry key, keylist ) {
- QCOMPARE( key.isNull(), false );
- QCOMPARE( key.type(), QCA::KeyStoreEntry::TypePGPPublicKey );
- QCOMPARE( key.id().length(), 16 ); // 16 hex digits
- QVERIFY( key.keyBundle().isNull() );
- QVERIFY( key.certificate().isNull() );
- QVERIFY( key.crl().isNull() );
- QVERIFY( key.pgpSecretKey().isNull() );
- QCOMPARE( key.pgpPublicKey().isNull(), false );
+ foreach (const QCA::KeyStoreEntry key, keylist) {
+ QCOMPARE(key.isNull(), false);
+ QCOMPARE(key.type(), QCA::KeyStoreEntry::TypePGPPublicKey);
+ QCOMPARE(key.id().length(), 16); // 16 hex digits
+ QVERIFY(key.keyBundle().isNull());
+ QVERIFY(key.certificate().isNull());
+ QVERIFY(key.crl().isNull());
+ QVERIFY(key.pgpSecretKey().isNull());
+ QCOMPARE(key.pgpPublicKey().isNull(), false);
// We accumulate the names, and check them next
nameList << key.name();
}
- QVERIFY( nameList.contains( "Steven Bakker <steven.bakker@ams-ix.net>" ) );
- QVERIFY( nameList.contains( "Romeo Zwart <rz@ams-ix.net>" ) );
- QVERIFY( nameList.contains( "Arien Vijn <arien.vijn@ams-ix.net>" ) );
- QVERIFY( nameList.contains( "Niels Bakker <niels.bakker@ams-ix.net>" ) );
- QVERIFY( nameList.contains( "Henk Steenman <Henk.Steenman@ams-ix.net>" ) );
- QVERIFY( nameList.contains( "Geert Nijpels <geert.nijpels@ams-ix.net>" ) );
+ QVERIFY(nameList.contains("Steven Bakker <steven.bakker@ams-ix.net>"));
+ QVERIFY(nameList.contains("Romeo Zwart <rz@ams-ix.net>"));
+ QVERIFY(nameList.contains("Arien Vijn <arien.vijn@ams-ix.net>"));
+ QVERIFY(nameList.contains("Niels Bakker <niels.bakker@ams-ix.net>"));
+ QVERIFY(nameList.contains("Henk Steenman <Henk.Steenman@ams-ix.net>"));
+ QVERIFY(nameList.contains("Geert Nijpels <geert.nijpels@ams-ix.net>"));
// TODO: We should test removeEntry() and writeEntry() here.
}
delete qcaInit;
qcaInit = new QCA::Initializer;
// We now test an empty keyring
- if ( qca_setenv( "GNUPGHOME", "./keys2_work", 1 ) != 0 )
- {
- QFAIL( "Expected to be able to set the GNUPGHOME environment variable, but couldn't" );
+ if (qca_setenv("GNUPGHOME", "./keys2_work", 1) != 0) {
+ QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
}
QCA::KeyStoreManager::start();
- if ( QCA::isSupported( QStringList( QString( "keystorelist" ) ),
- QString( "qca-gnupg" ) ) )
- {
+ if (QCA::isSupported(QStringList(QString("keystorelist")),
+ QString("qca-gnupg"))) {
QCA::KeyStoreManager keyManager(this);
- keyManager.waitForBusyFinished();
- QStringList storeIds = keyManager.keyStores();
- QVERIFY( storeIds.contains( "qca-gnupg" ) );
+ keyManager.waitForBusyFinished();
+ QStringList storeIds = keyManager.keyStores();
+ QVERIFY(storeIds.contains("qca-gnupg"));
- QCA::KeyStore pgpStore( QString("qca-gnupg"), &keyManager );
+ QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
- QCOMPARE( keylist.count(), 0 );
+ QCOMPARE(keylist.count(), 0);
// TODO: We should test removeEntry() and writeEntry() here.
}
- if ( false == oldGNUPGHOME.isNull() )
- {
- qca_setenv( "GNUPGHOME", oldGNUPGHOME.data(), 1 );
+ if (false == oldGNUPGHOME.isNull()) {
+ qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
}
delete qcaInit;
}
void PgpUnitTest::testMessageSign()
{
QCA::Initializer qcaInit;
// event handling cannot be used in the same thread as synchronous calls
// which might require event handling. let's put our event handler in
// a side thread so that we can write the unit test synchronously.
PGPPassphraseProviderThread thread;
thread.start();
// This keyring has a private / public key pair
- QByteArray oldGNUPGHOME = qgetenv( "GNUPGHOME" );
- if ( 0 != qca_setenv( "GNUPGHOME", "./keys3_work", 1 ) ) {
- QFAIL( "Expected to be able to set the GNUPGHOME environment variable, but couldn't" );
+ QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
+ if (0 != qca_setenv("GNUPGHOME", "./keys3_work", 1)) {
+ QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
}
-
+
// activate the KeyStoreManager
QCA::KeyStoreManager::start();
QCA::KeyStoreManager keyManager(this);
keyManager.waitForBusyFinished();
- if ( QCA::isSupported( QStringList( QString( "openpgp" ) ), QString( "qca-gnupg" ) ) ||
- QCA::isSupported( QStringList( QString( "keystorelist" ) ), QString( "qca-gnupg" ) ) ) {
+ if (QCA::isSupported(QStringList(QString("openpgp")), QString("qca-gnupg")) ||
+ QCA::isSupported(QStringList(QString("keystorelist")), QString("qca-gnupg"))) {
QStringList storeIds = keyManager.keyStores();
- QVERIFY( storeIds.contains( "qca-gnupg" ) );
-
- QCA::KeyStore pgpStore( QString("qca-gnupg"), &keyManager );
- QVERIFY( pgpStore.isValid() );
-
- QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
- QCOMPARE( keylist.count(), 1 );
-
- QCA::KeyStoreEntry myPGPKey = keylist.at(0);
- QCOMPARE( myPGPKey.isNull(), false );
- QCOMPARE( myPGPKey.name(), QString("Qca Test Key (This key is only for QCA unit tests) <qca@example.com>") );
- QCOMPARE( myPGPKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey );
- QCOMPARE( myPGPKey.id(), QString("9E946237DAFCCFF4") );
- QVERIFY( myPGPKey.keyBundle().isNull() );
- QVERIFY( myPGPKey.certificate().isNull() );
- QVERIFY( myPGPKey.crl().isNull() );
- QCOMPARE( myPGPKey.pgpSecretKey().isNull(), false );
- QCOMPARE( myPGPKey.pgpPublicKey().isNull(), false );
-
- // first make the SecureMessageKey
- QCA::SecureMessageKey key;
- key.setPGPSecretKey( myPGPKey.pgpSecretKey() );
- QVERIFY( key.havePrivate() );
-
- // our data to sign
- QByteArray plain = "Hello, world";
-
- // let's do it
- QCA::OpenPGP pgp;
- QCA::SecureMessage msg(&pgp);
- msg.setSigner(key);
- msg.setFormat(QCA::SecureMessage::Ascii);
- msg.startSign(QCA::SecureMessage::Message);
- msg.update(plain);
- msg.end();
- msg.waitForFinished(5000);
+ QVERIFY(storeIds.contains("qca-gnupg"));
+
+ QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
+ QVERIFY(pgpStore.isValid());
+
+ QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
+ QCOMPARE(keylist.count(), 1);
+
+ QCA::KeyStoreEntry myPGPKey = keylist.at(0);
+ QCOMPARE(myPGPKey.isNull(), false);
+ QCOMPARE(myPGPKey.name(), QString("Qca Test Key (This key is only for QCA unit tests) <qca@example.com>"));
+ QCOMPARE(myPGPKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
+ QCOMPARE(myPGPKey.id(), QString("9E946237DAFCCFF4"));
+ QVERIFY(myPGPKey.keyBundle().isNull());
+ QVERIFY(myPGPKey.certificate().isNull());
+ QVERIFY(myPGPKey.crl().isNull());
+ QCOMPARE(myPGPKey.pgpSecretKey().isNull(), false);
+ QCOMPARE(myPGPKey.pgpPublicKey().isNull(), false);
+
+ // first make the SecureMessageKey
+ QCA::SecureMessageKey key;
+ key.setPGPSecretKey(myPGPKey.pgpSecretKey());
+ QVERIFY(key.havePrivate());
+
+ // our data to sign
+ QByteArray plain = "Hello, world";
+
+ // let's do it
+ QCA::OpenPGP pgp;
+ QCA::SecureMessage msg(&pgp);
+ msg.setSigner(key);
+ msg.setFormat(QCA::SecureMessage::Ascii);
+ msg.startSign(QCA::SecureMessage::Message);
+ msg.update(plain);
+ msg.end();
+ msg.waitForFinished(5000);
#if 0
QString str = QCA::KeyStoreManager::diagnosticText();
QCA::KeyStoreManager::clearDiagnosticText();
QStringList lines = str.split('\n', QString::SkipEmptyParts);
- for(int n = 0; n < lines.count(); ++n)
- fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ for (int n = 0; n < lines.count(); ++n) {
+ fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ }
QString out = msg.diagnosticText();
QStringList msglines = out.split('\n', QString::SkipEmptyParts);
- for(int n = 0; n < msglines.count(); ++n)
- fprintf(stderr, "message: %s\n", qPrintable(msglines[n]));
+ for (int n = 0; n < msglines.count(); ++n) {
+ fprintf(stderr, "message: %s\n", qPrintable(msglines[n]));
+ }
#endif
- QByteArray messageData;
- if(msg.success()) {
- messageData = msg.read();
- } else {
- qDebug() << "Failure:" << msg.errorCode();
- QFAIL("Failed to sign in Message format");
- }
- // qDebug() << "Message format data:" << messageData;
-
- // OK, now lets verify that the result will verify.
- // let's do it
- QCA::OpenPGP pgp2;
- QCA::SecureMessage msg2(&pgp2);
- msg2.setFormat(QCA::SecureMessage::Ascii);
- msg2.startVerify();
- msg2.update(messageData);
- msg2.end();
- msg2.waitForFinished(5000);
-
- QVERIFY(msg2.verifySuccess());
-
- if(msg2.success()) {
- QCOMPARE( msg2.read(), plain );
- } else {
- qDebug() << "Failure:" << msg2.errorCode();
- QFAIL("Failed to verify message");
- }
-
- // why is this here?
- if ( false == oldGNUPGHOME.isNull() ) {
- qca_setenv( "GNUPGHOME", oldGNUPGHOME.data(), 1 );
- }
-
- // now test that if we corrupt the message, it no longer
- // verifies correctly.
- messageData.replace( 'T', 't' );
- messageData.replace( 'w', 'W' );
- QCA::SecureMessage msg3(&pgp2);
- msg3.setFormat(QCA::SecureMessage::Ascii);
- msg3.startVerify();
- msg3.update(messageData);
- msg3.end();
- msg3.waitForFinished(5000);
-
- QCOMPARE(msg3.verifySuccess(), false);
- QCOMPARE(msg3.errorCode(), QCA::SecureMessage::ErrorUnknown);
+ QByteArray messageData;
+ if (msg.success()) {
+ messageData = msg.read();
+ } else {
+ qDebug() << "Failure:" << msg.errorCode();
+ QFAIL("Failed to sign in Message format");
+ }
+ // qDebug() << "Message format data:" << messageData;
+
+ // OK, now lets verify that the result will verify.
+ // let's do it
+ QCA::OpenPGP pgp2;
+ QCA::SecureMessage msg2(&pgp2);
+ msg2.setFormat(QCA::SecureMessage::Ascii);
+ msg2.startVerify();
+ msg2.update(messageData);
+ msg2.end();
+ msg2.waitForFinished(5000);
+
+ QVERIFY(msg2.verifySuccess());
+
+ if (msg2.success()) {
+ QCOMPARE(msg2.read(), plain);
+ } else {
+ qDebug() << "Failure:" << msg2.errorCode();
+ QFAIL("Failed to verify message");
+ }
+
+ // why is this here?
+ if (false == oldGNUPGHOME.isNull()) {
+ qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
+ }
+
+ // now test that if we corrupt the message, it no longer
+ // verifies correctly.
+ messageData.replace('T', 't');
+ messageData.replace('w', 'W');
+ QCA::SecureMessage msg3(&pgp2);
+ msg3.setFormat(QCA::SecureMessage::Ascii);
+ msg3.startVerify();
+ msg3.update(messageData);
+ msg3.end();
+ msg3.waitForFinished(5000);
+
+ QCOMPARE(msg3.verifySuccess(), false);
+ QCOMPARE(msg3.errorCode(), QCA::SecureMessage::ErrorUnknown);
}
- if ( false == oldGNUPGHOME.isNull() ) {
- qca_setenv( "GNUPGHOME", oldGNUPGHOME.data(), 1 );
+ if (false == oldGNUPGHOME.isNull()) {
+ qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
}
}
-
void PgpUnitTest::testClearsign()
{
QCA::Initializer qcaInit;
// event handling cannot be used in the same thread as synchronous calls
// which might require event handling. let's put our event handler in
// a side thread so that we can write the unit test synchronously.
PGPPassphraseProviderThread thread;
thread.start();
// This keyring has a private / public key pair
- QByteArray oldGNUPGHOME = qgetenv( "GNUPGHOME" );
- if ( 0 != qca_setenv( "GNUPGHOME", "./keys3_work", 1 ) ) {
- QFAIL( "Expected to be able to set the GNUPGHOME environment variable, but couldn't" );
+ QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
+ if (0 != qca_setenv("GNUPGHOME", "./keys3_work", 1)) {
+ QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
}
-
+
// activate the KeyStoreManager
QCA::KeyStoreManager::start();
QCA::KeyStoreManager keyManager(this);
keyManager.waitForBusyFinished();
- if ( QCA::isSupported( QStringList( QString( "openpgp" ) ), QString( "qca-gnupg" ) ) ||
- QCA::isSupported( QStringList( QString( "keystorelist" ) ), QString( "qca-gnupg" ) ) ) {
+ if (QCA::isSupported(QStringList(QString("openpgp")), QString("qca-gnupg")) ||
+ QCA::isSupported(QStringList(QString("keystorelist")), QString("qca-gnupg"))) {
QStringList storeIds = keyManager.keyStores();
- QVERIFY( storeIds.contains( "qca-gnupg" ) );
-
- QCA::KeyStore pgpStore( QString("qca-gnupg"), &keyManager );
- QVERIFY( pgpStore.isValid() );
-
- QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
- QCOMPARE( keylist.count(), 1 );
-
- QCA::KeyStoreEntry myPGPKey = keylist.at(0);
- QCOMPARE( myPGPKey.isNull(), false );
- QCOMPARE( myPGPKey.name(), QString("Qca Test Key (This key is only for QCA unit tests) <qca@example.com>") );
- QCOMPARE( myPGPKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey );
- QCOMPARE( myPGPKey.id(), QString("9E946237DAFCCFF4") );
- QVERIFY( myPGPKey.keyBundle().isNull() );
- QVERIFY( myPGPKey.certificate().isNull() );
- QVERIFY( myPGPKey.crl().isNull() );
- QCOMPARE( myPGPKey.pgpSecretKey().isNull(), false );
- QCOMPARE( myPGPKey.pgpPublicKey().isNull(), false );
-
- // first make the SecureMessageKey
- QCA::SecureMessageKey key;
- key.setPGPSecretKey( myPGPKey.pgpSecretKey() );
- QVERIFY( key.havePrivate() );
-
- // our data to sign
- QByteArray plain = "Hello, world";
-
- // let's do it
- QCA::OpenPGP pgp;
- QCA::SecureMessage msg(&pgp);
- msg.setSigner(key);
- msg.setFormat(QCA::SecureMessage::Ascii);
- msg.startSign(QCA::SecureMessage::Clearsign);
- msg.update(plain);
- msg.end();
- msg.waitForFinished(5000);
+ QVERIFY(storeIds.contains("qca-gnupg"));
+
+ QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
+ QVERIFY(pgpStore.isValid());
+
+ QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
+ QCOMPARE(keylist.count(), 1);
+
+ QCA::KeyStoreEntry myPGPKey = keylist.at(0);
+ QCOMPARE(myPGPKey.isNull(), false);
+ QCOMPARE(myPGPKey.name(), QString("Qca Test Key (This key is only for QCA unit tests) <qca@example.com>"));
+ QCOMPARE(myPGPKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
+ QCOMPARE(myPGPKey.id(), QString("9E946237DAFCCFF4"));
+ QVERIFY(myPGPKey.keyBundle().isNull());
+ QVERIFY(myPGPKey.certificate().isNull());
+ QVERIFY(myPGPKey.crl().isNull());
+ QCOMPARE(myPGPKey.pgpSecretKey().isNull(), false);
+ QCOMPARE(myPGPKey.pgpPublicKey().isNull(), false);
+
+ // first make the SecureMessageKey
+ QCA::SecureMessageKey key;
+ key.setPGPSecretKey(myPGPKey.pgpSecretKey());
+ QVERIFY(key.havePrivate());
+
+ // our data to sign
+ QByteArray plain = "Hello, world";
+
+ // let's do it
+ QCA::OpenPGP pgp;
+ QCA::SecureMessage msg(&pgp);
+ msg.setSigner(key);
+ msg.setFormat(QCA::SecureMessage::Ascii);
+ msg.startSign(QCA::SecureMessage::Clearsign);
+ msg.update(plain);
+ msg.end();
+ msg.waitForFinished(5000);
#if 0
QString str = QCA::KeyStoreManager::diagnosticText();
QCA::KeyStoreManager::clearDiagnosticText();
QStringList lines = str.split('\n', QString::SkipEmptyParts);
- for(int n = 0; n < lines.count(); ++n)
- fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ for (int n = 0; n < lines.count(); ++n) {
+ fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ }
QString out = msg.diagnosticText();
QStringList msglines = out.split('\n', QString::SkipEmptyParts);
- for(int n = 0; n < msglines.count(); ++n)
- fprintf(stderr, "message: %s\n", qPrintable(msglines[n]));
+ for (int n = 0; n < msglines.count(); ++n) {
+ fprintf(stderr, "message: %s\n", qPrintable(msglines[n]));
+ }
#endif
- QByteArray clearsignedData;
- if(msg.success()) {
- clearsignedData = msg.read();
- } else {
- qDebug() << "Failure:" << msg.errorCode();
- QFAIL("Failed to clearsign");
- }
-
- // OK, now lets verify that the result will verify.
- // let's do it
- QCA::OpenPGP pgp2;
- QCA::SecureMessage msg2(&pgp2);
- msg2.setFormat(QCA::SecureMessage::Ascii);
- msg2.startVerify();
- msg2.update(clearsignedData);
- msg2.end();
- msg2.waitForFinished(5000);
-
- QVERIFY(msg2.verifySuccess());
-
- if(msg2.success()) {
- // The trimmed() call is needed because clearsigning
- // trashes whitespace
- QCOMPARE( QString(msg2.read()).trimmed(), QString(plain).trimmed() );
- } else {
- qDebug() << "Failure:" << msg2.errorCode();
- QFAIL("Failed to verify clearsigned message");
- }
+ QByteArray clearsignedData;
+ if (msg.success()) {
+ clearsignedData = msg.read();
+ } else {
+ qDebug() << "Failure:" << msg.errorCode();
+ QFAIL("Failed to clearsign");
+ }
+
+ // OK, now lets verify that the result will verify.
+ // let's do it
+ QCA::OpenPGP pgp2;
+ QCA::SecureMessage msg2(&pgp2);
+ msg2.setFormat(QCA::SecureMessage::Ascii);
+ msg2.startVerify();
+ msg2.update(clearsignedData);
+ msg2.end();
+ msg2.waitForFinished(5000);
+
+ QVERIFY(msg2.verifySuccess());
+
+ if (msg2.success()) {
+ // The trimmed() call is needed because clearsigning
+ // trashes whitespace
+ QCOMPARE(QString(msg2.read()).trimmed(), QString(plain).trimmed());
+ } else {
+ qDebug() << "Failure:" << msg2.errorCode();
+ QFAIL("Failed to verify clearsigned message");
+ }
}
- if ( false == oldGNUPGHOME.isNull() ) {
- qca_setenv( "GNUPGHOME", oldGNUPGHOME.data(), 1 );
+ if (false == oldGNUPGHOME.isNull()) {
+ qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
}
}
-
void PgpUnitTest::testDetachedSign()
{
QCA::Initializer qcaInit;
// event handling cannot be used in the same thread as synchronous calls
// which might require event handling. let's put our event handler in
// a side thread so that we can write the unit test synchronously.
PGPPassphraseProviderThread thread;
thread.start();
// This keyring has a private / public key pair
- QByteArray oldGNUPGHOME = qgetenv( "GNUPGHOME" );
- if ( 0 != qca_setenv( "GNUPGHOME", "./keys3_work", 1 ) ) {
- QFAIL( "Expected to be able to set the GNUPGHOME environment variable, but couldn't" );
+ QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
+ if (0 != qca_setenv("GNUPGHOME", "./keys3_work", 1)) {
+ QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
}
-
+
// activate the KeyStoreManager
QCA::KeyStoreManager::start();
QCA::KeyStoreManager keyManager(this);
keyManager.waitForBusyFinished();
- if ( QCA::isSupported( QStringList( QString( "openpgp" ) ), QString( "qca-gnupg" ) ) ||
- QCA::isSupported( QStringList( QString( "keystorelist" ) ), QString( "qca-gnupg" ) ) ) {
+ if (QCA::isSupported(QStringList(QString("openpgp")), QString("qca-gnupg")) ||
+ QCA::isSupported(QStringList(QString("keystorelist")), QString("qca-gnupg"))) {
QStringList storeIds = keyManager.keyStores();
- QVERIFY( storeIds.contains( "qca-gnupg" ) );
-
- QCA::KeyStore pgpStore( QString("qca-gnupg"), &keyManager );
- QVERIFY( pgpStore.isValid() );
-
- QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
- QCOMPARE( keylist.count(), 1 );
-
- QCA::KeyStoreEntry myPGPKey = keylist.at(0);
- QCOMPARE( myPGPKey.isNull(), false );
- QCOMPARE( myPGPKey.name(), QString("Qca Test Key (This key is only for QCA unit tests) <qca@example.com>") );
- QCOMPARE( myPGPKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey );
- QCOMPARE( myPGPKey.id(), QString("9E946237DAFCCFF4") );
- QVERIFY( myPGPKey.keyBundle().isNull() );
- QVERIFY( myPGPKey.certificate().isNull() );
- QVERIFY( myPGPKey.crl().isNull() );
- QCOMPARE( myPGPKey.pgpSecretKey().isNull(), false );
- QCOMPARE( myPGPKey.pgpPublicKey().isNull(), false );
-
- // first make the SecureMessageKey
- QCA::SecureMessageKey key;
- key.setPGPSecretKey( myPGPKey.pgpSecretKey() );
- QVERIFY( key.havePrivate() );
-
- // our data to sign
- QByteArray plain = "Hello, world";
-
- // let's do it
- QCA::OpenPGP pgp;
- QCA::SecureMessage msg(&pgp);
- msg.setSigner(key);
- msg.setFormat(QCA::SecureMessage::Ascii);
- msg.startSign(QCA::SecureMessage::Detached);
- msg.update(plain);
- msg.end();
- msg.waitForFinished(5000);
+ QVERIFY(storeIds.contains("qca-gnupg"));
+
+ QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
+ QVERIFY(pgpStore.isValid());
+
+ QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
+ QCOMPARE(keylist.count(), 1);
+
+ QCA::KeyStoreEntry myPGPKey = keylist.at(0);
+ QCOMPARE(myPGPKey.isNull(), false);
+ QCOMPARE(myPGPKey.name(), QString("Qca Test Key (This key is only for QCA unit tests) <qca@example.com>"));
+ QCOMPARE(myPGPKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
+ QCOMPARE(myPGPKey.id(), QString("9E946237DAFCCFF4"));
+ QVERIFY(myPGPKey.keyBundle().isNull());
+ QVERIFY(myPGPKey.certificate().isNull());
+ QVERIFY(myPGPKey.crl().isNull());
+ QCOMPARE(myPGPKey.pgpSecretKey().isNull(), false);
+ QCOMPARE(myPGPKey.pgpPublicKey().isNull(), false);
+
+ // first make the SecureMessageKey
+ QCA::SecureMessageKey key;
+ key.setPGPSecretKey(myPGPKey.pgpSecretKey());
+ QVERIFY(key.havePrivate());
+
+ // our data to sign
+ QByteArray plain = "Hello, world";
+
+ // let's do it
+ QCA::OpenPGP pgp;
+ QCA::SecureMessage msg(&pgp);
+ msg.setSigner(key);
+ msg.setFormat(QCA::SecureMessage::Ascii);
+ msg.startSign(QCA::SecureMessage::Detached);
+ msg.update(plain);
+ msg.end();
+ msg.waitForFinished(5000);
#if 0
QString str = QCA::KeyStoreManager::diagnosticText();
QCA::KeyStoreManager::clearDiagnosticText();
QStringList lines = str.split('\n', QString::SkipEmptyParts);
- for(int n = 0; n < lines.count(); ++n)
- fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ for (int n = 0; n < lines.count(); ++n) {
+ fprintf(stderr, "keystore: %s\n", qPrintable(lines[n]));
+ }
QString out = msg.diagnosticText();
QStringList msglines = out.split('\n', QString::SkipEmptyParts);
- for(int n = 0; n < msglines.count(); ++n)
- fprintf(stderr, "message: %s\n", qPrintable(msglines[n]));
+ for (int n = 0; n < msglines.count(); ++n) {
+ fprintf(stderr, "message: %s\n", qPrintable(msglines[n]));
+ }
#endif
- QByteArray detachedSignature;
- if(msg.success()) {
- detachedSignature = msg.signature();
- } else {
- qDebug() << "Failure:" << msg.errorCode();
- QFAIL("Failed to create detached signature");
- }
-
- // qDebug() << "result:" << detachedSignature;
-
+ QByteArray detachedSignature;
+ if (msg.success()) {
+ detachedSignature = msg.signature();
+ } else {
+ qDebug() << "Failure:" << msg.errorCode();
+ QFAIL("Failed to create detached signature");
+ }
- // OK, now lets verify that the resulting signature will verify.
- // let's do it
- QCA::OpenPGP pgp2;
- QCA::SecureMessage msg2( &pgp2 );
- msg2.setFormat( QCA::SecureMessage::Ascii );
- msg2.startVerify( detachedSignature );
- msg2.update( plain );
- msg2.end();
- msg2.waitForFinished( 2000 );
+ // qDebug() << "result:" << detachedSignature;
- QVERIFY(msg2.verifySuccess());
+ // OK, now lets verify that the resulting signature will verify.
+ // let's do it
+ QCA::OpenPGP pgp2;
+ QCA::SecureMessage msg2(&pgp2);
+ msg2.setFormat(QCA::SecureMessage::Ascii);
+ msg2.startVerify(detachedSignature);
+ msg2.update(plain);
+ msg2.end();
+ msg2.waitForFinished(2000);
+ QVERIFY(msg2.verifySuccess());
- // If the message is different, it shouldn't verify any more
- QCA::SecureMessage msg3( &pgp2 );
- msg3.setFormat( QCA::SecureMessage::Ascii );
- msg3.startVerify( detachedSignature );
- msg3.update( plain+'1' );
- msg3.end();
- msg3.waitForFinished( 2000 );
+ // If the message is different, it shouldn't verify any more
+ QCA::SecureMessage msg3(&pgp2);
+ msg3.setFormat(QCA::SecureMessage::Ascii);
+ msg3.startVerify(detachedSignature);
+ msg3.update(plain + '1');
+ msg3.end();
+ msg3.waitForFinished(2000);
- QCOMPARE( msg3.verifySuccess(), false );
+ QCOMPARE(msg3.verifySuccess(), false);
- QCOMPARE( msg3.errorCode(), QCA::SecureMessage::ErrorUnknown );
+ QCOMPARE(msg3.errorCode(), QCA::SecureMessage::ErrorUnknown);
}
// Restore things to the way they were....
- if ( false == oldGNUPGHOME.isNull() ) {
- qca_setenv( "GNUPGHOME", oldGNUPGHOME.data(), 1 );
+ if (false == oldGNUPGHOME.isNull()) {
+ qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
}
}
-
void PgpUnitTest::testSignaturesWithExpiredSubkeys()
{
- // This previously failing test tests signatures from
- // keys with expired subkeys, while assuring no loss
- // of functionality.
-
- QCA::Initializer qcaInit;
-
- PGPPassphraseProviderThread thread;
- thread.start();
-
- QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
- if (qca_setenv("GNUPGHOME", "./keys4_expired_subkeys_work", 1) != 0) {
- QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't" );
- }
-
- QCA::KeyStoreManager::start();
-
- QCA::KeyStoreManager keyManager(this);
- keyManager.waitForBusyFinished();
-
- if (QCA::isSupported(QStringList(QString("openpgp")), QString("qca-gnupg")) ||
- QCA::isSupported(QStringList(QString("keystorelist")), QString( "qca-gnupg"))) {
-
- QStringList storeIds = keyManager.keyStores();
- QVERIFY(storeIds.contains("qca-gnupg"));
-
- QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
- QVERIFY(pgpStore.isValid());
-
- QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
-
- QCA::KeyStoreEntry validKey;
- foreach(const QCA::KeyStoreEntry key, keylist) {
- if (key.id() == "DD773CA7E4E22769") {
- validKey = key;
- }
- }
-
- QCOMPARE(validKey.isNull(), false);
- QCOMPARE(validKey.name(), QString("QCA Test Key (Unit test key for expired subkeys) <qca@example.com>"));
- QCOMPARE(validKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
- QCOMPARE(validKey.id(), QString("DD773CA7E4E22769"));
- QCOMPARE(validKey.pgpSecretKey().isNull(), false);
- QCOMPARE(validKey.pgpPublicKey().isNull(), false);
-
- // Create a signature with the non-expired primary key first
- QByteArray validMessage("Non-expired key signature");
-
- QCA::SecureMessageKey secKey;
- secKey.setPGPSecretKey(validKey.pgpSecretKey());
- QVERIFY(secKey.havePrivate());
-
- QCA::OpenPGP pgp;
- QCA::SecureMessage msg(&pgp);
- msg.setSigner(secKey);
- msg.setFormat(QCA::SecureMessage::Ascii);
- msg.startSign(QCA::SecureMessage::Clearsign);
- msg.update(validMessage);
- msg.end();
- msg.waitForFinished(5000);
-
- QVERIFY(msg.success());
-
- QByteArray nonExpiredKeySignature = msg.read();
-
- // Verify it
- QCA::OpenPGP pgp1;
- QCA::SecureMessage msg1(&pgp1);
- msg1.setFormat(QCA::SecureMessage::Ascii);
- msg1.startVerify();
- msg1.update(nonExpiredKeySignature);
- msg1.end();
- msg1.waitForFinished(5000);
-
- QByteArray signedResult = msg1.read();
-
- QVERIFY(msg1.verifySuccess());
- QCOMPARE(QString(signedResult).trimmed(), QString(validMessage).trimmed());
-
- // Test signature made by the expired subkey
- QByteArray expiredKeySignature("-----BEGIN PGP SIGNED MESSAGE-----\n"
- "Hash: SHA1\n"
- "\n"
- "Expired signature\n"
- "-----BEGIN PGP SIGNATURE-----\n"
- "Version: GnuPG v1\n"
- "\n"
- "iQEcBAEBAgAGBQJTaI2VAAoJEPddwMGvBiCrA18H/RMJxnEnyNERd19ffTdSLvHH\n"
- "iwsfTEPmFQSpmCUnmjK2IIMXWTi6ofinGTWEsXKHSTqgytz715Q16OICwnFoeHin\n"
- "0SnsTgi5lH5QcJPJ5PqoRwgAy8vhy73EpYrv7zqLom1Qm/9NeGtNZsohjp0ECFEk\n"
- "4UmZiJF7u5Yn6hBl9btIPRTjI2FrXjr3Zy8jZijRaZMutnz5VveBHCLu00NvJQkG\n"
- "PC/ZvvfGOk9SeaApnrnntfdKJ4geKxoT0+r+Yz1kQ1VKG5Af3JziBwwNID6g/FYv\n"
- "cDK2no5KD7lyASAt6veCDXBdUmNatBO5Au9eE0jJwsSV6LZCpEYEcgBsnfDwxls=\n"
- "=UM6K\n"
- "-----END PGP SIGNATURE-----\n");
-
- QCA::OpenPGP pgp2;
- QCA::SecureMessage msg2(&pgp2);
- msg2.setFormat(QCA::SecureMessage::Ascii);
- msg2.startVerify();
- msg2.update(expiredKeySignature);
- msg2.end();
- msg2.waitForFinished(5000);
-
- QCOMPARE(msg2.verifySuccess(), false);
- QCOMPARE(msg2.errorCode(), QCA::SecureMessage::ErrorSignerExpired);
-
- // Test signature made by the revoked subkey
- QByteArray revokedKeySignature("-----BEGIN PGP SIGNED MESSAGE-----\n"
- "Hash: SHA1\n"
- "\n"
- "Revoked signature\n"
- "-----BEGIN PGP SIGNATURE-----\n"
- "Version: GnuPG v1\n"
- "\n"
- "iQEcBAEBAgAGBQJTd2AmAAoJEJwx7xWvfHTUCZMH/310hMg68H9kYWqKO12Qvyl7\n"
- "SlkHBxRsD1sKIBM10qxh6262582mbdAbObVCSFlHVR5NU2tDN5B67J9NU2KnwCcq\n"
- "Ny7Oj06UGEkZRmGA23BZ78w/xhPr2Xg80lckBIfGWCvezjSoAeOonk4WREpqzSUr\n"
- "sXX8iioBh98ySuQp4rtzf1j0sGB2Tui/bZybiLwz+/fBzW9ITSV0OXmeT5BfBhJU\n"
- "XXnOBXDwPUrJQPHxpGpX0s7iyElfZ2ws/PNqUJiWdmxqwLnndn1y5UECDC2T0FpC\n"
- "erOM27tQeEthdrZTjMjV47p1ilNgNJrMI328ovehABYyobK9UlnFHcUnn/1OFRw=\n"
- "=sE1o\n"
- "-----END PGP SIGNATURE-----\n");
-
- QCA::OpenPGP pgp3;
- QCA::SecureMessage msg3(&pgp3);
- msg3.setFormat(QCA::SecureMessage::Ascii);
- msg3.startVerify();
- msg3.update(revokedKeySignature);
- msg3.end();
- msg3.waitForFinished(5000);
-
- QCOMPARE(msg3.verifySuccess(), false);
- QCOMPARE(msg3.errorCode(), QCA::SecureMessage::ErrorSignerRevoked);
-
- // Test expired signature
- QByteArray expiredSignature("-----BEGIN PGP SIGNED MESSAGE-----\n"
- "Hash: SHA1\n"
- "\n"
- "Valid key, expired signature\n"
- "-----BEGIN PGP SIGNATURE-----\n"
- "Version: GnuPG v1\n"
- "\n"
- "iQEiBAEBAgAMBQJTkjUvBYMAAVGAAAoJEN13PKfk4idpItIH/1BpFQkPm8fQV0bd\n"
- "37qaXf7IWr7bsPBcb7NjR9EmB6Zl6wnmSKW9mvKvs0ZJ1HxyHx0yC5UQWsgTj3do\n"
- "xGDP4nJvi0L7EDUukZApWu98nFwrnTrLEd+JMwlpYDhtaljq2qQo7u7CsqyoE2cL\n"
- "nRuPkc+lRbDMlqGXk2QFPL8Wu7gW/ndJ8nQ0Dq+22q77Hh1PcyFlggTBxhLA4Svk\n"
- "Hx2I4bUjaUq5P4g9kFeXx6/0n31FCa+uThSkWWjH1OeLEXrUZSH/8nBWcnJ3IGbt\n"
- "W2bmHhTUx3tYt9aHc+1kje2bAT01xN974r+wS/XNT4cWw7ZSSvukEIjjieUMP4eQ\n"
- "S/H6RmM=\n"
- "=9pAJ\n"
- "-----END PGP SIGNATURE-----\n");
-
- QCA::OpenPGP pgp4;
- QCA::SecureMessage msg4(&pgp4);
- msg4.setFormat(QCA::SecureMessage::Ascii);
- msg4.startVerify();
- msg4.update(expiredSignature);
- msg4.end();
- msg4.waitForFinished(5000);
-
- QCOMPARE(msg4.verifySuccess(), false);
- QCOMPARE(msg4.errorCode(), QCA::SecureMessage::ErrorSignatureExpired);
- }
-
- if (!oldGNUPGHOME.isNull()) {
- qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
- }
+ // This previously failing test tests signatures from
+ // keys with expired subkeys, while assuring no loss
+ // of functionality.
+
+ QCA::Initializer qcaInit;
+
+ PGPPassphraseProviderThread thread;
+ thread.start();
+
+ QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
+ if (qca_setenv("GNUPGHOME", "./keys4_expired_subkeys_work", 1) != 0) {
+ QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
+ }
+
+ QCA::KeyStoreManager::start();
+
+ QCA::KeyStoreManager keyManager(this);
+ keyManager.waitForBusyFinished();
+
+ if (QCA::isSupported(QStringList(QString("openpgp")), QString("qca-gnupg")) ||
+ QCA::isSupported(QStringList(QString("keystorelist")), QString("qca-gnupg"))) {
+
+ QStringList storeIds = keyManager.keyStores();
+ QVERIFY(storeIds.contains("qca-gnupg"));
+
+ QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
+ QVERIFY(pgpStore.isValid());
+
+ QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
+
+ QCA::KeyStoreEntry validKey;
+ foreach (const QCA::KeyStoreEntry key, keylist) {
+ if (key.id() == "DD773CA7E4E22769") {
+ validKey = key;
+ }
+ }
+
+ QCOMPARE(validKey.isNull(), false);
+ QCOMPARE(validKey.name(), QString("QCA Test Key (Unit test key for expired subkeys) <qca@example.com>"));
+ QCOMPARE(validKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
+ QCOMPARE(validKey.id(), QString("DD773CA7E4E22769"));
+ QCOMPARE(validKey.pgpSecretKey().isNull(), false);
+ QCOMPARE(validKey.pgpPublicKey().isNull(), false);
+
+ // Create a signature with the non-expired primary key first
+ QByteArray validMessage("Non-expired key signature");
+
+ QCA::SecureMessageKey secKey;
+ secKey.setPGPSecretKey(validKey.pgpSecretKey());
+ QVERIFY(secKey.havePrivate());
+
+ QCA::OpenPGP pgp;
+ QCA::SecureMessage msg(&pgp);
+ msg.setSigner(secKey);
+ msg.setFormat(QCA::SecureMessage::Ascii);
+ msg.startSign(QCA::SecureMessage::Clearsign);
+ msg.update(validMessage);
+ msg.end();
+ msg.waitForFinished(5000);
+
+ QVERIFY(msg.success());
+
+ QByteArray nonExpiredKeySignature = msg.read();
+
+ // Verify it
+ QCA::OpenPGP pgp1;
+ QCA::SecureMessage msg1(&pgp1);
+ msg1.setFormat(QCA::SecureMessage::Ascii);
+ msg1.startVerify();
+ msg1.update(nonExpiredKeySignature);
+ msg1.end();
+ msg1.waitForFinished(5000);
+
+ QByteArray signedResult = msg1.read();
+
+ QVERIFY(msg1.verifySuccess());
+ QCOMPARE(QString(signedResult).trimmed(), QString(validMessage).trimmed());
+
+ // Test signature made by the expired subkey
+ QByteArray expiredKeySignature("-----BEGIN PGP SIGNED MESSAGE-----\n"
+ "Hash: SHA1\n"
+ "\n"
+ "Expired signature\n"
+ "-----BEGIN PGP SIGNATURE-----\n"
+ "Version: GnuPG v1\n"
+ "\n"
+ "iQEcBAEBAgAGBQJTaI2VAAoJEPddwMGvBiCrA18H/RMJxnEnyNERd19ffTdSLvHH\n"
+ "iwsfTEPmFQSpmCUnmjK2IIMXWTi6ofinGTWEsXKHSTqgytz715Q16OICwnFoeHin\n"
+ "0SnsTgi5lH5QcJPJ5PqoRwgAy8vhy73EpYrv7zqLom1Qm/9NeGtNZsohjp0ECFEk\n"
+ "4UmZiJF7u5Yn6hBl9btIPRTjI2FrXjr3Zy8jZijRaZMutnz5VveBHCLu00NvJQkG\n"
+ "PC/ZvvfGOk9SeaApnrnntfdKJ4geKxoT0+r+Yz1kQ1VKG5Af3JziBwwNID6g/FYv\n"
+ "cDK2no5KD7lyASAt6veCDXBdUmNatBO5Au9eE0jJwsSV6LZCpEYEcgBsnfDwxls=\n"
+ "=UM6K\n"
+ "-----END PGP SIGNATURE-----\n");
+
+ QCA::OpenPGP pgp2;
+ QCA::SecureMessage msg2(&pgp2);
+ msg2.setFormat(QCA::SecureMessage::Ascii);
+ msg2.startVerify();
+ msg2.update(expiredKeySignature);
+ msg2.end();
+ msg2.waitForFinished(5000);
+
+ QCOMPARE(msg2.verifySuccess(), false);
+ QCOMPARE(msg2.errorCode(), QCA::SecureMessage::ErrorSignerExpired);
+
+ // Test signature made by the revoked subkey
+ QByteArray revokedKeySignature("-----BEGIN PGP SIGNED MESSAGE-----\n"
+ "Hash: SHA1\n"
+ "\n"
+ "Revoked signature\n"
+ "-----BEGIN PGP SIGNATURE-----\n"
+ "Version: GnuPG v1\n"
+ "\n"
+ "iQEcBAEBAgAGBQJTd2AmAAoJEJwx7xWvfHTUCZMH/310hMg68H9kYWqKO12Qvyl7\n"
+ "SlkHBxRsD1sKIBM10qxh6262582mbdAbObVCSFlHVR5NU2tDN5B67J9NU2KnwCcq\n"
+ "Ny7Oj06UGEkZRmGA23BZ78w/xhPr2Xg80lckBIfGWCvezjSoAeOonk4WREpqzSUr\n"
+ "sXX8iioBh98ySuQp4rtzf1j0sGB2Tui/bZybiLwz+/fBzW9ITSV0OXmeT5BfBhJU\n"
+ "XXnOBXDwPUrJQPHxpGpX0s7iyElfZ2ws/PNqUJiWdmxqwLnndn1y5UECDC2T0FpC\n"
+ "erOM27tQeEthdrZTjMjV47p1ilNgNJrMI328ovehABYyobK9UlnFHcUnn/1OFRw=\n"
+ "=sE1o\n"
+ "-----END PGP SIGNATURE-----\n");
+
+ QCA::OpenPGP pgp3;
+ QCA::SecureMessage msg3(&pgp3);
+ msg3.setFormat(QCA::SecureMessage::Ascii);
+ msg3.startVerify();
+ msg3.update(revokedKeySignature);
+ msg3.end();
+ msg3.waitForFinished(5000);
+
+ QCOMPARE(msg3.verifySuccess(), false);
+ QCOMPARE(msg3.errorCode(), QCA::SecureMessage::ErrorSignerRevoked);
+
+ // Test expired signature
+ QByteArray expiredSignature("-----BEGIN PGP SIGNED MESSAGE-----\n"
+ "Hash: SHA1\n"
+ "\n"
+ "Valid key, expired signature\n"
+ "-----BEGIN PGP SIGNATURE-----\n"
+ "Version: GnuPG v1\n"
+ "\n"
+ "iQEiBAEBAgAMBQJTkjUvBYMAAVGAAAoJEN13PKfk4idpItIH/1BpFQkPm8fQV0bd\n"
+ "37qaXf7IWr7bsPBcb7NjR9EmB6Zl6wnmSKW9mvKvs0ZJ1HxyHx0yC5UQWsgTj3do\n"
+ "xGDP4nJvi0L7EDUukZApWu98nFwrnTrLEd+JMwlpYDhtaljq2qQo7u7CsqyoE2cL\n"
+ "nRuPkc+lRbDMlqGXk2QFPL8Wu7gW/ndJ8nQ0Dq+22q77Hh1PcyFlggTBxhLA4Svk\n"
+ "Hx2I4bUjaUq5P4g9kFeXx6/0n31FCa+uThSkWWjH1OeLEXrUZSH/8nBWcnJ3IGbt\n"
+ "W2bmHhTUx3tYt9aHc+1kje2bAT01xN974r+wS/XNT4cWw7ZSSvukEIjjieUMP4eQ\n"
+ "S/H6RmM=\n"
+ "=9pAJ\n"
+ "-----END PGP SIGNATURE-----\n");
+
+ QCA::OpenPGP pgp4;
+ QCA::SecureMessage msg4(&pgp4);
+ msg4.setFormat(QCA::SecureMessage::Ascii);
+ msg4.startVerify();
+ msg4.update(expiredSignature);
+ msg4.end();
+ msg4.waitForFinished(5000);
+
+ QCOMPARE(msg4.verifySuccess(), false);
+ QCOMPARE(msg4.errorCode(), QCA::SecureMessage::ErrorSignatureExpired);
+ }
+
+ if (!oldGNUPGHOME.isNull()) {
+ qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
+ }
}
void PgpUnitTest::testEncryptionWithExpiredSubkeys()
{
- // This previously failing test tests encrypting to
- // keys with expired subkeys, while assuring no loss
- // of functionality.
-
- QCA::Initializer qcaInit;
-
- PGPPassphraseProviderThread thread;
- thread.start();
-
- QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
- if (qca_setenv("GNUPGHOME", "./keys4_expired_subkeys_work", 1) != 0) {
- QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
- }
-
- QCA::KeyStoreManager::start();
-
- QCA::KeyStoreManager keyManager(this);
- keyManager.waitForBusyFinished();
-
- if (QCA::isSupported(QStringList(QString("openpgp")), QString("qca-gnupg")) ||
- QCA::isSupported(QStringList(QString("keystorelist")), QString("qca-gnupg"))) {
-
- QStringList storeIds = keyManager.keyStores();
- QVERIFY(storeIds.contains("qca-gnupg"));
-
- QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
- QVERIFY(pgpStore.isValid());
-
- QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
-
- QCA::KeyStoreEntry validKey;
- QCA::KeyStoreEntry expiredKey;
- QCA::KeyStoreEntry revokedKey;
- foreach(const QCA::KeyStoreEntry key, keylist) {
- if (key.id() == "FEF97E4C4C870810") {
- validKey = key;
- } else if (key.id() == "DD773CA7E4E22769") {
- expiredKey = key;
- } else if (key.id() == "1D6A028CC4F444A9") {
- revokedKey = key;
- }
- }
-
- QCOMPARE(validKey.isNull(), false);
- QCOMPARE(validKey.name(), QString("QCA Test Key 2 (Non-expired encryption key with expired encryption subkey) <qca@example.com>"));
- QCOMPARE(validKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
- QCOMPARE(validKey.id(), QString("FEF97E4C4C870810"));
- QCOMPARE(validKey.pgpSecretKey().isNull(), false);
- QCOMPARE(validKey.pgpPublicKey().isNull(), false);
-
- QCOMPARE(expiredKey.isNull(), false);
- QCOMPARE(expiredKey.name(), QString("QCA Test Key (Unit test key for expired subkeys) <qca@example.com>"));
- QCOMPARE(expiredKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
- QCOMPARE(expiredKey.id(), QString("DD773CA7E4E22769"));
- QCOMPARE(expiredKey.pgpSecretKey().isNull(), false);
- QCOMPARE(expiredKey.pgpPublicKey().isNull(), false);
-
- QCOMPARE(revokedKey.isNull(), false);
- QCOMPARE(revokedKey.name(), QString("QCA Test Key (Revoked unit test key) <qca@example.com>"));
- QCOMPARE(revokedKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
- QCOMPARE(revokedKey.id(), QString("1D6A028CC4F444A9"));
- QCOMPARE(revokedKey.pgpSecretKey().isNull(), false);
- QCOMPARE(revokedKey.pgpPublicKey().isNull(), false);
-
- // Test encrypting to a non-expired key first
- QByteArray nonExpiredMessage("Encrypting to non-expired subkey");
-
- QCA::SecureMessageKey key;
- key.setPGPPublicKey(validKey.pgpPublicKey());
-
- QCA::OpenPGP pgp;
- QCA::SecureMessage msg(&pgp);
- msg.setFormat(QCA::SecureMessage::Ascii);
- msg.setRecipient(key);
- msg.startEncrypt();
- msg.update(nonExpiredMessage);
- msg.end();
- msg.waitForFinished(5000);
-
- QVERIFY(msg.success());
- QByteArray encResult = msg.read();
-
- // Decrypt and compare it
- QCA::OpenPGP pgp1;
- QCA::SecureMessage msg1(&pgp1);
- msg1.startDecrypt();
- msg1.update(encResult);
- msg1.end();
- msg1.waitForFinished(5000);
-
- QVERIFY(msg1.success());
- QByteArray decResult = msg1.read();
- QCOMPARE(decResult, nonExpiredMessage);
-
- // Test encrypting to the expired key
- QByteArray expiredMessage("Encrypting to the expired key");
-
- QCA::SecureMessageKey key2;
- key2.setPGPPublicKey(expiredKey.pgpPublicKey());
-
- QCA::OpenPGP pgp2;
- QCA::SecureMessage msg2(&pgp2);
- msg2.setFormat(QCA::SecureMessage::Ascii);
- msg2.setRecipient(key2);
- msg2.startEncrypt();
- msg2.update(expiredMessage);
- msg2.end();
- msg2.waitForFinished(5000);
-
- QCOMPARE(msg2.success(), false);
- // Note: If gpg worked as expected, msg.errorCode() should
- // equal QCA::SecureMessage::ErrorEncryptExpired, but currently
- // it omits the reason for failure, so we check for both values.
- QVERIFY((msg2.errorCode() == QCA::SecureMessage::ErrorEncryptExpired) ||
- (msg2.errorCode() == QCA::SecureMessage::ErrorEncryptInvalid));
-
- // Test encrypting to the revoked key
- QByteArray revokedMessage("Encrypting to the revoked key");
-
- QCA::SecureMessageKey key3;
- key3.setPGPPublicKey(expiredKey.pgpPublicKey());
-
- QCA::OpenPGP pgp3;
- QCA::SecureMessage msg3(&pgp3);
- msg3.setFormat(QCA::SecureMessage::Ascii);
- msg3.setRecipient(key3);
- msg3.startEncrypt();
- msg3.update(revokedMessage);
- msg3.end();
- msg3.waitForFinished(5000);
-
- QCOMPARE(msg3.success(), false);
- // Note: If gpg worked as expected, msg.errorCode() should
- // equal QCA::SecureMessage::ErrorEncryptRevoked, but currently
- // it omits the reason for failure, so we check for both values.
- QVERIFY((msg3.errorCode() == QCA::SecureMessage::ErrorEncryptRevoked) ||
- (msg3.errorCode() == QCA::SecureMessage::ErrorEncryptInvalid));
- }
-
- if (!oldGNUPGHOME.isNull()) {
- qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
- }
-}
+ // This previously failing test tests encrypting to
+ // keys with expired subkeys, while assuring no loss
+ // of functionality.
+
+ QCA::Initializer qcaInit;
+
+ PGPPassphraseProviderThread thread;
+ thread.start();
+
+ QByteArray oldGNUPGHOME = qgetenv("GNUPGHOME");
+ if (qca_setenv("GNUPGHOME", "./keys4_expired_subkeys_work", 1) != 0) {
+ QFAIL("Expected to be able to set the GNUPGHOME environment variable, but couldn't");
+ }
+
+ QCA::KeyStoreManager::start();
+
+ QCA::KeyStoreManager keyManager(this);
+ keyManager.waitForBusyFinished();
+
+ if (QCA::isSupported(QStringList(QString("openpgp")), QString("qca-gnupg")) ||
+ QCA::isSupported(QStringList(QString("keystorelist")), QString("qca-gnupg"))) {
+ QStringList storeIds = keyManager.keyStores();
+ QVERIFY(storeIds.contains("qca-gnupg"));
+
+ QCA::KeyStore pgpStore(QString("qca-gnupg"), &keyManager);
+ QVERIFY(pgpStore.isValid());
+
+ QList<QCA::KeyStoreEntry> keylist = pgpStore.entryList();
+
+ QCA::KeyStoreEntry validKey;
+ QCA::KeyStoreEntry expiredKey;
+ QCA::KeyStoreEntry revokedKey;
+ foreach (const QCA::KeyStoreEntry key, keylist) {
+ if (key.id() == "FEF97E4C4C870810") {
+ validKey = key;
+ } else if (key.id() == "DD773CA7E4E22769") {
+ expiredKey = key;
+ } else if (key.id() == "1D6A028CC4F444A9") {
+ revokedKey = key;
+ }
+ }
+
+ QCOMPARE(validKey.isNull(), false);
+ QCOMPARE(validKey.name(), QString("QCA Test Key 2 (Non-expired encryption key with expired encryption subkey) <qca@example.com>"));
+ QCOMPARE(validKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
+ QCOMPARE(validKey.id(), QString("FEF97E4C4C870810"));
+ QCOMPARE(validKey.pgpSecretKey().isNull(), false);
+ QCOMPARE(validKey.pgpPublicKey().isNull(), false);
+
+ QCOMPARE(expiredKey.isNull(), false);
+ QCOMPARE(expiredKey.name(), QString("QCA Test Key (Unit test key for expired subkeys) <qca@example.com>"));
+ QCOMPARE(expiredKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
+ QCOMPARE(expiredKey.id(), QString("DD773CA7E4E22769"));
+ QCOMPARE(expiredKey.pgpSecretKey().isNull(), false);
+ QCOMPARE(expiredKey.pgpPublicKey().isNull(), false);
+
+ QCOMPARE(revokedKey.isNull(), false);
+ QCOMPARE(revokedKey.name(), QString("QCA Test Key (Revoked unit test key) <qca@example.com>"));
+ QCOMPARE(revokedKey.type(), QCA::KeyStoreEntry::TypePGPSecretKey);
+ QCOMPARE(revokedKey.id(), QString("1D6A028CC4F444A9"));
+ QCOMPARE(revokedKey.pgpSecretKey().isNull(), false);
+ QCOMPARE(revokedKey.pgpPublicKey().isNull(), false);
+
+ // Test encrypting to a non-expired key first
+ QByteArray nonExpiredMessage("Encrypting to non-expired subkey");
+
+ QCA::SecureMessageKey key;
+ key.setPGPPublicKey(validKey.pgpPublicKey());
+
+ QCA::OpenPGP pgp;
+ QCA::SecureMessage msg(&pgp);
+ msg.setFormat(QCA::SecureMessage::Ascii);
+ msg.setRecipient(key);
+ msg.startEncrypt();
+ msg.update(nonExpiredMessage);
+ msg.end();
+ msg.waitForFinished(5000);
+
+ QVERIFY(msg.success());
+ QByteArray encResult = msg.read();
+
+ // Decrypt and compare it
+ QCA::OpenPGP pgp1;
+ QCA::SecureMessage msg1(&pgp1);
+ msg1.startDecrypt();
+ msg1.update(encResult);
+ msg1.end();
+ msg1.waitForFinished(5000);
+
+ QVERIFY(msg1.success());
+ QByteArray decResult = msg1.read();
+ QCOMPARE(decResult, nonExpiredMessage);
+
+ // Test encrypting to the expired key
+ QByteArray expiredMessage("Encrypting to the expired key");
+
+ QCA::SecureMessageKey key2;
+ key2.setPGPPublicKey(expiredKey.pgpPublicKey());
+
+ QCA::OpenPGP pgp2;
+ QCA::SecureMessage msg2(&pgp2);
+ msg2.setFormat(QCA::SecureMessage::Ascii);
+ msg2.setRecipient(key2);
+ msg2.startEncrypt();
+ msg2.update(expiredMessage);
+ msg2.end();
+ msg2.waitForFinished(5000);
+
+ QCOMPARE(msg2.success(), false);
+ // Note: If gpg worked as expected, msg.errorCode() should
+ // equal QCA::SecureMessage::ErrorEncryptExpired, but currently
+ // it omits the reason for failure, so we check for both values.
+ QVERIFY((msg2.errorCode() == QCA::SecureMessage::ErrorEncryptExpired) ||
+ (msg2.errorCode() == QCA::SecureMessage::ErrorEncryptInvalid));
+
+ // Test encrypting to the revoked key
+ QByteArray revokedMessage("Encrypting to the revoked key");
+
+ QCA::SecureMessageKey key3;
+ key3.setPGPPublicKey(expiredKey.pgpPublicKey());
+
+ QCA::OpenPGP pgp3;
+ QCA::SecureMessage msg3(&pgp3);
+ msg3.setFormat(QCA::SecureMessage::Ascii);
+ msg3.setRecipient(key3);
+ msg3.startEncrypt();
+ msg3.update(revokedMessage);
+ msg3.end();
+ msg3.waitForFinished(5000);
+
+ QCOMPARE(msg3.success(), false);
+ // Note: If gpg worked as expected, msg.errorCode() should
+ // equal QCA::SecureMessage::ErrorEncryptRevoked, but currently
+ // it omits the reason for failure, so we check for both values.
+ QVERIFY((msg3.errorCode() == QCA::SecureMessage::ErrorEncryptRevoked) ||
+ (msg3.errorCode() == QCA::SecureMessage::ErrorEncryptInvalid));
+ }
+
+ if (!oldGNUPGHOME.isNull()) {
+ qca_setenv("GNUPGHOME", oldGNUPGHOME.data(), 1);
+ }
+}
QTEST_MAIN(PgpUnitTest)
#include "pgpunittest.moc"
diff --git a/unittest/pipeunittest/pipeunittest.cpp b/unittest/pipeunittest/pipeunittest.cpp
index 6282ef1a..b82422bd 100644
--- a/unittest/pipeunittest/pipeunittest.cpp
+++ b/unittest/pipeunittest/pipeunittest.cpp
@@ -1,263 +1,263 @@
/**
* Copyright (C) 2007 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class PipeUnitTest : public QObject
{
- Q_OBJECT
+ Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void createPipeWithInsecureMemory();
void createPipeWithSecureMemory();
void readWrite();
void readWriteSecure();
void signalTests();
void signalTestsSecure();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void PipeUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void PipeUnitTest::cleanupTestCase()
{
QCA::unloadAllPlugins();
delete m_init;
}
void PipeUnitTest::createPipeWithInsecureMemory()
{
QCA::QPipe pipe1;
// we haven't created the pipe yet, so it shouldn't be valid
- QCOMPARE( pipe1.readEnd().isValid(), false );
- QCOMPARE( pipe1.writeEnd().isValid(), false );
+ QCOMPARE(pipe1.readEnd().isValid(), false);
+ QCOMPARE(pipe1.writeEnd().isValid(), false);
pipe1.create(); // insecure memory used
- QVERIFY( pipe1.readEnd().isValid() );
- QVERIFY( pipe1.readEnd().type() == QCA::QPipeDevice::Read );
- QVERIFY( pipe1.writeEnd().isValid() );
- QVERIFY( pipe1.writeEnd().type() == QCA::QPipeDevice::Write );
+ QVERIFY(pipe1.readEnd().isValid());
+ QVERIFY(pipe1.readEnd().type() == QCA::QPipeDevice::Read);
+ QVERIFY(pipe1.writeEnd().isValid());
+ QVERIFY(pipe1.writeEnd().type() == QCA::QPipeDevice::Write);
pipe1.reset();
- QCOMPARE( pipe1.readEnd().isValid(), false );
- QCOMPARE( pipe1.writeEnd().isValid(), false );
+ QCOMPARE(pipe1.readEnd().isValid(), false);
+ QCOMPARE(pipe1.writeEnd().isValid(), false);
}
void PipeUnitTest::createPipeWithSecureMemory()
{
QCA::QPipe pipe1;
// we haven't created the pipe yet, so it shouldn't be valid
- QCOMPARE( pipe1.readEnd().isValid(), false );
- QCOMPARE( pipe1.writeEnd().isValid(), false );
+ QCOMPARE(pipe1.readEnd().isValid(), false);
+ QCOMPARE(pipe1.writeEnd().isValid(), false);
- pipe1.create( true ); // secure memory used
- QVERIFY( pipe1.readEnd().isValid() );
- QVERIFY( pipe1.readEnd().type() == QCA::QPipeDevice::Read );
- QVERIFY( pipe1.writeEnd().isValid() );
- QVERIFY( pipe1.writeEnd().type() == QCA::QPipeDevice::Write );
+ pipe1.create(true); // secure memory used
+ QVERIFY(pipe1.readEnd().isValid());
+ QVERIFY(pipe1.readEnd().type() == QCA::QPipeDevice::Read);
+ QVERIFY(pipe1.writeEnd().isValid());
+ QVERIFY(pipe1.writeEnd().type() == QCA::QPipeDevice::Write);
pipe1.reset();
- QCOMPARE( pipe1.readEnd().isValid(), false );
- QCOMPARE( pipe1.writeEnd().isValid(), false );
+ QCOMPARE(pipe1.readEnd().isValid(), false);
+ QCOMPARE(pipe1.writeEnd().isValid(), false);
}
void PipeUnitTest::readWrite()
{
QCA::QPipe pipe1;
- QByteArray testData1( "Down the" );
- QByteArray testData2( "pipe!" );
+ QByteArray testData1("Down the");
+ QByteArray testData2("pipe!");
pipe1.create();
- QVERIFY( pipe1.writeEnd().isValid() );
- QVERIFY( pipe1.readEnd().isValid() );
+ QVERIFY(pipe1.writeEnd().isValid());
+ QVERIFY(pipe1.readEnd().isValid());
// enable the pipe ends for read/write
pipe1.writeEnd().enable();
pipe1.readEnd().enable();
- pipe1.writeEnd().write( testData1 );
+ pipe1.writeEnd().write(testData1);
QTest::qWait(1); // process events
QTest::qWait(1); // process events
QByteArray out1 = pipe1.readEnd().read(); // read all...
- QCOMPARE( testData1, out1 );
+ QCOMPARE(testData1, out1);
- pipe1.writeEnd().write( testData1 ); // put it back in
+ pipe1.writeEnd().write(testData1); // put it back in
QTest::qWait(1); // process events
- QCOMPARE( pipe1.readEnd().bytesAvailable(), testData1.size() );
+ QCOMPARE(pipe1.readEnd().bytesAvailable(), testData1.size());
- pipe1.writeEnd().write( testData2 ); // add some more data
+ pipe1.writeEnd().write(testData2); // add some more data
QTest::qWait(1); // process events
- QCOMPARE( pipe1.readEnd().bytesAvailable(), testData1.size() + testData2.size() );
+ QCOMPARE(pipe1.readEnd().bytesAvailable(), testData1.size() + testData2.size());
QByteArray thisRead = pipe1.readEnd().read(1);
- QCOMPARE( thisRead, QByteArray("D") );
+ QCOMPARE(thisRead, QByteArray("D"));
thisRead = pipe1.readEnd().read(3);
- QCOMPARE( thisRead, QByteArray("own") );
+ QCOMPARE(thisRead, QByteArray("own"));
thisRead = pipe1.readEnd().read();
- QCOMPARE( thisRead, QByteArray(" thepipe!") );
+ QCOMPARE(thisRead, QByteArray(" thepipe!"));
}
void PipeUnitTest::readWriteSecure()
{
QCA::QPipe pipe1;
- QCA::SecureArray testData1( "Down the" );
- QCA::SecureArray testData2( " secure pipe!" );
+ QCA::SecureArray testData1("Down the");
+ QCA::SecureArray testData2(" secure pipe!");
pipe1.create(true);
- QVERIFY( pipe1.writeEnd().isValid() );
- QVERIFY( pipe1.readEnd().isValid() );
+ QVERIFY(pipe1.writeEnd().isValid());
+ QVERIFY(pipe1.readEnd().isValid());
// enable the pipe ends for read/write
pipe1.writeEnd().enable();
pipe1.readEnd().enable();
- pipe1.writeEnd().writeSecure( testData1 );
+ pipe1.writeEnd().writeSecure(testData1);
QTest::qWait(1); // process events
QTest::qWait(1); // process events
QCA::SecureArray out1 = pipe1.readEnd().readSecure(); // read all...
- QCOMPARE( testData1, out1 );
+ QCOMPARE(testData1, out1);
- pipe1.writeEnd().writeSecure( testData1 ); // put it back in
+ pipe1.writeEnd().writeSecure(testData1); // put it back in
QTest::qWait(1); // process events
- QCOMPARE( pipe1.readEnd().bytesAvailable(), testData1.size() );
+ QCOMPARE(pipe1.readEnd().bytesAvailable(), testData1.size());
- pipe1.writeEnd().writeSecure( testData2 ); // add some more data
+ pipe1.writeEnd().writeSecure(testData2); // add some more data
QTest::qWait(1); // process events
- QCOMPARE( pipe1.readEnd().bytesAvailable(), testData1.size() + testData2.size() );
+ QCOMPARE(pipe1.readEnd().bytesAvailable(), testData1.size() + testData2.size());
QCA::SecureArray thisRead = pipe1.readEnd().readSecure(1);
- QCOMPARE( thisRead, QCA::SecureArray("D") );
+ QCOMPARE(thisRead, QCA::SecureArray("D"));
thisRead = pipe1.readEnd().readSecure(3);
- QCOMPARE( thisRead, QCA::SecureArray("own") );
+ QCOMPARE(thisRead, QCA::SecureArray("own"));
thisRead = pipe1.readEnd().readSecure();
- QCOMPARE( thisRead, QCA::SecureArray(" the secure pipe!") );
+ QCOMPARE(thisRead, QCA::SecureArray(" the secure pipe!"));
}
void PipeUnitTest::signalTests()
{
- QCA::QPipe* pipe = new QCA::QPipe;
+ QCA::QPipe *pipe = new QCA::QPipe;
pipe->create();
-
- QVERIFY( pipe->writeEnd().isValid() );
+
+ QVERIFY(pipe->writeEnd().isValid());
pipe->writeEnd().enable();
- QVERIFY( pipe->readEnd().isValid() );
+ QVERIFY(pipe->readEnd().isValid());
pipe->readEnd().enable();
- QSignalSpy readyReadSpy( &(pipe->readEnd()), SIGNAL( readyRead() ) );
- QVERIFY( readyReadSpy.isValid() );
- QSignalSpy bytesWrittenSpy( &(pipe->writeEnd()), SIGNAL( bytesWritten(int) ) );
- QVERIFY( bytesWrittenSpy.isValid() );
- QSignalSpy closedWriteSpy( &(pipe->writeEnd()), SIGNAL( closed() ) );
- QVERIFY( closedWriteSpy.isValid() );
- QSignalSpy closedReadSpy( &(pipe->readEnd()), SIGNAL( closed() ) );
- QVERIFY( closedReadSpy.isValid() );
+ QSignalSpy readyReadSpy(&(pipe->readEnd()), SIGNAL(readyRead()));
+ QVERIFY(readyReadSpy.isValid());
+ QSignalSpy bytesWrittenSpy(&(pipe->writeEnd()), SIGNAL(bytesWritten(int)));
+ QVERIFY(bytesWrittenSpy.isValid());
+ QSignalSpy closedWriteSpy(&(pipe->writeEnd()), SIGNAL(closed()));
+ QVERIFY(closedWriteSpy.isValid());
+ QSignalSpy closedReadSpy(&(pipe->readEnd()), SIGNAL(closed()));
+ QVERIFY(closedReadSpy.isValid());
- QCOMPARE( readyReadSpy.count(), 0 );
- QCOMPARE( bytesWrittenSpy.count(), 0 );
- QCOMPARE( closedWriteSpy.count(), 0 );
- QCOMPARE( closedReadSpy.count(), 0 );
+ QCOMPARE(readyReadSpy.count(), 0);
+ QCOMPARE(bytesWrittenSpy.count(), 0);
+ QCOMPARE(closedWriteSpy.count(), 0);
+ QCOMPARE(closedReadSpy.count(), 0);
QByteArray data("Far better, it is, to dare mighty things");
- pipe->writeEnd().write( data );
+ pipe->writeEnd().write(data);
QTest::qWait(1);
QTest::qWait(1);
- QCOMPARE( readyReadSpy.count(), 1 );
- QCOMPARE( bytesWrittenSpy.count(), 1 );
+ QCOMPARE(readyReadSpy.count(), 1);
+ QCOMPARE(bytesWrittenSpy.count(), 1);
// this pulls out the first argument to the first signal as an integer
- QCOMPARE( bytesWrittenSpy.takeFirst().at(0).toInt(), data.size() );
- QCOMPARE( pipe->readEnd().bytesAvailable(), data.size() );
+ QCOMPARE(bytesWrittenSpy.takeFirst().at(0).toInt(), data.size());
+ QCOMPARE(pipe->readEnd().bytesAvailable(), data.size());
+
+ QCOMPARE(closedWriteSpy.count(), 0);
+ QCOMPARE(closedReadSpy.count(), 0);
- QCOMPARE( closedWriteSpy.count(), 0 );
- QCOMPARE( closedReadSpy.count(), 0 );
-
pipe->readEnd().close();
QTest::qWait(1);
- QCOMPARE( closedWriteSpy.count(), 0 );
- QCOMPARE( closedReadSpy.count(), 1 );
+ QCOMPARE(closedWriteSpy.count(), 0);
+ QCOMPARE(closedReadSpy.count(), 1);
pipe->writeEnd().close();
QTest::qWait(1);
- QCOMPARE( closedWriteSpy.count(), 1 );
- QCOMPARE( closedReadSpy.count(), 1 );
+ QCOMPARE(closedWriteSpy.count(), 1);
+ QCOMPARE(closedReadSpy.count(), 1);
}
void PipeUnitTest::signalTestsSecure()
{
- QCA::QPipe* pipe = new QCA::QPipe;
+ QCA::QPipe *pipe = new QCA::QPipe;
pipe->create(true);
-
- QVERIFY( pipe->writeEnd().isValid() );
+
+ QVERIFY(pipe->writeEnd().isValid());
pipe->writeEnd().enable();
- QVERIFY( pipe->readEnd().isValid() );
+ QVERIFY(pipe->readEnd().isValid());
pipe->readEnd().enable();
- QSignalSpy readyReadSpy( &(pipe->readEnd()), SIGNAL( readyRead() ) );
- QVERIFY( readyReadSpy.isValid() );
- QSignalSpy bytesWrittenSpy( &(pipe->writeEnd()), SIGNAL( bytesWritten(int) ) );
- QVERIFY( bytesWrittenSpy.isValid() );
- QSignalSpy closedWriteSpy( &(pipe->writeEnd()), SIGNAL( closed() ) );
- QVERIFY( closedWriteSpy.isValid() );
- QSignalSpy closedReadSpy( &(pipe->readEnd()), SIGNAL( closed() ) );
- QVERIFY( closedReadSpy.isValid() );
+ QSignalSpy readyReadSpy(&(pipe->readEnd()), SIGNAL(readyRead()));
+ QVERIFY(readyReadSpy.isValid());
+ QSignalSpy bytesWrittenSpy(&(pipe->writeEnd()), SIGNAL(bytesWritten(int)));
+ QVERIFY(bytesWrittenSpy.isValid());
+ QSignalSpy closedWriteSpy(&(pipe->writeEnd()), SIGNAL(closed()));
+ QVERIFY(closedWriteSpy.isValid());
+ QSignalSpy closedReadSpy(&(pipe->readEnd()), SIGNAL(closed()));
+ QVERIFY(closedReadSpy.isValid());
- QCOMPARE( readyReadSpy.count(), 0 );
- QCOMPARE( bytesWrittenSpy.count(), 0 );
- QCOMPARE( closedWriteSpy.count(), 0 );
- QCOMPARE( closedReadSpy.count(), 0 );
+ QCOMPARE(readyReadSpy.count(), 0);
+ QCOMPARE(bytesWrittenSpy.count(), 0);
+ QCOMPARE(closedWriteSpy.count(), 0);
+ QCOMPARE(closedReadSpy.count(), 0);
QCA::SecureArray data("Far better, it is, to dare mighty things");
- pipe->writeEnd().writeSecure( data );
+ pipe->writeEnd().writeSecure(data);
QTest::qWait(1);
QTest::qWait(1);
- QCOMPARE( readyReadSpy.count(), 1 );
- QCOMPARE( bytesWrittenSpy.count(), 1 );
+ QCOMPARE(readyReadSpy.count(), 1);
+ QCOMPARE(bytesWrittenSpy.count(), 1);
// this pulls out the first argument to the first signal as an integer
- QCOMPARE( bytesWrittenSpy.takeFirst().at(0).toInt(), data.size() );
- QCOMPARE( pipe->readEnd().bytesAvailable(), data.size() );
+ QCOMPARE(bytesWrittenSpy.takeFirst().at(0).toInt(), data.size());
+ QCOMPARE(pipe->readEnd().bytesAvailable(), data.size());
+
+ QCOMPARE(closedWriteSpy.count(), 0);
+ QCOMPARE(closedReadSpy.count(), 0);
- QCOMPARE( closedWriteSpy.count(), 0 );
- QCOMPARE( closedReadSpy.count(), 0 );
-
pipe->readEnd().close();
QTest::qWait(1);
- QCOMPARE( closedWriteSpy.count(), 0 );
- QCOMPARE( closedReadSpy.count(), 1 );
+ QCOMPARE(closedWriteSpy.count(), 0);
+ QCOMPARE(closedReadSpy.count(), 1);
pipe->writeEnd().close();
QTest::qWait(1);
- QCOMPARE( closedWriteSpy.count(), 1 );
- QCOMPARE( closedReadSpy.count(), 1 );
+ QCOMPARE(closedWriteSpy.count(), 1);
+ QCOMPARE(closedReadSpy.count(), 1);
}
QTEST_MAIN(PipeUnitTest)
#include "pipeunittest.moc"
diff --git a/unittest/pkits/pkits.cpp b/unittest/pkits/pkits.cpp
index 8e9ab958..f1f2512f 100644
--- a/unittest/pkits/pkits.cpp
+++ b/unittest/pkits/pkits.cpp
@@ -1,1134 +1,1132 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class Pkits : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void pkits4_1_1();
void pkits4_1_2();
void pkits4_1_3();
void pkits4_1_4();
void pkits4_1_5();
void pkits4_1_6();
void pkits4_2_1();
void pkits4_2_2();
void pkits4_2_3();
void pkits4_2_4();
void pkits4_2_5();
void pkits4_2_6();
void pkits4_2_7();
void pkits4_2_8();
void pkits4_3_1();
void pkits4_3_2();
void pkits4_3_3();
void pkits4_3_4();
void pkits4_3_5();
void pkits4_3_6();
void pkits4_3_9();
#ifdef ALL_PKITS_TESTS
void pkits4_3_7();
void pkits4_3_8();
void pkits4_3_10();
void pkits4_3_11();
#endif
void pkits4_4_1();
void pkits4_4_2();
void pkits4_4_3();
void cleanupTestCase();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void Pkits::initTestCase()
{
m_init = new QCA::Initializer;
}
void Pkits::cleanupTestCase()
{
delete m_init;
}
static QCA::Certificate certFromDERFile(const QString &fileName, const QString &provider)
{
QFile certFile(fileName);
certFile.open(QFile::ReadOnly);
QByteArray certArray = certFile.readAll();
QCA::ConvertResult resultCert;
- QCA::Certificate cert = QCA::Certificate::fromDER( certArray, &resultCert, provider);
+ QCA::Certificate cert = QCA::Certificate::fromDER(certArray, &resultCert, provider);
return cert;
}
static QCA::CRL crlFromDERFile(const QString &fileName, const QString &provider)
{
QFile crlFile(fileName);
crlFile.open(QFile::ReadOnly);
QByteArray crlArray = crlFile.readAll();
QCA::ConvertResult crlResult;
- QCA::CRL crl = QCA::CRL::fromDER( crlArray, &crlResult, provider);
+ QCA::CRL crl = QCA::CRL::fromDER(crlArray, &crlResult, provider);
return crl;
}
void Pkits::pkits4_1_1()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidCertificatePathTest1EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCOMPARE( cert.policies().count(), 1 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidCertificatePathTest1EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCOMPARE(cert.policies().count(), 1);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
void Pkits::pkits4_1_2()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidCASignatureTest2EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCOMPARE( cert.policies().count(), 1 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/BadSignedCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/BadSignedCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorSignatureFailed );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidCASignatureTest2EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCOMPARE(cert.policies().count(), 1);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/BadSignedCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/BadSignedCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorSignatureFailed);
+ }
}
}
void Pkits::pkits4_1_3()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidEESignatureTest3EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCOMPARE( cert.policies().count(), 1 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorSignatureFailed );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidEESignatureTest3EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCOMPARE(cert.policies().count(), 1);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorSignatureFailed);
+ }
}
}
void Pkits::pkits4_1_4()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidDSASignaturesTest4EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCOMPARE( cert.policies().count(), 1 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/DSACACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/DSACACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidDSASignaturesTest4EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCOMPARE(cert.policies().count(), 1);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/DSACACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/DSACACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
void Pkits::pkits4_1_5()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidDSAParameterInheritanceTest5EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- // QCOMPARE( cert.policies().count(), 1 );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/DSACACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/DSACACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCA::Certificate params = certFromDERFile("certs/DSAParametersInheritedCACert.crt", provider);
- QCOMPARE( params.isNull(), false );
- untrusted.addCertificate( params );
- QCA::CRL paramsCRL = crlFromDERFile("certs/DSAParametersInheritedCACRL.crl", provider);
- QCOMPARE( paramsCRL.isNull(), false );
- untrusted.addCRL( paramsCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidDSAParameterInheritanceTest5EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ // QCOMPARE( cert.policies().count(), 1 );
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/DSACACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/DSACACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCA::Certificate params = certFromDERFile("certs/DSAParametersInheritedCACert.crt", provider);
+ QCOMPARE(params.isNull(), false);
+ untrusted.addCertificate(params);
+ QCA::CRL paramsCRL = crlFromDERFile("certs/DSAParametersInheritedCACRL.crl", provider);
+ QCOMPARE(paramsCRL.isNull(), false);
+ untrusted.addCRL(paramsCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
void Pkits::pkits4_1_6()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidDSASignatureTest6EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/DSACACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/DSACACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorSignatureFailed );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidDSASignatureTest6EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/DSACACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/DSACACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorSignatureFailed);
+ }
}
}
void Pkits::pkits4_2_1()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidCAnotBeforeDateTest1EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/BadnotBeforeDateCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/BadnotBeforeDateCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorExpired );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidCAnotBeforeDateTest1EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/BadnotBeforeDateCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/BadnotBeforeDateCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorExpired);
+ }
}
}
void Pkits::pkits4_2_2()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidEEnotBeforeDateTest2EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorExpired );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidEEnotBeforeDateTest2EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorExpired);
+ }
}
}
void Pkits::pkits4_2_3()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/Validpre2000UTCnotBeforeDateTest3EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/Validpre2000UTCnotBeforeDateTest3EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
void Pkits::pkits4_2_4()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidGeneralizedTimenotBeforeDateTest4EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidGeneralizedTimenotBeforeDateTest4EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
-
void Pkits::pkits4_2_5()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidCAnotAfterDateTest5EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/BadnotAfterDateCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/BadnotAfterDateCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorExpired );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidCAnotAfterDateTest5EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/BadnotAfterDateCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/BadnotAfterDateCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorExpired);
+ }
}
}
void Pkits::pkits4_2_6()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidEEnotAfterDateTest6EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorExpired );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidEEnotAfterDateTest6EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorExpired);
+ }
}
}
void Pkits::pkits4_2_7()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/Invalidpre2000UTCEEnotAfterDateTest7EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorExpired );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/Invalidpre2000UTCEEnotAfterDateTest7EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorExpired);
+ }
}
}
void Pkits::pkits4_2_8()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidGeneralizedTimenotAfterDateTest8EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidGeneralizedTimenotAfterDateTest8EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
void Pkits::pkits4_3_1()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidNameChainingTest1EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidNameChainingTest1EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+ }
}
}
void Pkits::pkits4_3_2()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidNameChainingOrderTest2EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidNameChainingOrderTest2EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+ }
}
}
void Pkits::pkits4_3_3()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidNameChainingWhitespaceTest3EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidNameChainingWhitespaceTest3EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
-
void Pkits::pkits4_3_4()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidNameChainingWhitespaceTest4EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidNameChainingWhitespaceTest4EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
void Pkits::pkits4_3_5()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidNameChainingCapitalizationTest5EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidNameChainingCapitalizationTest5EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
void Pkits::pkits4_3_6()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidNameUIDsTest6EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/UIDCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/UIDCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidNameUIDsTest6EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/UIDCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/UIDCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
#ifdef ALL_PKITS_TESTS
void Pkits::pkits4_3_7()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidRFC3280MandatoryAttributeTypesTest7EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/RFC3280MandatoryAttributeTypesCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/RFC3280MandatoryAttributeTypesCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidRFC3280MandatoryAttributeTypesTest7EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/RFC3280MandatoryAttributeTypesCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/RFC3280MandatoryAttributeTypesCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
#endif
#ifdef ALL_PKITS_TESTS
void Pkits::pkits4_3_8()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidRFC3280OptionalAttributeTypesTest8EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/RFC3280OptionalAttributeTypesCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/RFC3280OptionalAttributeTypesCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidRFC3280OptionalAttributeTypesTest8EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/RFC3280OptionalAttributeTypesCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/RFC3280OptionalAttributeTypesCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
#endif
void Pkits::pkits4_3_9()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidUTF8StringEncodedNamesTest9EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/UTF8StringEncodedNamesCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/UTF8StringEncodedNamesCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidUTF8StringEncodedNamesTest9EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/UTF8StringEncodedNamesCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/UTF8StringEncodedNamesCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
#ifdef ALL_PKITS_TESTS
void Pkits::pkits4_3_10()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidRolloverfromPrintableStringtoUTF8StringTest10EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/RolloverfromPrintableStringtoUTF8StringCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/RolloverfromPrintableStringtoUTF8StringCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidRolloverfromPrintableStringtoUTF8StringTest10EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/RolloverfromPrintableStringtoUTF8StringCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/RolloverfromPrintableStringtoUTF8StringCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
#endif
#ifdef ALL_PKITS_TESTS
void Pkits::pkits4_3_11()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/ValidUTF8StringCaseInsensitiveMatchTest11EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/UTF8StringCaseInsensitiveMatchCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/UTF8StringCaseInsensitiveMatchCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- qDebug() << "validity: " << cert.validate( trusted, untrusted );
-
- QEXPECT_FAIL("", "This should validate, but it doesn't (QCA::ErrorInvalidCA)", Continue);
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ValidityGood );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/ValidUTF8StringCaseInsensitiveMatchTest11EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/UTF8StringCaseInsensitiveMatchCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/UTF8StringCaseInsensitiveMatchCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ qDebug() << "validity: " << cert.validate(trusted, untrusted);
+
+ QEXPECT_FAIL("", "This should validate, but it doesn't (QCA::ErrorInvalidCA)", Continue);
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ValidityGood);
+ }
}
}
#endif
void Pkits::pkits4_4_1()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidMissingCRLTest1EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/NoCRLCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
-
- qDebug() << "validity: " << cert.validate( trusted, untrusted );
-
- QEXPECT_FAIL("", "This should not validate, but it does", Continue);
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidMissingCRLTest1EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/NoCRLCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+
+ qDebug() << "validity: " << cert.validate(trusted, untrusted);
+
+ QEXPECT_FAIL("", "This should not validate, but it does", Continue);
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+ }
}
}
void Pkits::pkits4_4_2()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidRevokedCATest2EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- QCA::Certificate subca = certFromDERFile("certs/RevokedsubCACert.crt", provider);
- QCOMPARE( subca.isNull(), false );
- untrusted.addCertificate( subca );
- QCA::CRL subcaCRL = crlFromDERFile("certs/RevokedsubCACRL.crl", provider);
- QCOMPARE( subcaCRL.isNull(), false );
- untrusted.addCRL( subcaCRL );
-
- qDebug() << "validity: " << cert.validate( trusted, untrusted );
-
- QEXPECT_FAIL("", "This should not validate, but it does", Continue);
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidRevokedCATest2EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ QCA::Certificate subca = certFromDERFile("certs/RevokedsubCACert.crt", provider);
+ QCOMPARE(subca.isNull(), false);
+ untrusted.addCertificate(subca);
+ QCA::CRL subcaCRL = crlFromDERFile("certs/RevokedsubCACRL.crl", provider);
+ QCOMPARE(subcaCRL.isNull(), false);
+ untrusted.addCRL(subcaCRL);
+
+ qDebug() << "validity: " << cert.validate(trusted, untrusted);
+
+ QEXPECT_FAIL("", "This should not validate, but it does", Continue);
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+ }
}
}
void Pkits::pkits4_4_3()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
- foreach(const QString provider, providersToTest) {
- if( !QCA::isSupported( "cert", provider ) )
- QWARN( QString( "Certificate handling not supported for "+provider).toLocal8Bit() );
- else {
- QCA::Certificate cert = certFromDERFile("certs/InvalidRevokedEETest3EE.crt", provider);
- QCOMPARE( cert.isNull(), false );
-
- QCA::CertificateCollection trusted;
- QCA::CertificateCollection untrusted;
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorInvalidCA );
-
- QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
- QCOMPARE( root.isNull(), false );
- trusted.addCertificate( root );
- QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
- QCOMPARE( rootCRL.isNull(), false );
- trusted.addCRL( rootCRL );
-
- QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
- QCOMPARE( ca.isNull(), false );
- untrusted.addCertificate( ca );
- QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
- QCOMPARE( caCRL.isNull(), false );
- untrusted.addCRL( caCRL );
-
- qDebug() << "validity: " << cert.validate( trusted, untrusted );
-
- QEXPECT_FAIL("", "This should not validate, but it does", Continue);
- QCOMPARE( cert.validate( trusted, untrusted ), QCA::ErrorUntrusted );
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("cert", provider)) {
+ QWARN(QString("Certificate handling not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::Certificate cert = certFromDERFile("certs/InvalidRevokedEETest3EE.crt", provider);
+ QCOMPARE(cert.isNull(), false);
+
+ QCA::CertificateCollection trusted;
+ QCA::CertificateCollection untrusted;
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorInvalidCA);
+
+ QCA::Certificate root = certFromDERFile("certs/TrustAnchorRootCertificate.crt", provider);
+ QCOMPARE(root.isNull(), false);
+ trusted.addCertificate(root);
+ QCA::CRL rootCRL = crlFromDERFile("certs/TrustAnchorRootCRL.crl", provider);
+ QCOMPARE(rootCRL.isNull(), false);
+ trusted.addCRL(rootCRL);
+
+ QCA::Certificate ca = certFromDERFile("certs/GoodCACert.crt", provider);
+ QCOMPARE(ca.isNull(), false);
+ untrusted.addCertificate(ca);
+ QCA::CRL caCRL = crlFromDERFile("certs/GoodCACRL.crl", provider);
+ QCOMPARE(caCRL.isNull(), false);
+ untrusted.addCRL(caCRL);
+
+ qDebug() << "validity: " << cert.validate(trusted, untrusted);
+
+ QEXPECT_FAIL("", "This should not validate, but it does", Continue);
+ QCOMPARE(cert.validate(trusted, untrusted), QCA::ErrorUntrusted);
+ }
}
}
QTEST_MAIN(Pkits)
#include "pkits.moc"
diff --git a/unittest/rsaunittest/rsaunittest.cpp b/unittest/rsaunittest/rsaunittest.cpp
index 3c86b068..6999c1fd 100644
--- a/unittest/rsaunittest/rsaunittest.cpp
+++ b/unittest/rsaunittest/rsaunittest.cpp
@@ -1,199 +1,199 @@
/**
* Copyright (C) 2005-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class RSAUnitTest : public QObject
{
Q_OBJECT
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testrsa();
void testAsymmetricEncryption();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void RSAUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void RSAUnitTest::cleanupTestCase()
{
delete m_init;
}
void RSAUnitTest::testrsa()
{
QStringList providersToTest;
providersToTest.append("qca-ossl");
// providersToTest.append("qca-gcrypt");
- foreach(const QString provider, providersToTest) {
- if(!QCA::isSupported("pkey", provider) ||
- !QCA::PKey::supportedTypes(provider).contains(QCA::PKey::RSA) ||
- !QCA::PKey::supportedIOTypes(provider).contains(QCA::PKey::RSA))
- QWARN(QString("RSA not supported for "+provider).toLocal8Bit());
- else {
- QCA::KeyGenerator keygen;
- QCOMPARE( keygen.isBusy(), false );
- QCOMPARE( keygen.blockingEnabled(), true );
-
- QList<int> keySizes;
- keySizes << 512 << 1024 << 768 << 2048;
- foreach( int keysize, keySizes ) {
- QCA::PrivateKey rsaKey = keygen.createRSA(keysize, 65537, provider);
- QCOMPARE( rsaKey.isNull(), false );
- QCOMPARE( rsaKey.isRSA(), true );
- QCOMPARE( rsaKey.isDSA(), false );
- QCOMPARE( rsaKey.isDH(), false );
- QCOMPARE( rsaKey.isPrivate(), true );
- QCOMPARE( rsaKey.isPublic(), false );
- QCOMPARE( rsaKey.canSign(), true);
- QCOMPARE( rsaKey.canDecrypt(), true);
- QCOMPARE( rsaKey.canEncrypt(), true);
-
- QCA::RSAPrivateKey rsaPrivKey = rsaKey.toRSA();
- QCOMPARE( rsaPrivKey.bitSize(), keysize );
-
- QString rsaPEM = rsaKey.toPEM();
- QCOMPARE( rsaPEM.isEmpty(), false );
-
- QCA::ConvertResult checkResult;
- QCA::PrivateKey fromPEMkey = QCA::PrivateKey::fromPEM(rsaPEM, QCA::SecureArray(), &checkResult);
- QCOMPARE( checkResult, QCA::ConvertGood );
- QCOMPARE( fromPEMkey.isNull(), false );
- QCOMPARE( fromPEMkey.isRSA(), true );
- QCOMPARE( fromPEMkey.isDSA(), false );
- QCOMPARE( fromPEMkey.isDH(), false );
- QCOMPARE( fromPEMkey.isPrivate(), true );
- QCOMPARE( fromPEMkey.isPublic(), false );
- QCOMPARE( rsaKey == fromPEMkey, true );
-
- QCA::SecureArray rsaDER = rsaKey.toDER(QCA::SecureArray("foo"));
- QCOMPARE( rsaDER.isEmpty(), false );
-
- QCA::PrivateKey fromDERkey = QCA::PrivateKey::fromDER(rsaDER, QCA::SecureArray("foo"), &checkResult);
- QCOMPARE( checkResult, QCA::ConvertGood );
- QCOMPARE( fromDERkey.isNull(), false );
- QCOMPARE( fromDERkey.isRSA(), true );
- QCOMPARE( fromDERkey.isDSA(), false );
- QCOMPARE( fromDERkey.isDH(), false );
- QCOMPARE( fromDERkey.isPrivate(), true );
- QCOMPARE( fromDERkey.isPublic(), false );
- QCOMPARE( rsaKey == fromDERkey, true );
-
- // same test, without passphrase
- rsaDER = rsaKey.toDER();
- QCOMPARE( rsaDER.isEmpty(), false );
-
- fromDERkey = QCA::PrivateKey::fromDER(rsaDER, QCA::SecureArray(), &checkResult);
- QCOMPARE( checkResult, QCA::ConvertGood );
- QCOMPARE( fromDERkey.isNull(), false );
- QCOMPARE( fromDERkey.isRSA(), true );
- QCOMPARE( fromDERkey.isDSA(), false );
- QCOMPARE( fromDERkey.isDH(), false );
- QCOMPARE( fromDERkey.isPrivate(), true );
- QCOMPARE( fromDERkey.isPublic(), false );
- QCOMPARE( rsaKey == fromDERkey, true );
-
- QCA::PublicKey pubKey = rsaKey.toPublicKey();
- QCOMPARE( pubKey.isNull(), false );
- QCOMPARE( pubKey.isRSA(), true );
- QCOMPARE( pubKey.isDSA(), false );
- QCOMPARE( pubKey.isDH(), false );
- QCOMPARE( pubKey.isPrivate(), false );
- QCOMPARE( pubKey.isPublic(), true );
-
- QCA::RSAPublicKey RSApubKey = pubKey.toRSA();
- QCOMPARE( RSApubKey.e(), QCA::BigInteger(65537) );
- QCOMPARE( RSApubKey.isNull(), false );
- QCOMPARE( RSApubKey.isRSA(), true );
- QCOMPARE( RSApubKey.isDSA(), false );
- QCOMPARE( RSApubKey.isDH(), false );
- QCOMPARE( RSApubKey.isPrivate(), false );
- QCOMPARE( RSApubKey.isPublic(), true );
- }
- }
+ foreach (const QString provider, providersToTest) {
+ if (!QCA::isSupported("pkey", provider) ||
+ !QCA::PKey::supportedTypes(provider).contains(QCA::PKey::RSA) ||
+ !QCA::PKey::supportedIOTypes(provider).contains(QCA::PKey::RSA)) {
+ QWARN(QString("RSA not supported for " + provider).toLocal8Bit());
+ } else {
+ QCA::KeyGenerator keygen;
+ QCOMPARE(keygen.isBusy(), false);
+ QCOMPARE(keygen.blockingEnabled(), true);
+
+ QList<int> keySizes;
+ keySizes << 512 << 1024 << 768 << 2048;
+ foreach (int keysize, keySizes) {
+ QCA::PrivateKey rsaKey = keygen.createRSA(keysize, 65537, provider);
+ QCOMPARE(rsaKey.isNull(), false);
+ QCOMPARE(rsaKey.isRSA(), true);
+ QCOMPARE(rsaKey.isDSA(), false);
+ QCOMPARE(rsaKey.isDH(), false);
+ QCOMPARE(rsaKey.isPrivate(), true);
+ QCOMPARE(rsaKey.isPublic(), false);
+ QCOMPARE(rsaKey.canSign(), true);
+ QCOMPARE(rsaKey.canDecrypt(), true);
+ QCOMPARE(rsaKey.canEncrypt(), true);
+
+ QCA::RSAPrivateKey rsaPrivKey = rsaKey.toRSA();
+ QCOMPARE(rsaPrivKey.bitSize(), keysize);
+
+ QString rsaPEM = rsaKey.toPEM();
+ QCOMPARE(rsaPEM.isEmpty(), false);
+
+ QCA::ConvertResult checkResult;
+ QCA::PrivateKey fromPEMkey = QCA::PrivateKey::fromPEM(rsaPEM, QCA::SecureArray(), &checkResult);
+ QCOMPARE(checkResult, QCA::ConvertGood);
+ QCOMPARE(fromPEMkey.isNull(), false);
+ QCOMPARE(fromPEMkey.isRSA(), true);
+ QCOMPARE(fromPEMkey.isDSA(), false);
+ QCOMPARE(fromPEMkey.isDH(), false);
+ QCOMPARE(fromPEMkey.isPrivate(), true);
+ QCOMPARE(fromPEMkey.isPublic(), false);
+ QCOMPARE(rsaKey == fromPEMkey, true);
+
+ QCA::SecureArray rsaDER = rsaKey.toDER(QCA::SecureArray("foo"));
+ QCOMPARE(rsaDER.isEmpty(), false);
+
+ QCA::PrivateKey fromDERkey = QCA::PrivateKey::fromDER(rsaDER, QCA::SecureArray("foo"), &checkResult);
+ QCOMPARE(checkResult, QCA::ConvertGood);
+ QCOMPARE(fromDERkey.isNull(), false);
+ QCOMPARE(fromDERkey.isRSA(), true);
+ QCOMPARE(fromDERkey.isDSA(), false);
+ QCOMPARE(fromDERkey.isDH(), false);
+ QCOMPARE(fromDERkey.isPrivate(), true);
+ QCOMPARE(fromDERkey.isPublic(), false);
+ QCOMPARE(rsaKey == fromDERkey, true);
+
+ // same test, without passphrase
+ rsaDER = rsaKey.toDER();
+ QCOMPARE(rsaDER.isEmpty(), false);
+
+ fromDERkey = QCA::PrivateKey::fromDER(rsaDER, QCA::SecureArray(), &checkResult);
+ QCOMPARE(checkResult, QCA::ConvertGood);
+ QCOMPARE(fromDERkey.isNull(), false);
+ QCOMPARE(fromDERkey.isRSA(), true);
+ QCOMPARE(fromDERkey.isDSA(), false);
+ QCOMPARE(fromDERkey.isDH(), false);
+ QCOMPARE(fromDERkey.isPrivate(), true);
+ QCOMPARE(fromDERkey.isPublic(), false);
+ QCOMPARE(rsaKey == fromDERkey, true);
+
+ QCA::PublicKey pubKey = rsaKey.toPublicKey();
+ QCOMPARE(pubKey.isNull(), false);
+ QCOMPARE(pubKey.isRSA(), true);
+ QCOMPARE(pubKey.isDSA(), false);
+ QCOMPARE(pubKey.isDH(), false);
+ QCOMPARE(pubKey.isPrivate(), false);
+ QCOMPARE(pubKey.isPublic(), true);
+
+ QCA::RSAPublicKey RSApubKey = pubKey.toRSA();
+ QCOMPARE(RSApubKey.e(), QCA::BigInteger(65537));
+ QCOMPARE(RSApubKey.isNull(), false);
+ QCOMPARE(RSApubKey.isRSA(), true);
+ QCOMPARE(RSApubKey.isDSA(), false);
+ QCOMPARE(RSApubKey.isDH(), false);
+ QCOMPARE(RSApubKey.isPrivate(), false);
+ QCOMPARE(RSApubKey.isPublic(), true);
+ }
+ }
}
}
void RSAUnitTest::testAsymmetricEncryption()
{
- if(!QCA::isSupported("pkey", "qca-ossl") ||
- !QCA::PKey::supportedTypes("qca-ossl").contains(QCA::PKey::RSA) ||
- !QCA::PKey::supportedIOTypes("qca-ossl").contains(QCA::PKey::RSA)) {
- QWARN(QString("RSA not supported").toLocal8Bit());
+ if (!QCA::isSupported("pkey", "qca-ossl") ||
+ !QCA::PKey::supportedTypes("qca-ossl").contains(QCA::PKey::RSA) ||
+ !QCA::PKey::supportedIOTypes("qca-ossl").contains(QCA::PKey::RSA)) {
+ QWARN(QString("RSA not supported").toLocal8Bit());
#if QT_VERSION >= 0x050000
- QSKIP("RSA not supported. skipping");
+ QSKIP("RSA not supported. skipping");
#else
- QSKIP("RSA not supported. skipping",SkipAll);
+ QSKIP("RSA not supported. skipping", SkipAll);
#endif
- }
- QCA::RSAPrivateKey rsaPrivKey1 = QCA::KeyGenerator().createRSA(512, 65537, "qca-ossl").toRSA();
- QCA::RSAPublicKey rsaPubKey1 = rsaPrivKey1.toPublicKey().toRSA();
-
- QCA::RSAPrivateKey rsaPrivKey2 = QCA::KeyGenerator().createRSA(512, 65537, "qca-ossl").toRSA();
- // QCA::RSAPublicKey rsaPubKey2 = rsaPrivKey2.toPublicKey().toRSA();
-
- const QCA::SecureArray clearText = "Hello World !";
- QCA::SecureArray testText;
- QCA::SecureArray cipherText;
-
- // Test keys #1: Enc with public, dec with private
- QVERIFY( rsaPubKey1.maximumEncryptSize(QCA::EME_PKCS1v15) >= clearText.size() );
- cipherText = rsaPubKey1.encrypt(clearText, QCA::EME_PKCS1v15);
- QVERIFY( rsaPrivKey1.decrypt(cipherText, &testText, QCA::EME_PKCS1v15) );
- QCOMPARE( clearText, testText );
- testText.clear();
- // ---
-
- // Test keys #2 to decipher key #1
- QVERIFY( !rsaPrivKey2.decrypt(cipherText, &testText, QCA::EME_PKCS1v15) );
- QVERIFY( testText.isEmpty() );
- // ---
-
- // Test keys #2: Enc with private, dec with public
- cipherText.clear();
- QVERIFY( rsaPrivKey1.maximumEncryptSize(QCA::EME_PKCS1v15) >= clearText.size() );
- cipherText = rsaPrivKey1.encrypt(clearText, QCA::EME_PKCS1v15);
- QVERIFY( rsaPubKey1.decrypt(cipherText, &testText, QCA::EME_PKCS1v15) );
- QCOMPARE( clearText, testText );
- testText.clear();
- // ---
+ }
+ QCA::RSAPrivateKey rsaPrivKey1 = QCA::KeyGenerator().createRSA(512, 65537, "qca-ossl").toRSA();
+ QCA::RSAPublicKey rsaPubKey1 = rsaPrivKey1.toPublicKey().toRSA();
+
+ QCA::RSAPrivateKey rsaPrivKey2 = QCA::KeyGenerator().createRSA(512, 65537, "qca-ossl").toRSA();
+ // QCA::RSAPublicKey rsaPubKey2 = rsaPrivKey2.toPublicKey().toRSA();
+
+ const QCA::SecureArray clearText = "Hello World !";
+ QCA::SecureArray testText;
+ QCA::SecureArray cipherText;
+
+ // Test keys #1: Enc with public, dec with private
+ QVERIFY(rsaPubKey1.maximumEncryptSize(QCA::EME_PKCS1v15) >= clearText.size());
+ cipherText = rsaPubKey1.encrypt(clearText, QCA::EME_PKCS1v15);
+ QVERIFY(rsaPrivKey1.decrypt(cipherText, &testText, QCA::EME_PKCS1v15));
+ QCOMPARE(clearText, testText);
+ testText.clear();
+ // ---
+
+ // Test keys #2 to decipher key #1
+ QVERIFY(!rsaPrivKey2.decrypt(cipherText, &testText, QCA::EME_PKCS1v15));
+ QVERIFY(testText.isEmpty());
+ // ---
+
+ // Test keys #2: Enc with private, dec with public
+ cipherText.clear();
+ QVERIFY(rsaPrivKey1.maximumEncryptSize(QCA::EME_PKCS1v15) >= clearText.size());
+ cipherText = rsaPrivKey1.encrypt(clearText, QCA::EME_PKCS1v15);
+ QVERIFY(rsaPubKey1.decrypt(cipherText, &testText, QCA::EME_PKCS1v15));
+ QCOMPARE(clearText, testText);
+ testText.clear();
+ // ---
}
QTEST_MAIN(RSAUnitTest)
#include "rsaunittest.moc"
diff --git a/unittest/securearrayunittest/securearrayunittest.cpp b/unittest/securearrayunittest/securearrayunittest.cpp
index 391e1c9a..0dc352e8 100644
--- a/unittest/securearrayunittest/securearrayunittest.cpp
+++ b/unittest/securearrayunittest/securearrayunittest.cpp
@@ -1,151 +1,147 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class SecureArrayUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testAll();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
-
void SecureArrayUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void SecureArrayUnitTest::cleanupTestCase()
{
delete m_init;
}
-
void SecureArrayUnitTest::testAll()
{
QCA::SecureArray emptyArray;
- QCOMPARE( emptyArray.size(), 0 );
- QVERIFY( emptyArray.isEmpty() );
+ QCOMPARE(emptyArray.size(), 0);
+ QVERIFY(emptyArray.isEmpty());
QCA::SecureArray testArray(10);
- QCOMPARE( testArray.size(), 10 );
- QCOMPARE( testArray.isEmpty(), false );
+ QCOMPARE(testArray.size(), 10);
+ QCOMPARE(testArray.isEmpty(), false);
QCA::SecureArray testArray64(64);
- QCOMPARE( testArray64.size(), 64 );
- QCOMPARE( testArray64.isEmpty(), false );
+ QCOMPARE(testArray64.size(), 64);
+ QCOMPARE(testArray64.isEmpty(), false);
//testArray.fill( 'a' );
for (int i = 0; i < testArray.size(); i++) {
- testArray[ i ] = 0x61;
+ testArray[ i ] = 0x61;
}
- QCOMPARE( QCA::arrayToHex( testArray.toByteArray() ), QString( "61616161616161616161" ) );
+ QCOMPARE(QCA::arrayToHex(testArray.toByteArray()), QString("61616161616161616161"));
- testArray.fill( 'b' );
+ testArray.fill('b');
testArray[7] = 0x00;
- QCOMPARE( QCA::arrayToHex( testArray.toByteArray() ), QString( "62626262626262006262" ) );
+ QCOMPARE(QCA::arrayToHex(testArray.toByteArray()), QString("62626262626262006262"));
QByteArray byteArray(10, 'c');
- QCA::SecureArray secureArray( byteArray );
- QCOMPARE( secureArray.size(), 10 );
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
- byteArray.fill( 'd' );
+ QCA::SecureArray secureArray(byteArray);
+ QCOMPARE(secureArray.size(), 10);
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
+ byteArray.fill('d');
// it should be a copy, so no effect
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
- QCA::SecureArray copyArray( secureArray );
- QCOMPARE( QCA::arrayToHex ( copyArray.toByteArray() ), QString( "63636363636363636363" ) );
+ QCA::SecureArray copyArray(secureArray);
+ QCOMPARE(QCA::arrayToHex(copyArray.toByteArray()), QString("63636363636363636363"));
copyArray.fill(0x64);
- QCOMPARE( QCA::arrayToHex ( copyArray.toByteArray() ), QString( "64646464646464646464" ) );
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
+ QCOMPARE(QCA::arrayToHex(copyArray.toByteArray()), QString("64646464646464646464"));
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
// test for detaching
QCA::SecureArray detachArray1 = secureArray; // currently the same
- QCOMPARE( QCA::arrayToHex ( detachArray1.toByteArray() ), QString( "63636363636363636363" ) );
+ QCOMPARE(QCA::arrayToHex(detachArray1.toByteArray()), QString("63636363636363636363"));
for (int i = 0; i < detachArray1.size(); i++) {
- detachArray1[i] = 0x66; // implicit detach
+ detachArray1[i] = 0x66; // implicit detach
}
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
- QCOMPARE( QCA::arrayToHex ( detachArray1.toByteArray() ), QString( "66666666666666666666" ) );
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
+ QCOMPARE(QCA::arrayToHex(detachArray1.toByteArray()), QString("66666666666666666666"));
QCA::SecureArray detachArray2 = secureArray; // currently the same
- QCOMPARE( QCA::arrayToHex ( detachArray2.toByteArray() ), QString( "63636363636363636363" ) );
+ QCOMPARE(QCA::arrayToHex(detachArray2.toByteArray()), QString("63636363636363636363"));
//implicit detach
for (int i = 0; i < detachArray2.size(); i++) {
- detachArray2.data()[i] = 0x67;
+ detachArray2.data()[i] = 0x67;
}
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
- QCOMPARE( QCA::arrayToHex ( detachArray2.toByteArray() ), QString( "67676767676767676767" ) );
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
+ QCOMPARE(QCA::arrayToHex(detachArray2.toByteArray()), QString("67676767676767676767"));
QCA::SecureArray detachArray3 = secureArray; // implicitly shared copy
- QCOMPARE( QCA::arrayToHex ( detachArray3.toByteArray() ), QString( "63636363636363636363" ) );
+ QCOMPARE(QCA::arrayToHex(detachArray3.toByteArray()), QString("63636363636363636363"));
for (int i = 0; i < detachArray3.size(); i++) {
- detachArray3.data()[i] = 0x68;
+ detachArray3.data()[i] = 0x68;
}
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
- QCOMPARE( QCA::arrayToHex ( detachArray3.toByteArray() ), QString( "68686868686868686868" ) );
-
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
+ QCOMPARE(QCA::arrayToHex(detachArray3.toByteArray()), QString("68686868686868686868"));
// test for resizing
QCA::SecureArray resizeArray = emptyArray;
- QCOMPARE( resizeArray.size(), 0 );
+ QCOMPARE(resizeArray.size(), 0);
resizeArray.resize(20);
- QCOMPARE( resizeArray.size(), 20 );
+ QCOMPARE(resizeArray.size(), 20);
resizeArray.resize(40);
- QCOMPARE( resizeArray.size(), 40 );
+ QCOMPARE(resizeArray.size(), 40);
resizeArray.resize(10);
- QCOMPARE( resizeArray.size(), 10 );
-
+ QCOMPARE(resizeArray.size(), 10);
// test for append
QCA::SecureArray appendArray = secureArray;
- appendArray.append( QCA::SecureArray() );
- QCOMPARE( QCA::arrayToHex( secureArray.toByteArray() ), QCA::arrayToHex( appendArray.toByteArray() ) );
- appendArray.append( secureArray );
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
- QCOMPARE( QCA::arrayToHex ( appendArray.toByteArray() ), QString( "6363636363636363636363636363636363636363" ) );
+ appendArray.append(QCA::SecureArray());
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QCA::arrayToHex(appendArray.toByteArray()));
+ appendArray.append(secureArray);
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
+ QCOMPARE(QCA::arrayToHex(appendArray.toByteArray()), QString("6363636363636363636363636363636363636363"));
QCA::SecureArray appendArray2 = secureArray;
- QCOMPARE( QCA::arrayToHex ( appendArray2.append(secureArray).toByteArray() ), QString( "6363636363636363636363636363636363636363" ) );
+ QCOMPARE(QCA::arrayToHex(appendArray2.append(secureArray).toByteArray()), QString("6363636363636363636363636363636363636363"));
// test for a possible problem with operator[]
- QVERIFY( (secureArray[0] == (char)0x63) );
+ QVERIFY((secureArray[0] == (char)0x63));
}
QTEST_MAIN(SecureArrayUnitTest)
#include "securearrayunittest.moc"
diff --git a/unittest/staticunittest/staticunittest.cpp b/unittest/staticunittest/staticunittest.cpp
index 2c34876a..54802e92 100644
--- a/unittest/staticunittest/staticunittest.cpp
+++ b/unittest/staticunittest/staticunittest.cpp
@@ -1,117 +1,116 @@
/**
* Copyright (C) 2004-2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class StaticUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void hexConversions();
void capabilities();
void secureMemory();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void StaticUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void StaticUnitTest::cleanupTestCase()
{
delete m_init;
}
void StaticUnitTest::hexConversions()
{
QByteArray test(10, 'a');
- QCOMPARE( QCA::arrayToHex(test), QString("61616161616161616161") );
+ QCOMPARE(QCA::arrayToHex(test), QString("61616161616161616161"));
test.fill('b');
test[7] = 0x00;
- QCOMPARE( test == QCA::hexToArray(QString("62626262626262006262")), true );
+ QCOMPARE(test == QCA::hexToArray(QString("62626262626262006262")), true);
QCA::SecureArray testArray(10);
//testArray.fill( 'a' );
for (int i = 0; i < testArray.size(); i++) {
- testArray[ i ] = 0x61;
+ testArray[ i ] = 0x61;
}
- QCOMPARE( QCA::arrayToHex( testArray.toByteArray() ), QString( "61616161616161616161" ) );
+ QCOMPARE(QCA::arrayToHex(testArray.toByteArray()), QString("61616161616161616161"));
//testArray.fill( 'b' );
for (int i = 0; i < testArray.size(); i++) {
- testArray[ i ] = 0x62;
+ testArray[ i ] = 0x62;
}
testArray[6] = 0x00;
- QCOMPARE( testArray == QCA::hexToArray(QString("62626262626200626262")), true );
+ QCOMPARE(testArray == QCA::hexToArray(QString("62626262626200626262")), true);
- QCOMPARE( testArray == QCA::hexToArray( QCA::arrayToHex( testArray.toByteArray() ) ), true );
+ QCOMPARE(testArray == QCA::hexToArray(QCA::arrayToHex(testArray.toByteArray())), true);
testArray[9] = 0x00;
- QCOMPARE( testArray == QCA::hexToArray( QCA::arrayToHex( testArray.toByteArray() ) ), true );
+ QCOMPARE(testArray == QCA::hexToArray(QCA::arrayToHex(testArray.toByteArray())), true);
}
-
void StaticUnitTest::capabilities()
{
// capabilities are reported as a list - that is a problem for
// doing a direct comparison, since they change
// We try to work around that using contains()
QStringList defaultCapabilities = QCA::defaultFeatures();
- QVERIFY( defaultCapabilities.contains("random") );
- QVERIFY( defaultCapabilities.contains("sha1") );
- QVERIFY( defaultCapabilities.contains("md5") );
+ QVERIFY(defaultCapabilities.contains("random"));
+ QVERIFY(defaultCapabilities.contains("sha1"));
+ QVERIFY(defaultCapabilities.contains("md5"));
QStringList capList;
capList << "random" << "sha1";
- QCOMPARE( QCA::isSupported(capList), true );
+ QCOMPARE(QCA::isSupported(capList), true);
capList.append("noSuch");
- QCOMPARE( QCA::isSupported(capList), false );
+ QCOMPARE(QCA::isSupported(capList), false);
capList.clear();
capList.append("noSuch");
- QCOMPARE( QCA::isSupported(capList), false );
+ QCOMPARE(QCA::isSupported(capList), false);
}
void StaticUnitTest::secureMemory()
{
// this should be reliably true
- QCOMPARE( QCA::haveSecureMemory(), true );
+ QCOMPARE(QCA::haveSecureMemory(), true);
}
QTEST_MAIN(StaticUnitTest)
#include "staticunittest.moc"
diff --git a/unittest/symmetrickeyunittest/symmetrickeyunittest.cpp b/unittest/symmetrickeyunittest/symmetrickeyunittest.cpp
index 4843d316..5d6abb95 100644
--- a/unittest/symmetrickeyunittest/symmetrickeyunittest.cpp
+++ b/unittest/symmetrickeyunittest/symmetrickeyunittest.cpp
@@ -1,120 +1,118 @@
/**
* Copyright (C) 2004, 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class SymmetricKeyUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void test1();
void weakKey_data();
void weakKey();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void SymmetricKeyUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void SymmetricKeyUnitTest::cleanupTestCase()
{
delete m_init;
}
void SymmetricKeyUnitTest::test1()
{
QCA::SymmetricKey emptyKey;
- QCOMPARE( emptyKey.size(), 0 );
+ QCOMPARE(emptyKey.size(), 0);
QCA::SymmetricKey randomKey(10);
- QCOMPARE( randomKey.size(),10 );
+ QCOMPARE(randomKey.size(), 10);
QByteArray byteArray(10, 'c');
- QCA::SecureArray secureArray( byteArray );
+ QCA::SecureArray secureArray(byteArray);
QCA::SymmetricKey keyArray = secureArray;
- QCOMPARE( secureArray.size(), 10 );
- QCOMPARE( keyArray.size(), secureArray.size() );
- QCOMPARE( QCA::arrayToHex ( keyArray.toByteArray() ), QString( "63636363636363636363" ) );
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
+ QCOMPARE(secureArray.size(), 10);
+ QCOMPARE(keyArray.size(), secureArray.size());
+ QCOMPARE(QCA::arrayToHex(keyArray.toByteArray()), QString("63636363636363636363"));
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
keyArray[3] = 0x00; // test keyArray detaches OK
- QCOMPARE( QCA::arrayToHex ( keyArray.toByteArray() ), QString( "63636300636363636363" ) );
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
+ QCOMPARE(QCA::arrayToHex(keyArray.toByteArray()), QString("63636300636363636363"));
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
QCA::SymmetricKey anotherKey;
anotherKey = keyArray;
- QCOMPARE( QCA::arrayToHex ( anotherKey.toByteArray() ), QString( "63636300636363636363" ) );
- QCA::SymmetricKey bigKey( 100 );
+ QCOMPARE(QCA::arrayToHex(anotherKey.toByteArray()), QString("63636300636363636363"));
+ QCA::SymmetricKey bigKey(100);
anotherKey = bigKey;
- QCOMPARE( anotherKey.size(), 100 );
+ QCOMPARE(anotherKey.size(), 100);
anotherKey = secureArray;
- QCOMPARE( QCA::arrayToHex ( secureArray.toByteArray() ), QString( "63636363636363636363" ) );
- QCOMPARE( anotherKey.size(), 10 );
+ QCOMPARE(QCA::arrayToHex(secureArray.toByteArray()), QString("63636363636363636363"));
+ QCOMPARE(anotherKey.size(), 10);
anotherKey = emptyKey;
- QCOMPARE( anotherKey.size(), 0 );
+ QCOMPARE(anotherKey.size(), 0);
}
// These are from the Botan test suite
void SymmetricKeyUnitTest::weakKey_data()
{
QTest::addColumn<QByteArray>("keyText");
QTest::addColumn<bool>("isWeak");
-
QTest::newRow("") << QByteArray("ffffffffffffffff") << true;
QTest::newRow("") << QByteArray("0000000000000000") << true;
QTest::newRow("") << QByteArray("d5d44ff720683d0d") << false;
QTest::newRow("") << QByteArray("d5d44ff720683d0d") << false;
QTest::newRow("") << QByteArray("1046913489980131") << false;
QTest::newRow("") << QByteArray("1007103489988020") << false;
QTest::newRow("") << QByteArray("10071034c8980120") << false;
QTest::newRow("") << QByteArray("1046103489988020") << false;
}
-
void SymmetricKeyUnitTest::weakKey()
{
- QFETCH( QByteArray, keyText );
- QFETCH( bool, isWeak );
+ QFETCH(QByteArray, keyText);
+ QFETCH(bool, isWeak);
- QCA::SymmetricKey key( QCA::hexToArray( QByteArray( keyText ) ) );
- QCOMPARE( key.isWeakDESKey(), isWeak );
+ QCA::SymmetricKey key(QCA::hexToArray(QByteArray(keyText)));
+ QCOMPARE(key.isWeakDESKey(), isWeak);
}
QTEST_MAIN(SymmetricKeyUnitTest)
#include "symmetrickeyunittest.moc"
diff --git a/unittest/tls/tlsunittest.cpp b/unittest/tls/tlsunittest.cpp
index 4be7fff7..8c050171 100644
--- a/unittest/tls/tlsunittest.cpp
+++ b/unittest/tls/tlsunittest.cpp
@@ -1,133 +1,133 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QtCrypto>
#include <QtTest/QtTest>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class TLSUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void testCipherList();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
};
void TLSUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void TLSUnitTest::cleanupTestCase()
{
delete m_init;
}
void TLSUnitTest::testCipherList()
{
- if(!QCA::isSupported("tls", "qca-ossl"))
- QWARN("TLS not supported for qca-ossl");
- else {
- QCA::TLS *tls = new QCA::TLS(QCA::TLS::Stream, 0, "qca-ossl");
- QStringList cipherList = tls->supportedCipherSuites(QCA::TLS::TLS_v1);
- QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA") );
- QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA") );
- QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA") );
-
- // openSUSE TW OpenSSL 1.1 does not have this
- // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") );
-
- // Fedora 26 openssl has no this cipher suites.
- // QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") );
- // QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") );
- // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") );
- // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") );
-
- // Fedora 20 openssl has no this cipher suites.
- // I just believe that F20 has the most strict patent rules
- // and Fedora list is the minimal default list.
- // It should fit for every openssl distribuition.
-
- // QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") );
- // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
- // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") );
-
- // OpenSSL 1.1 in openSUSE TW has it disabled by default
- // cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v3);
- // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") );
-
- // Fedora 22 has no SSL_RSA_WITH_RC4_128_MD5
- // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") );
-
- // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") );
- // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
- // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") );
-
- // Debian testing (jessie) has no these ciphers. So disable them.
-
- // cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v2);
- // QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") );
- // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
- // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") );
- // QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") );
- // QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") );
- // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") );
- // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
+ if (!QCA::isSupported("tls", "qca-ossl")) {
+ QWARN("TLS not supported for qca-ossl");
+ } else {
+ QCA::TLS *tls = new QCA::TLS(QCA::TLS::Stream, 0, "qca-ossl");
+ QStringList cipherList = tls->supportedCipherSuites(QCA::TLS::TLS_v1);
+ QVERIFY(cipherList.contains("TLS_DHE_RSA_WITH_AES_256_CBC_SHA"));
+ QVERIFY(cipherList.contains("TLS_RSA_WITH_AES_256_CBC_SHA"));
+ QVERIFY(cipherList.contains("TLS_DHE_RSA_WITH_AES_128_CBC_SHA"));
+
+ // openSUSE TW OpenSSL 1.1 does not have this
+ // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_256_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_RSA_WITH_3DES_EDE_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_RSA_WITH_AES_128_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_AES_128_CBC_SHA") );
+
+ // Fedora 26 openssl has no this cipher suites.
+ // QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_SHA") );
+ // QVERIFY( cipherList.contains("TLS_RSA_WITH_RC4_128_MD5") );
+ // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_SHA") );
+ // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") );
+
+ // Fedora 20 openssl has no this cipher suites.
+ // I just believe that F20 has the most strict patent rules
+ // and Fedora list is the minimal default list.
+ // It should fit for every openssl distribuition.
+
+ // QVERIFY( cipherList.contains("TLS_DHE_RSA_WITH_DES_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_DHE_DSS_WITH_DES_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_RSA_WITH_DES_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_DES40_CBC_SHA") );
+ // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
+ // QVERIFY( cipherList.contains("TLS_RSA_EXPORT_WITH_RC4_40_MD5") );
+
+ // OpenSSL 1.1 in openSUSE TW has it disabled by default
+ // cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v3);
+ // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_256_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_256_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_256_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_RSA_WITH_3DES_EDE_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_AES_128_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_AES_128_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_RSA_WITH_AES_128_CBC_SHA") );
+
+ // Fedora 22 has no SSL_RSA_WITH_RC4_128_MD5
+ // QVERIFY( cipherList.contains("SSL_RSA_WITH_RC4_128_MD5") );
+
+ // QVERIFY( cipherList.contains("SSL_DHE_RSA_WITH_DES_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_DSS_WITH_DES_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_RSA_WITH_DES_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_DES40_CBC_SHA") );
+ // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5") );
+ // QVERIFY( cipherList.contains("SSL_RSA_EXPORT_WITH_RC4_40_MD5") );
+
+ // Debian testing (jessie) has no these ciphers. So disable them.
+
+ // cipherList = tls->supportedCipherSuites(QCA::TLS::SSL_v2);
+ // QVERIFY( cipherList.contains("SSL_CK_DES_192_EDE3_CBC_WITH_MD5") );
+ // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
+ // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_WITH_MD5") );
+ // QVERIFY( cipherList.contains("SSL_CK_RC4_128_WITH_MD5") );
+ // QVERIFY( cipherList.contains("SSL_CK_DES_64_CBC_WITH_MD5") );
+ // QVERIFY( cipherList.contains("SSL_CK_RC2_128_CBC_EXPORT40_WITH_MD5") );
+ // QVERIFY( cipherList.contains("SSL_CK_RC4_128_EXPORT40_WITH_MD5") );
}
}
QTEST_MAIN(TLSUnitTest)
#include "tlsunittest.moc"
diff --git a/unittest/velox/veloxunittest.cpp b/unittest/velox/veloxunittest.cpp
index 06a557f8..43cb9490 100644
--- a/unittest/velox/veloxunittest.cpp
+++ b/unittest/velox/veloxunittest.cpp
@@ -1,219 +1,217 @@
/**
* Copyright (C) 2006 Brad Hards <bradh@frogmouth.net>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <QTcpSocket>
#include <QtTest/QtTest>
#include <QtCrypto>
#ifdef QT_STATICPLUGIN
#include "import_plugins.h"
#endif
class TlsTest : public QObject
{
Q_OBJECT
public:
TlsTest()
{
- sock = new QTcpSocket( this );
+ sock = new QTcpSocket(this);
connect(sock, SIGNAL(connected()), SLOT(sock_connected()));
connect(sock, SIGNAL(readyRead()), SLOT(sock_readyRead()));
- ssl = new QCA::TLS( this );
+ ssl = new QCA::TLS(this);
connect(ssl, SIGNAL(handshaken()), SLOT(ssl_handshaken()));
connect(ssl, SIGNAL(readyReadOutgoing()),
SLOT(ssl_readyReadOutgoing()));
- sync = new QCA::Synchronizer( this );
+ sync = new QCA::Synchronizer(this);
}
~TlsTest()
{
delete ssl;
delete sock;
}
void start(const QString &_host, int port)
{
host = _host;
sock->connectToHost(host, port);
}
- void waitForHandshake( int timeout = 20000 )
+ void waitForHandshake(int timeout = 20000)
{
- sync->waitForCondition( timeout );
+ sync->waitForCondition(timeout);
}
bool isHandshaken()
{
return ssl->isHandshaken();
}
private slots:
void sock_connected()
{
QCA::CertificateCollection rootCerts;
QCA::ConvertResult resultRootCert;
- QCA::Certificate rootCert = QCA::Certificate::fromPEMFile( "root.crt", &resultRootCert);
- QCOMPARE( resultRootCert, QCA::ConvertGood );
- rootCerts.addCertificate( rootCert );
+ QCA::Certificate rootCert = QCA::Certificate::fromPEMFile("root.crt", &resultRootCert);
+ QCOMPARE(resultRootCert, QCA::ConvertGood);
+ rootCerts.addCertificate(rootCert);
ssl->setTrustedCertificates(rootCerts);
ssl->startClient(host);
}
void sock_readyRead()
{
ssl->writeIncoming(sock->readAll());
}
void ssl_handshaken()
{
QCA::TLS::IdentityResult r = ssl->peerIdentityResult();
- QCOMPARE( r, QCA::TLS::Valid );
+ QCOMPARE(r, QCA::TLS::Valid);
sync->conditionMet();
}
void ssl_readyReadOutgoing()
{
sock->write(ssl->readOutgoing());
}
private:
QString host;
QTcpSocket *sock;
QCA::TLS *ssl;
QCA::Certificate cert;
QCA::Synchronizer *sync;
};
-
class VeloxUnitTest : public QObject
{
Q_OBJECT
private slots:
void initTestCase();
void cleanupTestCase();
void sniAlice();
void sniBob();
void sniCarol();
void sniDave();
void sniMallory();
void sniIvan();
private:
- QCA::Initializer* m_init;
+ QCA::Initializer *m_init;
QCA::CertificateCollection rootCerts;
};
void VeloxUnitTest::initTestCase()
{
m_init = new QCA::Initializer;
}
void VeloxUnitTest::cleanupTestCase()
{
delete m_init;
}
void VeloxUnitTest::sniAlice()
{
- if(!QCA::isSupported("tls", "qca-ossl"))
- QWARN("TLS not supported for qca-ossl");
- else {
+ if (!QCA::isSupported("tls", "qca-ossl")) {
+ QWARN("TLS not supported for qca-ossl");
+ } else {
TlsTest *s = new TlsTest;
- s->start( "alice.sni.velox.ch", 443 );
+ s->start("alice.sni.velox.ch", 443);
s->waitForHandshake();
- QVERIFY( s->isHandshaken() );
+ QVERIFY(s->isHandshaken());
}
}
void VeloxUnitTest::sniBob()
{
- if(!QCA::isSupported("tls", "qca-ossl"))
- QWARN("TLS not supported for qca-ossl");
- else {
+ if (!QCA::isSupported("tls", "qca-ossl")) {
+ QWARN("TLS not supported for qca-ossl");
+ } else {
TlsTest *s = new TlsTest;
- s->start( "bob.sni.velox.ch", 443 );
+ s->start("bob.sni.velox.ch", 443);
s->waitForHandshake();
- QVERIFY( s->isHandshaken() );
+ QVERIFY(s->isHandshaken());
}
}
void VeloxUnitTest::sniCarol()
{
- if(!QCA::isSupported("tls", "qca-ossl"))
- QWARN("TLS not supported for qca-ossl");
- else {
+ if (!QCA::isSupported("tls", "qca-ossl")) {
+ QWARN("TLS not supported for qca-ossl");
+ } else {
TlsTest *s = new TlsTest;
- s->start( "carol.sni.velox.ch", 443 );
+ s->start("carol.sni.velox.ch", 443);
s->waitForHandshake();
- QVERIFY( s->isHandshaken() );
+ QVERIFY(s->isHandshaken());
}
}
void VeloxUnitTest::sniDave()
{
- if(!QCA::isSupported("tls", "qca-ossl"))
- QWARN("TLS not supported for qca-ossl");
- else {
+ if (!QCA::isSupported("tls", "qca-ossl")) {
+ QWARN("TLS not supported for qca-ossl");
+ } else {
TlsTest *s = new TlsTest;
- s->start( "dave.sni.velox.ch", 443 );
+ s->start("dave.sni.velox.ch", 443);
s->waitForHandshake();
- QVERIFY( s->isHandshaken() );
+ QVERIFY(s->isHandshaken());
}
}
void VeloxUnitTest::sniMallory()
{
- if(!QCA::isSupported("tls", "qca-ossl"))
- QWARN("TLS not supported for qca-ossl");
- else {
+ if (!QCA::isSupported("tls", "qca-ossl")) {
+ QWARN("TLS not supported for qca-ossl");
+ } else {
TlsTest *s = new TlsTest;
- s->start( "mallory.sni.velox.ch", 443 );
+ s->start("mallory.sni.velox.ch", 443);
s->waitForHandshake();
- QVERIFY( s->isHandshaken() );
+ QVERIFY(s->isHandshaken());
}
}
-
void VeloxUnitTest::sniIvan()
{
- if(!QCA::isSupported("tls", "qca-ossl"))
- QWARN("TLS not supported for qca-ossl");
- else {
+ if (!QCA::isSupported("tls", "qca-ossl")) {
+ QWARN("TLS not supported for qca-ossl");
+ } else {
TlsTest *s = new TlsTest;
- s->start( "ivan.sni.velox.ch", 443 );
+ s->start("ivan.sni.velox.ch", 443);
s->waitForHandshake();
- QVERIFY( s->isHandshaken() );
+ QVERIFY(s->isHandshaken());
}
}
QTEST_MAIN(VeloxUnitTest)
#include "veloxunittest.moc"