QCA

rsatest.cpp
1/*
2 Copyright (C) 2003 Justin Karneges <justin@affinix.com>
3 Copyright (C) 2005 Brad Hards <bradh@frogmouth.net>
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
19 AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21*/
22
23#include <QCoreApplication>
24#include <QtCrypto>
25
26#include <iostream>
27
28#ifdef QT_STATICPLUGIN
29#include "import_plugins.h"
30#endif
31
32int main(int argc, char **argv)
33{
34 // The Initializer object sets things up, and also
35 // does cleanup when it goes out of scope
37
38 QCoreApplication app(argc, argv);
39
40 // we use the first argument if provided, or
41 // use "hello" if no arguments
42 QCA::SecureArray arg = (argc >= 2) ? argv[1] : "hello";
43
44 // We demonstrate PEM usage here, so we need to test for
45 // supportedIOTypes, not just supportedTypes
47 std::cout << "RSA not supported!\n";
48 else {
49 // When creating a public / private key pair, you make the
50 // private key, and then extract the public key component from it
51 // Using RSA is very common, however DSA can provide equivalent
52 // signature/verification. This example applies to DSA to the
53 // extent that the operations work on that key type.
54
55 // QCA provides KeyGenerator as a convenient source of new keys,
56 // however you could also import an existing key instead.
58 if (seckey.isNull()) {
59 std::cout << "Failed to make private RSA key" << std::endl;
60 return 1;
61 }
62
63 QCA::PublicKey pubkey = seckey.toPublicKey();
64
65 // check if the key can encrypt
66 if (!pubkey.canEncrypt()) {
67 std::cout << "Error: this kind of key cannot encrypt" << std::endl;
68 return 1;
69 }
70
71 // encrypt some data - note that only the public key is required
72 // you must also choose the algorithm to be used
73 QCA::SecureArray result = pubkey.encrypt(arg, QCA::EME_PKCS1_OAEP);
74 if (result.isEmpty()) {
75 std::cout << "Error encrypting" << std::endl;
76 return 1;
77 }
78
79 // output the encrypted data
80 QString rstr = QCA::arrayToHex(result.toByteArray());
81 std::cout << "\"" << arg.data() << "\" encrypted with RSA is \"";
82 std::cout << qPrintable(rstr) << "\"" << std::endl;
83
84 // save the private key - in a real example, make sure this goes
85 // somewhere secure and has a good pass phrase
86 // You can use the same technique with the public key too.
87 QCA::SecureArray passPhrase = "pass phrase";
88 seckey.toPEMFile(QStringLiteral("keyprivate.pem"), passPhrase);
89
90 // Read that key back in, checking if the read succeeded
91 QCA::ConvertResult conversionResult;
92 QCA::PrivateKey privateKey =
93 QCA::PrivateKey::fromPEMFile(QStringLiteral("keyprivate.pem"), passPhrase, &conversionResult);
94 if (!(QCA::ConvertGood == conversionResult)) {
95 std::cout << "Private key read failed" << std::endl;
96 }
97
98 // now decrypt that encrypted data using the private key that
99 // we read in. The algorithm is the same.
100 QCA::SecureArray decrypt;
101 if (0 == privateKey.decrypt(result, &decrypt, QCA::EME_PKCS1_OAEP)) {
102 std::cout << "Error decrypting.\n";
103 return 1;
104 }
105
106 // output the resulting decrypted string
107 std::cout << "\"" << qPrintable(rstr) << "\" decrypted with RSA is \"";
108 std::cout << decrypt.data() << "\"" << std::endl;
109
110 // Some private keys can also be used for producing signatures
111 if (!privateKey.canSign()) {
112 std::cout << "Error: this kind of key cannot sign" << std::endl;
113 return 1;
114 }
115 privateKey.startSign(QCA::EMSA3_MD5);
116 privateKey.update(arg); // just reuse the same message
117 QByteArray argSig = privateKey.signature();
118
119 // instead of using the startSign(), update(), signature() calls,
120 // you may be better doing the whole thing in one go, using the
121 // signMessage call. Of course you need the whole message in one
122 // hit, which may or may not be a problem
123
124 // output the resulting signature
125 rstr = QCA::arrayToHex(argSig);
126 std::cout << "Signature for \"" << arg.data() << "\" using RSA, is ";
127 std::cout << "\"" << qPrintable(rstr) << "\"" << std::endl;
128
129 // to check a signature, we must check that the key is
130 // appropriate
131 if (pubkey.canVerify()) {
133 pubkey.update(arg);
134 if (pubkey.validSignature(argSig)) {
135 std::cout << "Signature is valid" << std::endl;
136 } else {
137 std::cout << "Bad signature" << std::endl;
138 }
139 }
140
141 // We can also do the verification in a single step if we
142 // have all the message
143 if (pubkey.canVerify() && pubkey.verifyMessage(arg, argSig, QCA::EMSA3_MD5)) {
144 std::cout << "Signature is valid" << std::endl;
145 } else {
146 std::cout << "Signature could not be verified" << std::endl;
147 }
148 }
149
150 return 0;
151}
Convenience method for initialising and cleaning up QCA.
Definition qca_core.h:660
Class for generating asymmetric key pairs.
PrivateKey createRSA(int bits, int exp=65537, const QString &provider=QString())
Generate an RSA key of the specified length.
static QList< Type > supportedIOTypes(const QString &provider=QString())
PublicKey toPublicKey() const
Interpret this key as a PublicKey.
bool isNull() const
Test if the key is null (empty)
@ RSA
RSA key.
Generic private key.
void update(const MemoryRegion &a)
Update the signature process.
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.
bool decrypt(const SecureArray &in, SecureArray *out, EncryptionAlgorithm alg)
Decrypt the message.
QByteArray signature()
The resulting signature.
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.
void startSign(SignatureAlgorithm alg, SignatureFormat format=DefaultFormat)
Initialise the message signature process.
bool canSign() const
Test if this key can be used for signing.
Generic public key.
void update(const MemoryRegion &a)
Update the signature verification process with more data.
bool verifyMessage(const MemoryRegion &a, const QByteArray &sig, SignatureAlgorithm alg, SignatureFormat format=DefaultFormat)
Single step message verification.
bool canEncrypt() const
Test if this key can be used for encryption.
bool validSignature(const QByteArray &sig)
void startVerify(SignatureAlgorithm alg, SignatureFormat format=DefaultFormat)
Initialise the signature verification process.
bool canVerify() const
Test if the key can be used for verifying signatures.
SecureArray encrypt(const SecureArray &a, EncryptionAlgorithm alg)
Encrypt a message using a specified algorithm.
Secure array of bytes.
Definition qca_tools.h:317
char * data()
Pointer to the data in the secure array.
QByteArray toByteArray() const
Copy the contents of the secure array out to a standard QByteArray.
bool isEmpty() const
Test if the array contains any bytes.
void init(KXmlGuiWindow *window, KGameDifficulty *difficulty=nullptr)
@ EME_PKCS1_OAEP
Optimal asymmetric encryption padding (PKCS#1, Version 2.0)
QCA_EXPORT QString arrayToHex(const QByteArray &array)
Convert a byte array to printable hexadecimal representation.
QCA_EXPORT bool isSupported(const char *features, const QString &provider=QString())
Test if a capability (algorithm) is available.
ConvertResult
Return value from a format conversion.
@ ConvertGood
Conversion succeeded, results should be valid.
@ EMSA3_MD5
MD5, with EMSA3 (ie PKCS#1 Version 1.5) encoding (this is the usual RSA algorithm)
This file is part of the KDE documentation.
Documentation copyright © 1996-2024 The KDE developers.
Generated on Fri May 24 2024 11:53:51 by doxygen 1.10.0 written by Dimitri van Heesch, © 1997-2006

KDE's Doxygen guidelines are available online.