1/*
2 * qca_securemessage.h - Qt Cryptographic Architecture
3 * Copyright (C) 2003-2007 Justin Karneges <justin@affinix.com>
4 * Copyright (C) 2004,2005 Brad Hards <bradh@frogmouth.net>
5 *
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 * 02110-1301 USA
20 *
21 */
22
23/**
24 \file qca_securemessage.h
25
26 Header file for secure message (PGP, CMS) classes
27
28 \note You should not use this header directly from an
29 application. You should just use <tt> \#include \<QtCrypto>
30 </tt> instead.
31*/
32
33#ifndef QCA_SECUREMESSAGE_H
34#define QCA_SECUREMESSAGE_H
35
36#include "qca_cert.h"
37#include "qca_core.h"
38#include "qca_publickey.h"
39#include <QObject>
40
41class QDateTime;
42
43namespace QCA {
44
45class SecureMessageSystem;
46
47/**
48 \class SecureMessageKey qca_securemessage.h QtCrypto
49
50 Key for SecureMessage system
51
52 \ingroup UserAPI
53*/
54class QCA_EXPORT SecureMessageKey
55{
56public:
57 /**
58 The key type
59 */
60 enum Type
61 {
62 None, ///< no key
63 PGP, ///< Pretty Good Privacy key
64 X509 ///< X.509 CMS key
65 };
66
67 /**
68 Construct an empty key
69 */
70 SecureMessageKey();
71
72 /**
73 Standard copy constructor
74
75 \param from the source key
76 */
77 SecureMessageKey(const SecureMessageKey &from);
78
79 ~SecureMessageKey();
80
81 /**
82 Standard assignment operator
83
84 \param from the source key
85 */
86 SecureMessageKey &operator=(const SecureMessageKey &from);
87
88 /**
89 Returns true for null object
90 */
91 bool isNull() const;
92
93 /**
94 The key type
95 */
96 Type type() const;
97
98 /**
99 Public key part of a PGP key
100 */
101 PGPKey pgpPublicKey() const;
102
103 /**
104 Private key part of a PGP key
105 */
106 PGPKey pgpSecretKey() const;
107
108 /**
109 Set the public key part of a PGP key
110
111 \param pub the PGP public key
112 */
113 void setPGPPublicKey(const PGPKey &pub);
114
115 /**
116 Set the private key part of a PGP key
117
118 \param sec the PGP secretkey
119 */
120 void setPGPSecretKey(const PGPKey &sec);
121
122 /**
123 The X.509 certificate chain (public part) for this key
124 */
125 CertificateChain x509CertificateChain() const;
126
127 /**
128 The X.509 private key part of this key
129 */
130 PrivateKey x509PrivateKey() const;
131
132 /**
133 Set the public key part of this X.509 key.
134
135 \param c the Certificate chain containing the public keys
136 */
137 void setX509CertificateChain(const CertificateChain &c);
138
139 /**
140 Set the private key part of this X.509 key.
141
142 \param k the private key
143 */
144 void setX509PrivateKey(const PrivateKey &k);
145
146 /**
147 Set the public and private part of this X.509 key with KeyBundle.
148
149 \param kb the public and private key bundle
150 */
151 void setX509KeyBundle(const KeyBundle &kb);
152
153 /**
154 Test if this key contains a private key part
155 */
156 bool havePrivate() const;
157
158 /**
159 The name associated with this key
160
161 For a PGP key, this is the primary user ID
162
163 For an X.509 key, this is the Common Name
164 */
165 QString name() const;
166
167private:
168 class Private;
169 QSharedDataPointer<Private> d;
170};
171
172/**
173 A list of message keys
174*/
175typedef QList<SecureMessageKey> SecureMessageKeyList;
176
177/**
178 \class SecureMessageSignature qca_securemessage.h QtCrypto
179
180 SecureMessage signature
181
182 \ingroup UserAPI
183*/
184class QCA_EXPORT SecureMessageSignature
185{
186public:
187 /**
188 The result of identity verification
189 */
190 enum IdentityResult
191 {
192 Valid, ///< indentity is verified, matches signature
193 InvalidSignature, ///< valid key provided, but signature failed
194 InvalidKey, ///< invalid key provided
195 NoKey ///< identity unknown
196 };
197
198 /**
199 Create an empty signature check object.
200
201 User applications don't normally need to create signature checks. You normally
202 get the object back as a result of a SecureMessage operation.
203 */
204 SecureMessageSignature();
205
206 /**
207 Create a signature check object
208
209 User applications don't normally need to create signature checks. You normally
210 get the object back as a result of a SecureMessage operation.
211
212 \param r the result of the check
213 \param v the Validity of the key validation check
214 \param key the key associated with the signature
215 \param ts the timestamp associated with the signature
216 */
217 SecureMessageSignature(IdentityResult r, Validity v, const SecureMessageKey &key, const QDateTime &ts);
218
219 /**
220 Standard copy constructor
221
222 \param from the source signature object
223 */
224 SecureMessageSignature(const SecureMessageSignature &from);
225
226 ~SecureMessageSignature();
227
228 /**
229 Standard assignment operator
230
231 \param from the source signature object
232 */
233 SecureMessageSignature &operator=(const SecureMessageSignature &from);
234
235 /**
236 get the results of the identity check on this signature
237 */
238 IdentityResult identityResult() const;
239
240 /**
241 get the results of the key validation check on this signature
242 */
243 Validity keyValidity() const;
244
245 /**
246 get the key associated with this signature
247 */
248 SecureMessageKey key() const;
249
250 /**
251 get the timestamp associated with this signature
252 */
253 QDateTime timestamp() const;
254
255private:
256 class Private;
257 QSharedDataPointer<Private> d;
258};
259
260/**
261 A list of signatures
262*/
263typedef QList<SecureMessageSignature> SecureMessageSignatureList;
264
265/**
266 \class SecureMessage qca_securemessage.h QtCrypto
267
268 Class representing a secure message
269
270 SecureMessage presents a unified interface for working with both
271 OpenPGP and CMS (S/MIME) messages. Prepare the object by calling
272 setFormat(), setRecipient(), and setSigner() as necessary, and then
273 begin the operation by calling an appropriate 'start' function, such
274 as startSign().
275
276 Here is an example of how to perform a Clearsign operation using PGP:
277
278 \code
279// first make the SecureMessageKey
280PGPKey myPGPKey = getSecretKeyFromSomewhere();
281SecureMessageKey key;
282key.setPGPSecretKey(myPGPKey);
283
284// our data to sign
285QByteArray plain = "Hello, world";
286
287// let's do it
288OpenPGP pgp;
289SecureMessage msg(&pgp);
290msg.setSigner(key);
291msg.startSign(SecureMessage::Clearsign);
292msg.update(plain);
293msg.end();
294msg.waitForFinished(-1);
295
296if(msg.success())
297{
298 QByteArray result = msg.read();
299 // result now contains the clearsign text data
300}
301else
302{
303 // error
304 ...
305}
306 \endcode
307
308 Performing a CMS sign operation is similar. Simply set up the
309 SecureMessageKey with a Certificate instead of a PGPKey, and operate on a
310 CMS object instead of an OpenPGP object.
311
312 \sa SecureMessageKey
313 \sa SecureMessageSignature
314 \sa OpenPGP
315 \sa CMS
316
317 \ingroup UserAPI
318*/
319class QCA_EXPORT SecureMessage : public QObject, public Algorithm
320{
321 Q_OBJECT
322public:
323 /**
324 The type of secure message
325 */
326 enum Type
327 {
328 OpenPGP, ///< a Pretty Good Privacy message
329 CMS ///< a Cryptographic Message Syntax message
330 };
331
332 /**
333 The type of message signature
334 */
335 enum SignMode
336 {
337 Message, ///< the message includes the signature
338 Clearsign, ///< the message is clear signed
339 Detached ///< the signature is detached
340 };
341
342 /**
343 Formats for secure messages
344 */
345 enum Format
346 {
347 Binary, ///< DER/binary
348 Ascii ///< PEM/ascii-armored
349 };
350
351 /**
352 Errors for secure messages
353 */
354 enum Error
355 {
356 ErrorPassphrase, ///< passphrase was either wrong or not provided
357 ErrorFormat, ///< input format was bad
358 ErrorSignerExpired, ///< signing key is expired
359 ErrorSignerInvalid, ///< signing key is invalid in some way
360 ErrorEncryptExpired, ///< encrypting key is expired
361 ErrorEncryptUntrusted, ///< encrypting key is untrusted
362 ErrorEncryptInvalid, ///< encrypting key is invalid in some way
363 ErrorNeedCard, ///< pgp card is missing
364 ErrorCertKeyMismatch, ///< certificate and private key don't match
365 ErrorUnknown, ///< other error
366 ErrorSignerRevoked, ///< signing key is revoked
367 ErrorSignatureExpired, ///< signature is expired
368 ErrorEncryptRevoked ///< encrypting key is revoked
369 };
370
371 /**
372 Create a new secure message
373
374 This constructor uses an existing
375 SecureMessageSystem object (for example, an OpenPGP
376 or CMS object) to generate a specific kind of
377 secure message.
378
379 \param system a pre-existing and configured SecureMessageSystem
380 object
381 */
382 SecureMessage(SecureMessageSystem *system);
383 ~SecureMessage() override;
384
385 /**
386 The Type of secure message
387 */
388 Type type() const;
389
390 /**
391 Test if the message type supports multiple
392 (parallel) signatures.
393
394 \return true if the secure message support multiple
395 parallel signatures
396
397 \note PGP cannot do this - it is primarily a CMS
398 feature
399 */
400 bool canSignMultiple() const;
401
402 /**
403 True if the SecureMessageSystem can clearsign
404 messages.
405
406 \note CMS cannot clearsign - this is normally only
407 available for PGP
408 */
409 bool canClearsign() const;
410
411 /**
412 True if the SecureMessageSystem can both sign and
413 encrypt (in the same operation).
414
415 \note CMS cannot do an integrated sign/encrypt -
416 this is normally only available for PGP. You can do
417 separate signing and encrypting operations on the
418 same message with CMS though.
419 */
420 bool canSignAndEncrypt() const;
421
422 /**
423 Reset the object state to that of original construction.
424 Now a new operation can be performed immediately.
425 */
426 void reset();
427
428 /**
429 Returns true if bundling of the signer certificate chain is
430 enabled
431 */
432 bool bundleSignerEnabled() const;
433
434 /**
435 Returns true if inclusion of S/MIME attributes is enabled
436 */
437 bool smimeAttributesEnabled() const;
438
439 /**
440 Return the format type set for this message
441 */
442 Format format() const;
443
444 /**
445 Return the recipient(s) set for this message with setRecipient() or
446 setRecipients()
447 */
448 SecureMessageKeyList recipientKeys() const;
449
450 /**
451 Return the signer(s) set for this message with setSigner() or
452 setSigners()
453 */
454 SecureMessageKeyList signerKeys() const;
455
456 /**
457 For CMS only, this will bundle the signer certificate chain
458 into the message. This allows a message to be verified
459 on its own, without the need to have obtained the signer's
460 certificate in advance. Email clients using S/MIME often
461 bundle the signer, greatly simplifying key management.
462
463 This behavior is enabled by default.
464
465 \param b whether to bundle (if true) or not (false)
466 */
467 void setBundleSignerEnabled(bool b);
468
469 /**
470 For CMS only, this will put extra attributes into the
471 message related to S/MIME, such as the preferred
472 type of algorithm to use in replies. The attributes
473 used are decided by the provider.
474
475 This behavior is enabled by default.
476
477 \param b whether to embed extra attribues (if true) or not (false)
478 */
479 void setSMIMEAttributesEnabled(bool b);
480
481 /**
482 Set the Format used for messages
483
484 The default is Binary.
485
486 \param f whether to use Binary or Ascii
487 */
488 void setFormat(Format f);
489
490 /**
491 Set the recipient for an encrypted message
492
493 \param key the recipient's key
494
495 \sa setRecipients
496 */
497 void setRecipient(const SecureMessageKey &key);
498
499 /**
500 Set the list of recipients for an encrypted message.
501
502 For a list with one item, this has the same effect as setRecipient.
503
504 \param keys the recipients' key
505
506 \sa setRecipient
507 */
508 void setRecipients(const SecureMessageKeyList &keys);
509
510 /**
511 Set the signer for a signed message.
512
513 This is used for both creating signed messages as well as for
514 verifying CMS messages that have no signer bundled.
515
516 \param key the key associated with the signer
517
518 \sa setSigners
519 */
520 void setSigner(const SecureMessageKey &key);
521
522 /**
523 Set the list of signers for a signed message.
524
525 This is used for both creating signed messages as well as for
526 verifying CMS messages that have no signer bundled.
527
528 For a list with one item, this has the same effect as setSigner.
529
530 \param keys the key associated with the signer
531
532 \sa setSigner
533 */
534 void setSigners(const SecureMessageKeyList &keys);
535
536 /**
537 Start an encryption operation
538
539 You will normally use this with some code along
540 these lines:
541 \code
542encryptingObj.startEncrypt();
543encryptingObj.update(message);
544// perhaps some more update()s
545encryptingObj.end();
546 \endcode
547
548 Each update() may (or may not) result in some
549 encrypted data, as indicated by the readyRead()
550 signal being emitted. Alternatively, you can wait
551 until the whole message is available (using either
552 waitForFinished(), or use the finished()
553 signal. The encrypted message can then be read
554 using the read() method.
555 */
556 void startEncrypt();
557
558 /**
559 Start an decryption operation
560
561 You will normally use this with some code along
562 these lines:
563 \code
564decryptingObj.startEncrypt();
565decryptingObj.update(message);
566// perhaps some more update()s
567decryptingObj.end();
568 \endcode
569
570 Each update() may (or may not) result in some
571 decrypted data, as indicated by the readyRead()
572 signal being emitted. Alternatively, you can wait
573 until the whole message is available (using either
574 waitForFinished(), or the finished()
575 signal). The decrypted message can then be read
576 using the read() method.
577
578 \note If decrypted result is also signed (not for
579 CMS), then the signature will be verified during
580 this operation.
581 */
582 void startDecrypt();
583
584 /**
585 Start a signing operation
586
587 You will normally use this with some code along
588 these lines:
589 \code
590signingObj.startSign(QCA::SecureMessage::Detached)
591signingObj.update(message);
592// perhaps some more update()s
593signingObj.end();
594 \endcode
595
596 For Detached signatures, you won't get any results
597 until the whole process is done - you either
598 waitForFinished(), or use the finished() signal, to
599 figure out when you can get the signature (using
600 the signature() method, not using read()). For
601 other formats, you can use the readyRead() signal
602 to determine when there may be part of a signed
603 message to read().
604
605 \param m the mode that will be used to generate the
606 signature
607 */
608 void startSign(SignMode m = Message);
609
610 /**
611 Start a verification operation
612
613 \param detachedSig the detached signature to
614 verify. Do not pass a signature for other signature
615 types.
616 */
617 void startVerify(const QByteArray &detachedSig = QByteArray());
618
619 /**
620 Start a combined signing and encrypting
621 operation. You use this in the same way as
622 startEncrypt().
623
624 \note This may not be possible (e.g. CMS
625 cannot do this) - see canSignAndEncrypt() for a
626 suitable test.
627 */
628 void startSignAndEncrypt();
629
630 /**
631 Process a message (or the next part of a message)
632 in the current operation. You need to have already
633 set up the message (startEncrypt(), startDecrypt(),
634 startSign(), startSignAndEncrypt() and
635 startVerify()) before calling this method.
636
637 \param in the data to process
638 */
639 void update(const QByteArray &in);
640
641 /**
642 Read the available data.
643
644 \note For detached signatures, you don't get
645 anything back using this method. Use signature() to
646 get the detached signature().
647 */
648 QByteArray read();
649
650 /**
651 The number of bytes available to be read.
652 */
653 int bytesAvailable() const;
654
655 /**
656 Complete an operation.
657
658 You need to call this method after you have
659 processed the message (which you pass in as the
660 argument to update().
661
662 \note the results of the operation are not
663 available as soon as this method returns. You need
664 to wait for the finished() signal, or use
665 waitForFinished().
666 */
667 void end();
668
669 /**
670 Block until the operation (encryption, decryption,
671 signing or verifying) completes.
672
673 \param msecs the number of milliseconds to wait for
674 the operation to complete. Pass -1 to wait
675 indefinitely.
676
677 \note You should not use this in GUI
678 applications where the blocking behaviour looks
679 like a hung application. Instead, connect the
680 finished() signal to a slot that handles the
681 results.
682
683 \note This synchronous operation may require event handling, and so
684 it must not be called from the same thread as an EventHandler.
685 */
686 bool waitForFinished(int msecs = 30000);
687
688 /**
689 Indicates whether or not the operation was successful
690 or failed. If this function returns false, then
691 the reason for failure can be obtained with errorCode().
692
693 \sa errorCode
694 \sa diagnosticText
695 */
696 bool success() const;
697
698 /**
699 Returns the failure code.
700
701 \sa success
702 \sa diagnosticText
703 */
704 Error errorCode() const;
705
706 /**
707 The signature for the message. This is only used
708 for Detached signatures. For other message types,
709 you get the message and signature together using
710 read().
711 */
712 QByteArray signature() const;
713
714 /**
715 The name of the hash used for the signature process
716 */
717 QString hashName() const;
718
719 /**
720 Test if the message was signed.
721
722 This is true for OpenPGP if the decrypted message
723 was also signed.
724
725 \return true if the message was signed.
726 */
727 bool wasSigned() const;
728
729 /**
730 Verify that the message signature is correct.
731
732 \return true if the signature is valid for the
733 message, otherwise return false
734 */
735 bool verifySuccess() const;
736
737 /**
738 Information on the signer for the message
739 */
740 SecureMessageSignature signer() const;
741
742 /**
743 Information on the signers for the message.
744
745 This is only meaningful if the message type supports
746 multiple signatures (see canSignMultiple() for a
747 suitable test).
748 */
749 SecureMessageSignatureList signers() const;
750
751 /**
752 Returns a log of technical information about the operation,
753 which may be useful for presenting to the user in an
754 advanced error dialog.
755 */
756 QString diagnosticText() const;
757
758Q_SIGNALS:
759 /**
760 This signal is emitted when there is some data to
761 read. Typically you connect this signal to a slot
762 that does a read() of the available data.
763
764 \note This signal does not mean that the processing
765 of a message is necessarily complete - see
766 finished().
767 */
768 void readyRead();
769
770 /**
771 This signal is emitted when data has been accepted
772 by the message processor.
773
774 \param bytes the number of bytes written
775 */
776 void bytesWritten(int bytes);
777
778 /**
779 This signal is emitted when the message is fully
780 processed.
781 */
782 void finished();
783
784private:
785 Q_DISABLE_COPY(SecureMessage)
786
787 class Private;
788 friend class Private;
789 Private *d;
790};
791
792/**
793 \class SecureMessageSystem qca_securemessage.h QtCrypto
794
795 Abstract superclass for secure messaging systems
796
797 \sa SecureMessage
798 \sa SecureMessageKey
799
800 \ingroup UserAPI
801*/
802class QCA_EXPORT SecureMessageSystem : public QObject, public Algorithm
803{
804 Q_OBJECT
805public:
806 ~SecureMessageSystem() override;
807
808protected:
809 /**
810 Protected constructor for SecureMessageSystem
811 classes. You are meant to be using a subclass (such
812 as OpenPGP or CMS) - you only need to worry about
813 this class if you are creating a whole new
814 SecureMessageSystem type.
815
816 \param parent the parent object for this object
817 \param type the name of the Type of
818 SecureMessageSystem to create
819 \param provider the provider to use, if a specific
820 provider is required.
821 */
822 SecureMessageSystem(QObject *parent, const QString &type, const QString &provider);
823
824private:
825 Q_DISABLE_COPY(SecureMessageSystem)
826};
827
828/**
829 \class OpenPGP qca_securemessage.h QtCrypto
830
831 Pretty Good Privacy messaging system
832
833 \sa SecureMessage
834 \sa SecureMessageKey
835
836 \ingroup UserAPI
837
838*/
839class QCA_EXPORT OpenPGP : public SecureMessageSystem
840{
841 Q_OBJECT
842public:
843 /**
844 Standard constructor
845
846 \param parent the parent object for this object
847 \param provider the provider to use, if a specific
848 provider is required
849 */
850 explicit OpenPGP(QObject *parent = nullptr, const QString &provider = QString());
851 ~OpenPGP() override;
852
853private:
854 Q_DISABLE_COPY(OpenPGP)
855
856 class Private;
857 Private *d;
858};
859
860/**
861 \class CMS qca_securemessage.h QtCrypto
862
863 Cryptographic Message Syntax messaging system
864
865 Cryptographic Message Syntax (%CMS) "is used to digitally
866 sign, digest, authenticate, or encrypt arbitrary message
867 content. The %CMS describes an encapsulation syntax for
868 data protection. It supports digital signatures and
869 encryption. The syntax allows multiple encapsulations; one
870 encapsulation envelope can be nested inside another.
871 Likewise, one party can digitally sign some previously
872 encapsulated data. It also allows arbitrary attributes,
873 such as signing time, to be signed along with the message
874 content, and provides for other attributes such as
875 countersignatures to be associated with a signature." (from
876 <a href="http://www.ietf.org/rfc/rfc3852.txt">RFC3852</a>
877 "Cryptographic Message Syntax")
878
879 \sa SecureMessage
880 \sa SecureMessageKey
881
882 \ingroup UserAPI
883
884*/
885class QCA_EXPORT CMS : public SecureMessageSystem
886{
887 Q_OBJECT
888public:
889 /**
890 Standard constructor
891
892 \param parent the parent object for this object
893 \param provider the provider to use, if a specific
894 provider is required
895 */
896 explicit CMS(QObject *parent = nullptr, const QString &provider = QString());
897 ~CMS() override;
898
899 /**
900 Return the trusted certificates set for this object
901 */
902 CertificateCollection trustedCertificates() const;
903
904 /**
905 Return the untrusted certificates set for this object
906 */
907 CertificateCollection untrustedCertificates() const;
908
909 /**
910 Return the private keys set for this object
911 */
912 SecureMessageKeyList privateKeys() const;
913
914 /**
915 Set the trusted certificates to use for the
916 messages built using this CMS object.
917
918 \param trusted the collection of trusted
919 certificates to use
920 */
921 void setTrustedCertificates(const CertificateCollection &trusted);
922
923 /**
924 Set the untrusted certificates to use for the
925 messages built using this CMS object.
926
927 This function is useful when verifying messages that don't
928 contain the certificates (or intermediate signers) within
929 the CMS blob. In order to verify such messages, you'll
930 have to pass the possible signer certs with this function.
931
932 \param untrusted the collection of untrusted
933 certificates to use
934 */
935 void setUntrustedCertificates(const CertificateCollection &untrusted);
936
937 /**
938 Set the private keys to use for the messages built
939 using this CMS object.
940
941 Keys are required for decrypting and signing (not
942 for encrypting or verifying).
943
944 \param keys the collection of keys to use
945 */
946 void setPrivateKeys(const SecureMessageKeyList &keys);
947
948private:
949 Q_DISABLE_COPY(CMS)
950
951 class Private;
952 Private *d;
953};
954
955}
956
957#endif
958

source code of qca/include/QtCrypto/qca_securemessage.h