forked from weidai11/cryptopp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptlib.h
3232 lines (2833 loc) · 171 KB
/
cryptlib.h
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
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// cryptlib.h - originally written and placed in the public domain by Wei Dai
/// \file cryptlib.h
/// \brief Abstract base classes that provide a uniform interface to this library.
/*! \mainpage Crypto++ Library 7.1 API Reference
<dl>
<dt>Abstract Base Classes<dd>
cryptlib.h
<dt>Authenticated Encryption Modes<dd>
CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)"
<dt>Block Ciphers<dd>
\ref Rijndael "AES", ARIA, Weak::ARC4, Blowfish, BTEA, \ref CHAM128 "CHAM (64/128)", Camellia,
\ref CAST128 "CAST (128/256)", DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES",
\ref DES_XEX3 "DESX", GOST, HIGHT, IDEA, LEA, \ref LR "Luby-Rackoff", \ref Kalyna128 "Kalyna (128/256/512)",
MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent,
\ref SHACAL2 "SHACAL-2", SHARK, \ref SIMECK64 "SIMECK (32/64)" SKIPJACK, SM4, Square, TEA,
\ref ThreeWay "3-Way", \ref Threefish256 "Threefish (256/512/1024)", Twofish, XTEA
<dt>Stream Ciphers<dd>
\ref ChaCha "ChaCha (8/12/20)", \ref HC128 "HC-128/256", \ref Panama "Panama-LE", \ref Panama "Panama-BE",
Rabbit, Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20
<dt>Hash Functions<dd>
BLAKE2s, BLAKE2b, \ref Keccak "Keccak (F1600)", SHA1, SHA224, SHA256, SHA384, SHA512,
\ref SHA3 "SHA-3", SM3, Tiger, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, SipHash, Whirlpool,
Weak::MD2, Weak::MD4, Weak::MD5
<dt>Non-Cryptographic Checksums<dd>
CRC32, Adler32
<dt>Message Authentication Codes<dd>
BLAKE2b, BLAKE2s, CBC_MAC, CMAC, DMAC, \ref GCM "GCM (GMAC)", HMAC, Poly1305, TTMAC, VMAC
<dt>Random Number Generators<dd>
NullRNG, LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG,
NIST Hash_DRBG and HMAC_DRBG, \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)",
DARN, RDRAND, RDSEED
<dt>Key Derivation and Password-based Cryptography<dd>
HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)",
\ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)"
<dt>Public Key Cryptosystems<dd>
DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
<dt>Public Key Signature Schemes<dd>
DSA2, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, RabinSS, RWSS, ESIGN
<dt>Key Agreement<dd>
DH, DH2, \ref MQV_Domain "MQV", \ref HMQV_Domain "HMQV", \ref FHMQV_Domain "FHMQV",
ECDH, x25519, ECMQV, ECHMQV,
ECFHMQV, XTR_DH
<dt>Algebraic Structures<dd>
Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP
<dt>Secret Sharing and Information Dispersal<dd>
SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
<dt>Compression<dd>
Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
<dt>Input Source Classes<dd>
StringSource, ArraySource, VectorSource, FileSource, RandomNumberSource
<dt>Output Sink Classes<dd>
StringSinkTemplate, StringSink, VectorSink, ArraySink, FileSink, RandomNumberSink
<dt>Filter Wrappers<dd>
StreamTransformationFilter, AuthenticatedEncryptionFilter, AuthenticatedDecryptionFilter, HashFilter,
HashVerificationFilter, SignerFilter, SignatureVerificationFilter
<dt>Binary to Text Encoders and Decoders<dd>
HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder,
Base32Decoder
<dt>Wrappers for OS features<dd>
Timer, ThreadUserTimer
</dl>
<!--
<dt>FIPS 140 validated cryptography<dd>
fips140.h
In the DLL version of Crypto++, only the following implementation class are available.
<dl>
<dt>Block Ciphers<dd>
AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK
<dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
\ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>",
\ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>"
<dt>Hash Functions<dd>
SHA1, SHA224, SHA256, SHA384, SHA512
<dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
RSASS\<PKCS1v15, H\>, RSASS\<PSS, H\>, RSASS_ISO\<H\>, RWSS\<P1363_EMSA2, H\>, DSA, ECDSA\<ECP, H\>,
ECDSA\<EC2N, H\>
<dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
HMAC\<H\>, CBC_MAC\<DES_EDE2\>, CBC_MAC\<DES_EDE3\>, GCM\<AES\>
<dt>Random Number Generators<dd>
DefaultAutoSeededRNG (AutoSeededX917RNG\<AES\>)
<dt>Key Agreement<dd>
DH, DH2
<dt>Public Key Cryptosystems<dd>
RSAES\<OAEP\<SHA1\> \>
</dl>
-->
<p>This reference manual is a work in progress. Some classes lack detailed descriptions.
<p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
<p>Thanks to Ryan Phillips for providing the Doxygen configuration file
and getting us started on the manual.
*/
#ifndef CRYPTOPP_CRYPTLIB_H
#define CRYPTOPP_CRYPTLIB_H
#include "config.h"
#include "stdcpp.h"
#include "trap.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4127 4189 4505 4702)
#endif
NAMESPACE_BEGIN(CryptoPP)
// forward declarations
class Integer;
class RandomNumberGenerator;
class BufferedTransformation;
/// \brief Specifies a direction for a cipher to operate
/// \sa BlockTransformation::IsForwardTransformation(), BlockTransformation::IsPermutation(), BlockTransformation::GetCipherDirection()
enum CipherDir {
/// \brief the cipher is performing encryption
ENCRYPTION,
/// \brief the cipher is performing decryption
DECRYPTION};
/// \brief Represents infinite time
const unsigned long INFINITE_TIME = ULONG_MAX;
// VC60 workaround: using enums as template parameters causes problems
/// \brief Converts an enumeration to a type suitable for use as a template parameter
template <typename ENUM_TYPE, int VALUE>
struct EnumToType
{
static ENUM_TYPE ToEnum() {return static_cast<ENUM_TYPE>(VALUE);}
};
/// \brief Provides the byte ordering
/// \details Big-endian and little-endian modes are supported. Bi-endian and PDP-endian modes
/// are not supported.
enum ByteOrder {
/// \brief byte order is little-endian
LITTLE_ENDIAN_ORDER = 0,
/// \brief byte order is big-endian
BIG_ENDIAN_ORDER = 1};
/// \brief Provides a constant for LittleEndian
typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian;
/// \brief Provides a constant for BigEndian
typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian;
/// \brief Base class for all exceptions thrown by the library
/// \details All library exceptions directly or indirectly inherit from the Exception class.
/// The Exception class itself inherits from std::exception. The library does not use
/// std::runtime_error derived classes.
class CRYPTOPP_DLL Exception : public std::exception
{
public:
/// \enum ErrorType
/// \brief Error types or categories
enum ErrorType {
/// \brief A method was called which was not implemented
NOT_IMPLEMENTED,
/// \brief An invalid argument was detected
INVALID_ARGUMENT,
/// \brief BufferedTransformation received a Flush(true) signal but can't flush buffers
CANNOT_FLUSH,
/// \brief Data integerity check, such as CRC or MAC, failed
DATA_INTEGRITY_CHECK_FAILED,
/// \brief Input data was received that did not conform to expected format
INVALID_DATA_FORMAT,
/// \brief Error reading from input device or writing to output device
IO_ERROR,
/// \brief Some other error occurred not belonging to other categories
OTHER_ERROR
};
virtual ~Exception() throw() {}
/// \brief Construct a new Exception
explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
/// \brief Retrieves a C-string describing the exception
const char *what() const throw() {return (m_what.c_str());}
/// \brief Retrieves a string describing the exception
const std::string &GetWhat() const {return m_what;}
/// \brief Sets the error string for the exception
void SetWhat(const std::string &s) {m_what = s;}
/// \brief Retrieves the error type for the exception
ErrorType GetErrorType() const {return m_errorType;}
/// \brief Sets the error type for the exceptions
void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
private:
ErrorType m_errorType;
std::string m_what;
};
/// \brief An invalid argument was detected
class CRYPTOPP_DLL InvalidArgument : public Exception
{
public:
explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
};
/// \brief Input data was received that did not conform to expected format
class CRYPTOPP_DLL InvalidDataFormat : public Exception
{
public:
explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
};
/// \brief A decryption filter encountered invalid ciphertext
class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
{
public:
explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
};
/// \brief A method was called which was not implemented
class CRYPTOPP_DLL NotImplemented : public Exception
{
public:
explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
};
/// \brief Flush(true) was called but it can't completely flush its buffers
class CRYPTOPP_DLL CannotFlush : public Exception
{
public:
explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
};
/// \brief The operating system reported an error
class CRYPTOPP_DLL OS_Error : public Exception
{
public:
virtual ~OS_Error() throw() {}
OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
: Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
/// \brief Retrieve the operating system API that reported the error
const std::string & GetOperation() const {return m_operation;}
/// \brief Retrieve the error code returned by the operating system
int GetErrorCode() const {return m_errorCode;}
protected:
std::string m_operation;
int m_errorCode;
};
/// \brief Returns a decoding results
struct CRYPTOPP_DLL DecodingResult
{
/// \brief Constructs a DecodingResult
/// \details isValidCoding is initialized to false and messageLength is initialized to 0.
explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
/// \brief Constructs a DecodingResult
/// \param len the message length
/// \details isValidCoding is initialized to true.
explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
/// \brief Compare two DecodingResult
/// \param rhs the other DecodingResult
/// \return true if both isValidCoding and messageLength are equal, false otherwise
bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
/// \brief Compare two DecodingResult
/// \param rhs the other DecodingResult
/// \return true if either isValidCoding or messageLength is \a not equal, false otherwise
/// \details Returns <tt>!operator==(rhs)</tt>.
bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
/// \brief Flag to indicate the decoding is valid
bool isValidCoding;
/// \brief Recovered message length if isValidCoding is true, undefined otherwise
size_t messageLength;
};
/// \brief Interface for retrieving values given their names
/// \details This class is used to safely pass a variable number of arbitrarily typed arguments to functions
/// and to read values from keys and crypto parameters.
/// \details To obtain an object that implements NameValuePairs for the purpose of parameter
/// passing, use the MakeParameters() function.
/// \details To get a value from NameValuePairs, you need to know the name and the type of the value.
/// Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports.
/// then look at the Name namespace documentation to see what the type of each value is, or
/// alternatively, call GetIntValue() with the value name, and if the type is not int, a
/// ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object.
/// \sa NullNameValuePairs, g_nullNameValuePairs,
/// <A HREF="http://www.cryptopp.com/wiki/NameValuePairs">NameValuePairs</A> on the Crypto++ wiki
class NameValuePairs
{
public:
virtual ~NameValuePairs() {}
/// \brief Thrown when an unexpected type is encountered
/// \details Exception thrown when trying to retrieve a value using a different type than expected
class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
{
public:
/// \brief Construct a ValueTypeMismatch
/// \param name the name of the value
/// \param stored the \a actual type of the value stored
/// \param retrieving the \a presumed type of the value retrieved
ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
: InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
, m_stored(stored), m_retrieving(retrieving) {}
/// \brief Provides the stored type
/// \return the C++ mangled name of the type
const std::type_info & GetStoredTypeInfo() const {return m_stored;}
/// \brief Provides the retrieveing type
/// \return the C++ mangled name of the type
const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
private:
const std::type_info &m_stored;
const std::type_info &m_retrieving;
};
/// \brief Get a copy of this object or subobject
/// \tparam T class or type
/// \param object reference to a variable that receives the value
template <class T>
bool GetThisObject(T &object) const
{
return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
}
/// \brief Get a pointer to this object
/// \tparam T class or type
/// \param ptr reference to a pointer to a variable that receives the value
template <class T>
bool GetThisPointer(T *&ptr) const
{
return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr);
}
/// \brief Get a named value
/// \tparam T class or type
/// \param name the name of the object or value to retrieve
/// \param value reference to a variable that receives the value
/// \returns true if the value was retrieved, false otherwise
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
template <class T>
bool GetValue(const char *name, T &value) const
{
return GetVoidValue(name, typeid(T), &value);
}
/// \brief Get a named value
/// \tparam T class or type
/// \param name the name of the object or value to retrieve
/// \param defaultValue the default value of the class or type if it does not exist
/// \return the object or value
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
template <class T>
T GetValueWithDefault(const char *name, T defaultValue) const
{
T value;
bool result = GetValue(name, value);
// No assert... this recovers from failure
if (result) {return value;}
return defaultValue;
}
/// \brief Get a list of value names that can be retrieved
/// \return a list of names available to retrieve
/// \details the items in the list are delimited with a colon.
CRYPTOPP_DLL std::string GetValueNames() const
{std::string result; GetValue("ValueNames", result); return result;}
/// \brief Get a named value with type int
/// \param name the name of the value to retrieve
/// \param value the value retrieved upon success
/// \return true if an int value was retrieved, false otherwise
/// \details GetIntValue() is used to ensure we don't accidentally try to get an
/// unsigned int or some other type when we mean int (which is the most common case)
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
{return GetValue(name, value);}
/// \brief Get a named value with type int, with default
/// \param name the name of the value to retrieve
/// \param defaultValue the default value if the name does not exist
/// \return the value retrieved on success or the default value
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
{return GetValueWithDefault(name, defaultValue);}
/// \brief Get a named value with type word64
/// \param name the name of the value to retrieve
/// \param value the value retrieved upon success
/// \return true if an word64 value was retrieved, false otherwise
/// \sa GetValue(), GetValueWithDefault(), GetWord64ValueWithDefault(), GetIntValue(),
/// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredIntParameter()
CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const
{return GetValue(name, value);}
/// \brief Get a named value with type word64, with default
/// \param name the name of the value to retrieve
/// \param defaultValue the default value if the name does not exist
/// \return the value retrieved on success or the default value
/// \sa GetValue(), GetValueWithDefault(), GetWord64Value(), GetIntValue(),
/// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredWord64Parameter()
CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
{return GetValueWithDefault(name, defaultValue);}
/// \brief Ensures an expected name and type is present
/// \param name the name of the value
/// \param stored the type that was stored for the name
/// \param retrieving the type that is being retrieved for the name
/// \throws ValueTypeMismatch
/// \details ThrowIfTypeMismatch() effectively performs a type safety check.
/// stored and retrieving are C++ mangled names for the type.
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
{if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
/// \brief Retrieves a required name/value pair
/// \tparam T class or type
/// \param className the name of the class
/// \param name the name of the value
/// \param value reference to a variable to receive the value
/// \throws InvalidArgument
/// \details GetRequiredParameter() throws InvalidArgument if the name
/// is not present or not of the expected type T.
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
template <class T>
void GetRequiredParameter(const char *className, const char *name, T &value) const
{
if (!GetValue(name, value))
throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
}
/// \brief Retrieves a required name/value pair
/// \param className the name of the class
/// \param name the name of the value
/// \param value reference to a variable to receive the value
/// \throws InvalidArgument
/// \details GetRequiredParameter() throws InvalidArgument if the name
/// is not present or not of the expected type T.
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
{
if (!GetIntValue(name, value))
throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
}
/// \brief Get a named value
/// \param name the name of the object or value to retrieve
/// \param valueType reference to a variable that receives the value
/// \param pValue void pointer to a variable that receives the value
/// \returns true if the value was retrieved, false otherwise
/// \details GetVoidValue() retrieves the value of name if it exists.
/// \note GetVoidValue() is an internal function and should be implemented
/// by derived classes. Users should use one of the other functions instead.
/// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
/// GetRequiredParameter() and GetRequiredIntParameter()
CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
};
// Doxygen cannot handle initialization
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Default channel for BufferedTransformation
/// \details DEFAULT_CHANNEL is equal to an empty string
/// \details The definition for DEFAULT_CHANNEL is in <tt>cryptlib.cpp</tt>.
/// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
/// Initialization Order Fiasco</A>. If you experience a crash in
/// DEFAULT_CHANNEL where the string object is NULL, then you probably have
/// a global object using DEFAULT_CHANNEL before it has been constructed.
const std::string DEFAULT_CHANNEL;
/// \brief Channel for additional authenticated data
/// \details AAD_CHANNEL is equal to "AAD"
/// \details The definition for AAD_CHANNEL is in <tt>cryptlib.cpp</tt>.
/// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
/// Initialization Order Fiasco</A>. If you experience a crash in
/// AAD_CHANNEL where the string object is NULL, then you probably have a
/// global object using AAD_CHANNEL before it has been constructed.
const std::string AAD_CHANNEL;
/// \brief An empty set of name-value pairs
/// \details The definition for g_nullNameValuePairs is in <tt>cryptlib.cpp</tt>.
/// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
/// Initialization Order Fiasco</A>. If you experience a crash in
/// g_nullNameValuePairs where the string object is NULL, then you probably
/// have a global object using g_nullNameValuePairs before it has been
/// constructed.
const NameValuePairs& g_nullNameValuePairs;
#else
extern const std::string DEFAULT_CHANNEL;
extern const std::string AAD_CHANNEL;
extern const NameValuePairs& g_nullNameValuePairs;
#endif
// Document additional name spaces which show up elsewhere in the sources.
#if CRYPTOPP_DOXYGEN_PROCESSING
/// \brief Namespace containing value name definitions.
/// \details Name is part of the CryptoPP namespace.
/// \details The semantics of value names, types are:
/// <pre>
/// ThisObject:ClassName (ClassName, copy of this object or a subobject)
/// ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
/// </pre>
DOCUMENTED_NAMESPACE_BEGIN(Name)
// more names defined in argnames.h
DOCUMENTED_NAMESPACE_END
/// \brief Namespace containing weak and wounded algorithms.
/// \details Weak is part of the CryptoPP namespace. Schemes and algorithms are moved into Weak
/// when their security level is reduced to an unacceptable level by contemporary standards.
/// \details To use an algorithm in the Weak namespace, you must <tt>\c \#define
/// CRYPTOPP_ENABLE_NAMESPACE_WEAK 1</tt> before including a header for a weak or wounded
/// algorithm. For example:
/// <pre>
/// \c \#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
/// \c \#include <md5.h>
/// ...
/// CryptoPP::Weak::MD5 md5;
/// </pre>
DOCUMENTED_NAMESPACE_BEGIN(Weak)
// weak and wounded algorithms
DOCUMENTED_NAMESPACE_END
#endif
/// \brief Namespace containing NaCl library functions
/// \details TweetNaCl is a compact and portable reimplementation of the NaCl library.
DOCUMENTED_NAMESPACE_BEGIN(NaCl)
// crypto_box, crypto_box_open, crypto_sign, and crypto_sign_open (and friends)
DOCUMENTED_NAMESPACE_END
/// \brief Namespace containing testing and benchmark classes.
/// \details Source files for classes in the Test namespaces include
/// <tt>test.cpp</tt>, <tt>validat#.cpp</tt> and <tt>bench#.cpp</tt>.
DOCUMENTED_NAMESPACE_BEGIN(Test)
// testing and benchmark classes
DOCUMENTED_NAMESPACE_END
// ********************************************************
/// \brief Interface for cloning objects
/// \note this is \a not implemented by most classes
/// \sa ClonableImpl, NotCopyable
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
{
public:
virtual ~Clonable() {}
/// \brief Copies this object
/// \return a copy of this object
/// \throws NotImplemented
/// \note this is \a not implemented by most classes
/// \sa NotCopyable
virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
};
/// \brief Interface for all crypto algorithms
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
{
public:
virtual ~Algorithm() {}
/// \brief Interface for all crypto algorithms
/// \param checkSelfTestStatus determines whether the object can proceed if the self
/// tests have not been run or failed.
/// \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
/// this constructor throws SelfTestFailure if the self test hasn't been run or fails.
/// \details FIPS 140-2 compliance is disabled by default. It is only used by certain
/// versions of the library when the library is built as a DLL on Windows. Also see
/// CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h.
Algorithm(bool checkSelfTestStatus = true);
/// \brief Provides the name of this algorithm
/// \return the standard algorithm name
/// \details The standard algorithm name can be a name like <tt>AES</tt> or <tt>AES/GCM</tt>.
/// Some algorithms do not have standard names yet. For example, there is no standard
/// algorithm name for Shoup's ECIES.
/// \note AlgorithmName is not universally implemented yet.
virtual std::string AlgorithmName() const {return "unknown";}
/// \brief Retrieve the provider of this algorithm
/// \return the algorithm provider
/// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
/// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
/// usually indicate a specialized implementation using instructions from a higher
/// instruction set architecture (ISA). Future labels may include external hardware
/// like a hardware security module (HSM).
/// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
/// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
/// instead of ASM.
/// \details Algorithms which combine different instructions or ISAs provide the
/// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
/// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
/// \note Provider is not universally implemented yet.
/// \since Crypto++ 7.1
virtual std::string AlgorithmProvider() const {return "C++";}
};
/// \brief Interface for algorithms that take byte strings as keys
/// \sa FixedKeyLength(), VariableKeyLength(), SameKeyLengthAs(), SimpleKeyingInterfaceImpl()
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
{
public:
virtual ~SimpleKeyingInterface() {}
/// \brief Returns smallest valid key length
/// \returns the minimum key length, in bytes
virtual size_t MinKeyLength() const =0;
/// \brief Returns largest valid key length
/// \returns the maximum key length, in bytes
virtual size_t MaxKeyLength() const =0;
/// \brief Returns default key length
/// \returns the default key length, in bytes
virtual size_t DefaultKeyLength() const =0;
/// \brief Returns a valid key length for the algorithm
/// \param keylength the size of the key, in bytes
/// \returns the valid key length, in bytes
/// \details keylength is provided in bytes, not bits. If keylength is less than MIN_KEYLENGTH,
/// then the function returns MIN_KEYLENGTH. If keylength is greater than MAX_KEYLENGTH,
/// then the function returns MAX_KEYLENGTH. if If keylength is a multiple of KEYLENGTH_MULTIPLE,
/// then keylength is returned. Otherwise, the function returns a \a lower multiple of
/// KEYLENGTH_MULTIPLE.
virtual size_t GetValidKeyLength(size_t keylength) const =0;
/// \brief Returns whether keylength is a valid key length
/// \param keylength the requested keylength
/// \return true if keylength is valid, false otherwise
/// \details Internally the function calls GetValidKeyLength()
virtual bool IsValidKeyLength(size_t keylength) const
{return keylength == GetValidKeyLength(keylength);}
/// \brief Sets or reset the key of this object
/// \param key the key to use when keying the object
/// \param length the size of the key, in bytes
/// \param params additional initialization parameters to configure this object
virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms = g_nullNameValuePairs);
/// \brief Sets or reset the key of this object
/// \param key the key to use when keying the object
/// \param length the size of the key, in bytes
/// \param rounds the number of rounds to apply the transformation function,
/// if applicable
/// \details SetKeyWithRounds() calls SetKey() with a NameValuePairs
/// object that only specifies rounds. rounds is an integer parameter,
/// and <tt>-1</tt> means use the default number of rounds.
void SetKeyWithRounds(const byte *key, size_t length, int rounds);
/// \brief Sets or reset the key of this object
/// \param key the key to use when keying the object
/// \param length the size of the key, in bytes
/// \param iv the initialization vector to use when keying the object
/// \param ivLength the size of the iv, in bytes
/// \details SetKeyWithIV() calls SetKey() with a NameValuePairs
/// that only specifies IV. The IV is a byte buffer with size ivLength.
/// ivLength is an integer parameter, and <tt>-1</tt> means use IVSize().
void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
/// \brief Sets or reset the key of this object
/// \param key the key to use when keying the object
/// \param length the size of the key, in bytes
/// \param iv the initialization vector to use when keying the object
/// \details SetKeyWithIV() calls SetKey() with a NameValuePairs() object
/// that only specifies iv. iv is a byte buffer, and it must have
/// a size IVSize().
void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
{SetKeyWithIV(key, length, iv, IVSize());}
/// \brief Secure IVs requirements as enumerated values.
/// \details Provides secure IV requirements as a monotonically increasing enumerated values.
/// Requirements can be compared using less than (<) and greater than (>). For example,
/// <tt>UNIQUE_IV < RANDOM_IV</tt> and <tt>UNPREDICTABLE_RANDOM_IV > RANDOM_IV</tt>.
/// \details Objects that use SimpleKeyingInterface do not support an optional IV. That is,
/// an IV must be present or it must be absent. If you wish to support an optional IV then
/// provide two classes - one with an IV and one without an IV.
/// \sa IsResynchronizable(), CanUseRandomIVs(), CanUsePredictableIVs(), CanUseStructuredIVs()
enum IV_Requirement {
/// \brief The IV must be unique
UNIQUE_IV = 0,
/// \brief The IV must be random and possibly predictable
RANDOM_IV,
/// \brief The IV must be random and unpredictable
UNPREDICTABLE_RANDOM_IV,
/// \brief The IV is set by the object
INTERNALLY_GENERATED_IV,
/// \brief The object does not use an IV
NOT_RESYNCHRONIZABLE
};
/// \brief Minimal requirement for secure IVs
/// \return the secure IV requirement of the algorithm
virtual IV_Requirement IVRequirement() const =0;
/// \brief Determines if the object can be resynchronized
/// \return true if the object can be resynchronized (i.e. supports initialization vectors), false otherwise
/// \note If this function returns true, and no IV is passed to SetKey() and <tt>CanUseStructuredIVs()==true</tt>,
/// an IV of all 0's will be assumed.
bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
/// \brief Determines if the object can use random IVs
/// \return true if the object can use random IVs (in addition to ones returned by GetNextIV), false otherwise
bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
/// \brief Determines if the object can use random but possibly predictable IVs
/// \return true if the object can use random but possibly predictable IVs (in addition to ones returned by
/// GetNextIV), false otherwise
bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
/// \brief Determines if the object can use structured IVs
/// \returns true if the object can use structured IVs, false otherwise
/// \details CanUseStructuredIVs() indicates whether the object can use structured IVs; for example a counter
/// (in addition to ones returned by GetNextIV).
bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
/// \brief Returns length of the IV accepted by this object
/// \return the size of an IV, in bytes
/// \throws NotImplemented() if the object does not support resynchronization
/// \details The default implementation throws NotImplemented
virtual unsigned int IVSize() const
{throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
/// \brief Provides the default size of an IV
/// \return default length of IVs accepted by this object, in bytes
unsigned int DefaultIVLength() const {return IVSize();}
/// \brief Provides the minimum size of an IV
/// \return minimal length of IVs accepted by this object, in bytes
/// \throws NotImplemented() if the object does not support resynchronization
virtual unsigned int MinIVLength() const {return IVSize();}
/// \brief Provides the maximum size of an IV
/// \return maximal length of IVs accepted by this object, in bytes
/// \throws NotImplemented() if the object does not support resynchronization
virtual unsigned int MaxIVLength() const {return IVSize();}
/// \brief Resynchronize with an IV
/// \param iv the initialization vector
/// \param ivLength the size of the initialization vector, in bytes
/// \details Resynchronize() resynchronizes with an IV provided by the caller. <tt>ivLength=-1</tt> means use IVSize().
/// \throws NotImplemented() if the object does not support resynchronization
virtual void Resynchronize(const byte *iv, int ivLength=-1) {
CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength);
throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");
}
/// \brief Retrieves a secure IV for the next message
/// \param rng a RandomNumberGenerator to produce keying material
/// \param iv a block of bytes to receive the IV
/// \details The IV must be at least IVSize() in length.
/// \details This method should be called after you finish encrypting one message and are ready
/// to start the next one. After calling it, you must call SetKey() or Resynchronize().
/// before using this object again.
/// \details Internally, the base class implementation calls RandomNumberGenerator's GenerateBlock()
/// \note This method is not implemented on decryption objects.
virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
protected:
/// \brief Returns the base class Algorithm
/// \return the base class Algorithm
virtual const Algorithm & GetAlgorithm() const =0;
/// \brief Sets the key for this object without performing parameter validation
/// \param key a byte buffer used to key the cipher
/// \param length the length of the byte buffer
/// \param params additional parameters passed as NameValuePairs
/// \details key must be at least DEFAULT_KEYLENGTH in length.
virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms) =0;
/// \brief Validates the key length
/// \param length the size of the keying material, in bytes
/// \throws InvalidKeyLength if the key length is invalid
void ThrowIfInvalidKeyLength(size_t length);
/// \brief Validates the object
/// \throws InvalidArgument if the IV is present
/// \details Internally, the default implementation calls IsResynchronizable() and throws
/// InvalidArgument if the function returns true.
/// \note called when no IV is passed
void ThrowIfResynchronizable();
/// \brief Validates the IV
/// \param iv the IV with a length of IVSize, in bytes
/// \throws InvalidArgument on failure
/// \details Internally, the default implementation checks the iv. If iv is not NULL or nullptr,
/// then the function succeeds. If iv is NULL, then IVRequirement is checked against
/// UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then
/// then the function succeeds. Otherwise, an exception is thrown.
void ThrowIfInvalidIV(const byte *iv);
/// \brief Validates the IV length
/// \param length the size of an IV, in bytes
/// \throws InvalidArgument if the IV length is invalid
size_t ThrowIfInvalidIVLength(int length);
/// \brief Retrieves and validates the IV
/// \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter
/// \param size the length of the IV, in bytes
/// \return a pointer to the first byte of the IV
/// \throws InvalidArgument if the number of rounds are invalid
const byte * GetIVAndThrowIfInvalid(const NameValuePairs ¶ms, size_t &size);
/// \brief Validates the key length
/// \param length the size of the keying material, in bytes
inline void AssertValidKeyLength(size_t length) const
{CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));}
};
/// \brief Interface for the data processing part of block ciphers
/// \details Classes derived from BlockTransformation are block ciphers
/// in ECB mode (for example the DES::Encryption class), which are stateless.
/// These classes should not be used directly, but only in combination with
/// a mode class (see CipherModeDocumentation in modes.h).
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
{
public:
virtual ~BlockTransformation() {}
/// \brief Encrypt or decrypt a block
/// \param inBlock the input message before processing
/// \param outBlock the output message after processing
/// \param xorBlock an optional XOR mask
/// \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock.
/// \details The size of the block is determined by the block cipher and its documentation. Use
/// BLOCKSIZE at compile time, or BlockSize() at runtime.
/// \note The message can be transformed in-place, or the buffers must \a not overlap
/// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
/// \brief Encrypt or decrypt a block
/// \param inBlock the input message before processing
/// \param outBlock the output message after processing
/// \details ProcessBlock encrypts or decrypts inBlock and write to outBlock.
/// \details The size of the block is determined by the block cipher and its documentation.
/// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
/// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
/// \note The message can be transformed in-place, or the buffers must \a not overlap
void ProcessBlock(const byte *inBlock, byte *outBlock) const
{ProcessAndXorBlock(inBlock, NULLPTR, outBlock);}
/// \brief Encrypt or decrypt a block in place
/// \param inoutBlock the input message before processing
/// \details ProcessBlock encrypts or decrypts inoutBlock in-place.
/// \details The size of the block is determined by the block cipher and its documentation.
/// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
/// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
void ProcessBlock(byte *inoutBlock) const
{ProcessAndXorBlock(inoutBlock, NULLPTR, inoutBlock);}
/// Provides the block size of the cipher
/// \return the block size of the cipher, in bytes
virtual unsigned int BlockSize() const =0;
/// \brief Provides input and output data alignment for optimal performance.
/// \return the input data alignment that provides optimal performance
/// \sa GetAlignment() and OptimalBlockSize()
virtual unsigned int OptimalDataAlignment() const;
/// \brief Determines if the transformation is a permutation
/// \returns true if this is a permutation (i.e. there is an inverse transformation)
virtual bool IsPermutation() const {return true;}
/// \brief Determines if the cipher is being operated in its forward direction
/// \returns true if DIR is ENCRYPTION, false otherwise
/// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
virtual bool IsForwardTransformation() const =0;
/// \brief Determines the number of blocks that can be processed in parallel
/// \return the number of blocks that can be processed in parallel, for bit-slicing implementations
/// \details Bit-slicing is often used to improve throughput and minimize timing attacks.
virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
/// \brief Bit flags that control AdvancedProcessBlocks() behavior
enum FlagsForAdvancedProcessBlocks {
/// \brief inBlock is a counter
BT_InBlockIsCounter=1,
/// \brief should not modify block pointers
BT_DontIncrementInOutPointers=2,
/// \brief Xor inputs before transformation
BT_XorInput=4,
/// \brief perform the transformation in reverse
BT_ReverseDirection=8,
/// \brief Allow parallel transformations
BT_AllowParallel=16};
/// \brief Encrypt and xor multiple blocks using additional flags
/// \param inBlocks the input message before processing
/// \param xorBlocks an optional XOR mask
/// \param outBlocks the output message after processing
/// \param length the size of the blocks, in bytes
/// \param flags additional flags to control processing
/// \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags.
/// \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified.
virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
/// \brief Provides the direction of the cipher
/// \return ENCRYPTION if IsForwardTransformation() is true, DECRYPTION otherwise
/// \sa IsForwardTransformation(), IsPermutation()
inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
};
/// \brief Interface for the data processing portion of stream ciphers
/// \sa StreamTransformationFilter()
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
{
public:
virtual ~StreamTransformation() {}
/// \brief Provides a reference to this object
/// \return A reference to this object
/// \details Useful for passing a temporary object to a function that takes a non-const reference
StreamTransformation& Ref() {return *this;}
/// \brief Provides the mandatory block size of the cipher
/// \return The block size of the cipher if input must be processed in blocks, 1 otherwise
/// \details Stream ciphers and some block ciphers modes of operation return 1. Modes that
/// return 1 must be able to process a single byte at a time, like counter mode. If a
/// mode of operation or block cipher cannot stream then it must not return 1.
/// \details When filters operate the mode or cipher, ProcessData will be called with a
/// string of bytes that is determined by MandatoryBlockSize and OptimalBlockSize. When a
/// policy is set, like 16-byte strings for a 16-byte block cipher, the filter will buffer
/// bytes until the specified number of bytes is available to the object.
/// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
virtual unsigned int MandatoryBlockSize() const {return 1;}
/// \brief Provides the input block size most efficient for this cipher
/// \return The input block size that is most efficient for the cipher
/// \details The base class implementation returns MandatoryBlockSize().
/// \note Optimal input length is
/// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>.
virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
/// \brief Provides the number of bytes used in the current block when processing at optimal block size.
/// \return the number of bytes used in the current block when processing at the optimal block size
virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
/// \brief Provides input and output data alignment for optimal performance
/// \return the input data alignment that provides optimal performance
/// \sa GetAlignment() and OptimalBlockSize()
virtual unsigned int OptimalDataAlignment() const;
/// \brief Encrypt or decrypt an array of bytes
/// \param outString the output byte buffer
/// \param inString the input byte buffer
/// \param length the size of the input and output byte buffers, in bytes
/// \details ProcessData is called with a string of bytes whose size depends on MandatoryBlockSize.
/// Either <tt>inString == outString</tt>, or they must not overlap.
/// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
/// \brief Encrypt or decrypt the last block of data
/// \param outString the output byte buffer
/// \param outLength the size of the output byte buffer, in bytes
/// \param inString the input byte buffer
/// \param inLength the size of the input byte buffer, in bytes
/// \returns the number of bytes used in outString
/// \details ProcessLastBlock is used when the last block of data is special and requires handling
/// by the cipher. The current implementation provides an output buffer with a size
/// <tt>inLength+2*MandatoryBlockSize()</tt>. The return value allows the cipher to expand cipher
/// text during encryption or shrink plain text during decryption.
/// \details This member function is used by CBC-CTS and OCB modes.
/// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
/// \brief Provides the size of the last block
/// \returns the minimum size of the last block
/// \details MinLastBlockSize() returns the minimum size of the last block. 0 indicates the last
/// block is not special.
/// \details MandatoryBlockSize() enlists one of two behaviors. First, if MandatoryBlockSize()
/// returns 1, then the cipher can be streamed and ProcessData() is called with the tail bytes.
/// Second, if MandatoryBlockSize() returns non-0, then the string of bytes is padded to
/// MandatoryBlockSize() according to the padding mode. Then, ProcessData() is called with the
/// padded string of bytes.
/// \details Some authenticated encryption modes are not expressed well with MandatoryBlockSize()
/// and MinLastBlockSize(). For example, AES/OCB uses 16-byte blocks (MandatoryBlockSize = 16)
/// and the last block requires special processing (MinLastBlockSize = 0). However, 0 is a valid
/// last block size for OCB and the special processing is custom padding, and not standard PKCS
/// padding. In response an unambiguous IsLastBlockSpecial() was added.
/// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
virtual unsigned int MinLastBlockSize() const {return 0;}
/// \brief Determines if the last block receives special processing
/// \returns true if the last block reveives special processing, false otherwise.
/// \details Some authenticated encryption modes are not expressed well with
/// MandatoryBlockSize() and MinLastBlockSize(). For example, AES/OCB uses
/// 16-byte blocks (MandatoryBlockSize = 16) and the last block requires special processing
/// (MinLastBlockSize = 0). However, 0 is a valid last block size for OCB and the special