rsatest.cpp

The code below shows some of the capabilities for how to use RSA.

The code below shows some of the capabilities for how to use RSA. This example also shows how to export and import a key to a file, using PEM encoding.

/*
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 <QCoreApplication>
#include <QtCrypto>
#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(QStringLiteral("keyprivate.pem"), passPhrase);
// Read that key back in, checking if the read succeeded
QCA::ConvertResult conversionResult;
QCA::PrivateKey privateKey =
QCA::PrivateKey::fromPEMFile(QStringLiteral("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;
}
QCA::Initializer
Convenience method for initialising and cleaning up QCA.
Definition qca_core.h:660
QCA::KeyGenerator
Class for generating asymmetric key pairs.
Definition qca_publickey.h:1138
QCA::KeyGenerator::createRSA
PrivateKey createRSA(int bits, int exp=65537, const QString &provider=QString())
Generate an RSA key of the specified length.
QCA::PKey::supportedIOTypes
static QList< Type > supportedIOTypes(const QString &provider=QString())
Test what types of keys are supported for IO operations.
QCA::PKey::toPublicKey
PublicKey toPublicKey() const
Interpret this key as a PublicKey.
QCA::PKey::isNull
bool isNull() const
Test if the key is null (empty).
QCA::PKey::RSA
@ RSA
RSA key.
Definition qca_publickey.h:258
QCA::PrivateKey
Generic private key.
Definition qca_publickey.h:833
QCA::PrivateKey::update
void update(const MemoryRegion &a)
Update the signature process.
QCA::PrivateKey::toPEMFile
bool toPEMFile(const QString &fileName, const SecureArray &passphrase=SecureArray(), PBEAlgorithm pbe=PBEDefault) const
Export the key in Privacy Enhanced Mail (PEM) format to a file.
QCA::PrivateKey::decrypt
bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg)
Decrypt the message.
QCA::PrivateKey::signature
QByteArray signature()
The resulting signature.
QCA::PrivateKey::fromPEMFile
static PrivateKey fromPEMFile(const QString &fileName, const SecureArray &passphrase=SecureArray(), ConvertResult *result=nullptr, const QString &provider=QString())
Import the key in Privacy Enhanced Mail (PEM) format from a file.
QCA::PrivateKey::startSign
void startSign(SignatureAlgorithm alg, SignatureFormat format=DefaultFormat)
Initialise the message signature process.
QCA::PrivateKey::canSign
bool canSign() const
Test if this key can be used for signing.
QCA::PublicKey
Generic public key.
Definition qca_publickey.h:529
QCA::PublicKey::update
void update(const MemoryRegion &a)
Update the signature verification process with more data.
QCA::PublicKey::verifyMessage
bool verifyMessage(const MemoryRegion &a, const QByteArray &sig, SignatureAlgorithm alg, SignatureFormat format=DefaultFormat)
Single step message verification.
QCA::PublicKey::canEncrypt
bool canEncrypt() const
Test if this key can be used for encryption.
QCA::PublicKey::validSignature
bool validSignature(const QByteArray &sig)
Check the signature is valid for the message.
QCA::PublicKey::startVerify
void startVerify(SignatureAlgorithm alg, SignatureFormat format=DefaultFormat)
Initialise the signature verification process.
QCA::PublicKey::canVerify
bool canVerify() const
Test if the key can be used for verifying signatures.
QCA::PublicKey::encrypt
SecureArray encrypt(const SecureArray &a, EncryptionAlgorithm alg)
Encrypt a message using a specified algorithm.
QCA::SecureArray
Secure array of bytes.
Definition qca_tools.h:317
QCA::SecureArray::data
char * data()
Pointer to the data in the secure array.
QCA::SecureArray::toByteArray
QByteArray toByteArray() const
Copy the contents of the secure array out to a standard QByteArray.
QCA::SecureArray::isEmpty
bool isEmpty() const
Test if the array contains any bytes.
QCA::EME_PKCS1_OAEP
@ EME_PKCS1_OAEP
Optimal asymmetric encryption padding (PKCS#1, Version 2.0).
Definition qca_publickey.h:57
QCA::arrayToHex
QCA_EXPORT QString arrayToHex(const QByteArray &array)
Convert a byte array to printable hexadecimal representation.
QCA::isSupported
QCA_EXPORT bool isSupported(const char *features, const QString &provider=QString())
Test if a capability (algorithm) is available.
QCA::ConvertResult
ConvertResult
Return value from a format conversion.
Definition qca_publickey.h:119
QCA::ConvertGood
@ ConvertGood
Conversion succeeded, results should be valid.
Definition qca_publickey.h:120
QCA::EMSA3_MD5
@ EMSA3_MD5
MD5, with EMSA3 (ie PKCS#1 Version 1.5) encoding (this is the usual RSA algorithm).
Definition qca_publickey.h:78