forked from weidai11/cryptopp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcryptlib.h
2473 lines (2108 loc) · 120 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 - written and placed in the public domain by Wei Dai
//! \file
//! Abstract base classes that provide a uniform interface to this library.
/*! \mainpage Crypto++ Library 5.6.3 API Reference
<dl>
<dt>Abstract Base Classes<dd>
cryptlib.h
<dt>Authenticated Encryption<dd>
AuthenticatedSymmetricCipherDocumentation
<dt>Symmetric Ciphers<dd>
SymmetricCipherDocumentation
<dt>Hash Functions<dd>
SHA1, SHA224, SHA256, SHA384, SHA512, Tiger, Whirlpool, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, Weak1::MD2, Weak1::MD4, Weak1::MD5
<dt>Non-Cryptographic Checksums<dd>
CRC32, Adler32
<dt>Message Authentication Codes<dd>
VMAC, HMAC, CBC_MAC, CMAC, DMAC, TTMAC, GCM (GMAC)
<dt>Random Number Generators<dd>
NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG, DefaultAutoSeededRNG
<dt>Key Derivation<dd>
HKDF
<dt>Password-based Cryptography<dd>
PasswordBasedKeyDerivationFunction
<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, MQV, ECDH, ECMQV, 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, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource
<dt>Output Sink Classes<dd>
StringSinkTemplate, ArraySink, FileSink, SocketSink, WindowsPipeSink, RandomNumberSink
<dt>Filter Wrappers<dd>
StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter
<dt>Binary to Text Encoders and Decoders<dd>
HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base32Encoder, Base32Decoder
<dt>Wrappers for OS features<dd>
Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer
<dt>FIPS 140 related<dd>
fips140.h
</dl>
In the DLL version of Crypto++, only the following implementation class are available.
<dl>
<dt>Block Ciphers<dd>
AES, DES_EDE2, DES_EDE3, SKIPJACK
<dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
ECB_Mode\<BC\>, CTR_Mode\<BC\>, CBC_Mode\<BC\>, CFB_FIPS_Mode\<BC\>, OFB_Mode\<BC\>, 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 are 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"
#if CRYPTOPP_MSC_VERSION
# pragma warning(push)
# pragma warning(disable: 4127 4189 4702)
#endif
NAMESPACE_BEGIN(CryptoPP)
// forward declarations
class Integer;
class RandomNumberGenerator;
class BufferedTransformation;
//! \brief Specifies a direction for a cipher to operate
enum CipherDir {ENCRYPTION, DECRYPTION};
//! \brief Represents infinite time
const unsigned long INFINITE_TIME = ULONG_MAX;
// VC60 workaround: using enums as template parameters causes problems
//! \brief Converts a typename to an enumerated value
template <typename ENUM_TYPE, int VALUE>
struct EnumToType
{
static ENUM_TYPE ToEnum() {return (ENUM_TYPE)VALUE;}
};
//! \brief Provides the byte ordering
enum ByteOrder {LITTLE_ENDIAN_ORDER = 0, BIG_ENDIAN_ORDER = 1};
//! \typedef Provides a constant for \p LittleEndian
typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian;
//! \typedef Provides a constant for \p BigEndian
typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian;
//! \class Exception
//! \brief Base class for all exceptions thrown by Crypto++
class CRYPTOPP_DLL Exception : public std::exception
{
public:
//! error types
enum ErrorType {
//! \brief A method was called which was not implemented
NOT_IMPLEMENTED,
//! \brief An invalid argument was detected
INVALID_ARGUMENT,
//! \brief \p 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 belong to any of the above categories
OTHER_ERROR
};
//! \brief Construct a new \p Exception
explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
virtual ~Exception() throw() {}
//! \brief Retrieves a C-string describing the exception
const char *what() const throw() {return (m_what.c_str());}
//! \brief Retrieves a \p string describing the exception
const std::string &GetWhat() const {return m_what;}
//! \brief Sets the error \p 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:
OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
: Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
~OS_Error() throw() {}
//! \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;
};
//! \class DecodingResult
//! \brief Returns a decoding results
struct CRYPTOPP_DLL DecodingResult
{
//! \brief Constructs a \p DecodingResult
explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
//! \brief Constructs a \p DecodingResult
explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
bool isValidCoding;
size_t messageLength;
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
operator size_t() const {return isValidCoding ? messageLength : 0;}
#endif
};
//! \class NameValuePairs
//! \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 \p 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
//! \p ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object.
class CRYPTOPP_NO_VTABLE NameValuePairs
{
public:
virtual ~NameValuePairs() {}
//! \class ValueTypeMismatch
//! \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
//! \returns the C++ mangled name of the type
const std::type_info & GetStoredTypeInfo() const {return m_stored;}
//! \brief Provides the retrieveing type
//! \returns 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, returns true if the name exists
//! \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 \p true if the value was retrieved, \p false otherwise
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
//! \returns the object or value
template <class T>
T GetValueWithDefault(const char *name, T defaultValue) const
{
GetValue(name, defaultValue);
return defaultValue;
}
//! \brief Get a list of value names that can be retrieved
//! \returns 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
//! \details 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)
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
//! \returns the value retrieved or the default value
CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int 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 \p ThrowIfTypeMismatch() effectively performs a type safety check.
//! \p stored and \p retrieving are C++ mangled names for the type.
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 \p GetRequiredParameter() throws \p InvalidArgument if the \p name
//! is not present or not of the expected type \p T.
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 \p GetRequiredParameter() throws \p InvalidArgument if the \p name
//! is not present or not of the expected type \p T.
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 + "'");
}
//! to be implemented by derived classes, users should use one of the above functions instead
CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
};
//! \brief Namespace containing value name definitions
/*! \details value names, types and semantics:
ThisObject:ClassName (ClassName, copy of this object or a subobject)
ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
*/
DOCUMENTED_NAMESPACE_BEGIN(Name)
// more names defined in argnames.h
DOCUMENTED_NAMESPACE_END
//! \brief Namespace containing weak and wounded algorithms
DOCUMENTED_NAMESPACE_BEGIN(Weak)
// weak and wounded algorithms
DOCUMENTED_NAMESPACE_END
//! \brief An empty set of name-value pairs
extern CRYPTOPP_DLL const NameValuePairs &g_nullNameValuePairs;
// ********************************************************
//! \class Clonable
//! \brief Interface for cloning objects
//! \note this is \a not implemented by most classes
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
{
public:
virtual ~Clonable() {}
//! \brief Copies \p this object
//! \returns a copy of this object
//! \throws NotImplemented
//! \note this is \a not implemented by most classes
virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
};
//! \class Algorithm
//! \brief Interface for all crypto algorithms
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
{
public:
//! \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
//! \p CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in \headerfile config.h.
Algorithm(bool checkSelfTestStatus = true);
//! \brief Provides the name of this algorithm
//! \returns the standard algorithm name
//! \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms
//! do not have standard names yet. For example, there is no standard algorithm name for
//! Shoup's \p ECIES.
//! \note \p AlgorithmName is not universally implemented yet
virtual std::string AlgorithmName() const {return "unknown";}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~Algorithm() {}
#endif
};
//! \class SimpleKeyingInterface
//! Interface for algorithms that take byte strings as keys
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
{
public:
virtual ~SimpleKeyingInterface() {}
//! \brief Returns smallest valid key length in bytes
virtual size_t MinKeyLength() const =0;
//! \brief Returns largest valid key length in bytes
virtual size_t MaxKeyLength() const =0;
//! \brief Returns default (recommended) key length in bytes
virtual size_t DefaultKeyLength() const =0;
//! \brief
//! \returns the smallest valid key length in bytes that is greater than or equal to <tt>min(n, GetMaxKeyLength())</tt>
virtual size_t GetValidKeyLength(size_t n) const =0;
//! \brief Returns whether \p keylength is a valid key length
//! \details Internally the function calls \p 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 that cannot be passed
//! directly through the constructor
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 \p SetKeyWithRounds calls \p SetKey with an \p NameValuePairs
//! object that just specifies \p rounds. \p 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 intiialization vector to use when keying the object
//! \param ivLength the size of the iv, in bytes
//! \details \p SetKeyWithIV calls \p SetKey with an \p NameValuePairs object
//! that just specifies \p iv. \p iv is a \p byte array with size \p ivLength.
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 intiialization vector to use when keying the object
//! \details \p SetKeyWithIV calls \p SetKey with an \p NameValuePairs object
//! that just specifies \p iv. \p iv is a \p byte array, and it must have
//! a size \p IVSize.
void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
{SetKeyWithIV(key, length, iv, IVSize());}
//! \brief Provides IV requirements as an enumerated value.
enum IV_Requirement {
//! \brief The IV must be unique
UNIQUE_IV = 0,
//! \brief The IV must be random
RANDOM_IV,
//! \brief The IV must be 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
};
//! returns the minimal requirement for secure IVs
virtual IV_Requirement IVRequirement() const =0;
//! returns whether the object can be resynchronized (i.e. supports initialization vectors)
/*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */
bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
//! returns whether the object can use random IVs (in addition to ones returned by GetNextIV)
bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
//! returns whether the object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV)
bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
//! returns 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
//! \details The default implementation throws \p NotImplemented
virtual unsigned int IVSize() const
{throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
//! returns default length of IVs accepted by this object
unsigned int DefaultIVLength() const {return IVSize();}
//! returns minimal length of IVs accepted by this object
virtual unsigned int MinIVLength() const {return IVSize();}
//! returns maximal length of IVs accepted by this object
virtual unsigned int MaxIVLength() const {return IVSize();}
//! resynchronize with an IV. ivLength=-1 means use IVSize()
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 Gets a secure IV for the next message
//! \param rng a \p RandomNumberGenerator to produce keying material
//! \param iv a block of bytes to receive the IV
//! \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 \p SetKey() or \p Resynchronize()
//! before using this object again.
//! \details \p key must be at least \p IVSize() in length.
//! \note This method is not implemented on decryption objects.
virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
protected:
//! \brief Returns the base class \p Algorithm
//! \returns the base class \p Algorithm
virtual const Algorithm & GetAlgorithm() const =0;
//! \brief Sets the key for this object without performing parameter validation
//! \param key a byte array used to key the cipher
//! \param length the length of the byte array
//! \param params additional parameters passed as \p NameValuePairs
//! \details \p key must be at least \p 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 \p IsResynchronizable() and throws
//! \p InvalidArgument if the function returns \p true.
//! \note called when no IV is passed
void ThrowIfResynchronizable();
//! \brief Validates the IV
//! \param iv the IV with a length of \p IVSize, in bytes
//! \throws InvalidArgument on failure
//! \details Internally, the default implementation checks the \p iv. If \p iv is not \p NULL,
//! then the function succeeds. If \p iv is \p NULL, then \p IVRequirement is checked against
//! \p UNPREDICTABLE_RANDOM_IV. If \p IVRequirement is \p 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 the IV, in bytes
//! \throws InvalidArgument if the number of \p rounds are invalid
size_t ThrowIfInvalidIVLength(int length);
//! \brief retrieves and validates the IV
//! \param params \p NameValuePairs with the IV supplied as a \p ConstByteArrayParameter
//! \param size the length of the IV, in bytes
//! \returns a pointer to the first byte of the \p IV
//! \throws InvalidArgument if the number of \p 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); assert(IsValidKeyLength(length));}
};
//! \brief Interface for the data processing part of block ciphers
/*! 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:
//! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock
virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
//! encrypt or decrypt one block
/*! \pre size of inBlock and outBlock == BlockSize() */
void ProcessBlock(const byte *inBlock, byte *outBlock) const
{ProcessAndXorBlock(inBlock, NULL, outBlock);}
//! encrypt or decrypt one block in place
void ProcessBlock(byte *inoutBlock) const
{ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);}
//! block size of the cipher in bytes
virtual unsigned int BlockSize() const =0;
//! returns how inputs and outputs should be aligned for optimal performance
virtual unsigned int OptimalDataAlignment() const;
//! returns true if this is a permutation (i.e. there is an inverse transformation)
virtual bool IsPermutation() const {return true;}
//! returns true if this is an encryption object
virtual bool IsForwardTransformation() const =0;
//! return number of blocks that can be processed in parallel, for bit-slicing implementations
virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
enum {BT_InBlockIsCounter=1, BT_DontIncrementInOutPointers=2, BT_XorInput=4, BT_ReverseDirection=8, BT_AllowParallel=16} FlagsForAdvancedProcessBlocks;
//! encrypt and xor blocks according to flags (see FlagsForAdvancedProcessBlocks)
/*! /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;
inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~BlockTransformation() {}
#endif
};
//! \brief Interface for the data processing portion of stream ciphers
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
{
public:
//! \brief 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 returns block size, if input must be processed in blocks, otherwise 1
virtual unsigned int MandatoryBlockSize() const {return 1;}
//! \brief returns the input block size that is most efficient for this cipher
/*! \note optimal input length is n * OptimalBlockSize() - GetOptimalBlockSizeUsed() for any n > 0 */
virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
//! \brief returns how much of the current block is used up
virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
//! \brief returns how input should be aligned for optimal performance
virtual unsigned int OptimalDataAlignment() const;
//! \brief encrypt or decrypt an array of bytes of specified length
//! \note either inString == outString, or they don't overlap
virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
//! \brief Encrypt or decrypt the last block of data for ciphers where the last block of data is special
//! For now the only use of this function is for CBC-CTS mode.
virtual void ProcessLastBlock(byte *outString, const byte *inString, size_t length);
//! returns the minimum size of the last block, 0 indicating the last block is not special
virtual unsigned int MinLastBlockSize() const {return 0;}
//! same as ProcessData(inoutString, inoutString, length)
inline void ProcessString(byte *inoutString, size_t length)
{ProcessData(inoutString, inoutString, length);}
//! same as ProcessData(outString, inString, length)
inline void ProcessString(byte *outString, const byte *inString, size_t length)
{ProcessData(outString, inString, length);}
//! implemented as {ProcessData(&input, &input, 1); return input;}
inline byte ProcessByte(byte input)
{ProcessData(&input, &input, 1); return input;}
//! returns whether this cipher supports random access
virtual bool IsRandomAccess() const =0;
//! for random access ciphers, seek to an absolute position
virtual void Seek(lword n)
{
CRYPTOPP_UNUSED(n);
assert(!IsRandomAccess());
throw NotImplemented("StreamTransformation: this object doesn't support random access");
}
//! returns whether this transformation is self-inverting (e.g. xor with a keystream)
virtual bool IsSelfInverting() const =0;
//! returns whether this is an encryption object
virtual bool IsForwardTransformation() const =0;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~StreamTransformation() {}
#endif
};
//! \brief Interface for hash functions and data processing part of MACs
/*! HashTransformation objects are stateful. They are created in an initial state,
change state as Update() is called, and return to the initial
state when Final() is called. This interface allows a large message to
be hashed in pieces by calling Update() on each piece followed by
calling Final().
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
{
public:
//! \brief Return a reference to this object
//! \details Useful for passing a temporary object to a function that takes a non-const reference
HashTransformation& Ref() {return *this;}
//! process more input
virtual void Update(const byte *input, size_t length) =0;
//! request space to write input into
virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULL;}
//! compute hash for current message, then restart for a new message
/*! \pre size of digest == DigestSize(). */
virtual void Final(byte *digest)
{TruncatedFinal(digest, DigestSize());}
//! discard the current state, and restart with a new message
virtual void Restart()
{TruncatedFinal(NULL, 0);}
//! size of the hash/digest/MAC returned by Final()
virtual unsigned int DigestSize() const =0;
//! same as DigestSize()
unsigned int TagSize() const {return DigestSize();}
//! block size of underlying compression function, or 0 if not block based
virtual unsigned int BlockSize() const {return 0;}
//! input to Update() should have length a multiple of this for optimal speed
virtual unsigned int OptimalBlockSize() const {return 1;}
//! returns how input should be aligned for optimal performance
virtual unsigned int OptimalDataAlignment() const;
//! use this if your input is in one piece and you don't want to call Update() and Final() separately
virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
{Update(input, length); Final(digest);}
//! verify that digest is a valid digest for the current message, then reinitialize the object
/*! Default implementation is to call Final() and do a bitwise comparison
between its output and digest. */
virtual bool Verify(const byte *digest)
{return TruncatedVerify(digest, DigestSize());}
//! use this if your input is in one piece and you don't want to call Update() and Verify() separately
virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
{Update(input, length); return Verify(digest);}
//! truncated version of Final()
virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
//! truncated version of CalculateDigest()
virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
{Update(input, length); TruncatedFinal(digest, digestSize);}
//! truncated version of Verify()
virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
//! truncated version of VerifyDigest()
virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
{Update(input, length); return TruncatedVerify(digest, digestLength);}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~HashTransformation() {}
#endif
protected:
void ThrowIfInvalidTruncatedSize(size_t size) const;
};
typedef HashTransformation HashFunction;
//! \brief Interface for one direction (encryption or decryption) of a block cipher
/*! \note These objects usually should not be used directly. See BlockTransformation for more details. */
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
{
protected:
const Algorithm & GetAlgorithm() const {return *this;}
};
//! \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
{
protected:
const Algorithm & GetAlgorithm() const {return *this;}
};
//! \brief Interface for message authentication codes
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
{
protected:
const Algorithm & GetAlgorithm() const {return *this;}
};
//! \brief Interface for for one direction (encryption or decryption) of a stream cipher or block cipher mode with authentication
/*! The StreamTransformation part of this interface is used to encrypt/decrypt the data, and the MessageAuthenticationCode part of this
interface is used to input additional authenticated data (AAD, which is MAC'ed but not encrypted), and to generate/verify the MAC. */
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
{
public:
//! this indicates that a member function was called in the wrong state, for example trying to encrypt a message before having set the key or IV
class BadState : public Exception
{
public:
explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
};
//! the maximum length of AAD that can be input before the encrypted data
virtual lword MaxHeaderLength() const =0;
//! the maximum length of encrypted data
virtual lword MaxMessageLength() const =0;
//! the maximum length of AAD that can be input after the encrypted data
virtual lword MaxFooterLength() const {return 0;}
//! if this function returns true, SpecifyDataLengths() must be called before attempting to input data
/*! This is the case for some schemes, such as CCM. */
virtual bool NeedsPrespecifiedDataLengths() const {return false;}
//! this function only needs to be called if NeedsPrespecifiedDataLengths() returns true
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
//! encrypt and generate MAC in one call. will truncate MAC if macSize < TagSize()
virtual void EncryptAndAuthenticate(byte *ciphertext, byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *message, size_t messageLength);
//! decrypt and verify MAC in one call, returning true iff MAC is valid. will assume MAC is truncated if macLength < TagSize()
virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macLength, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength);
// redeclare this to avoid compiler ambiguity errors
virtual std::string AlgorithmName() const =0;
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~AuthenticatedSymmetricCipher() {}
#endif
protected:
const Algorithm & GetAlgorithm() const
{return *static_cast<const MessageAuthenticationCode *>(this);}
virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
{CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);}
};
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
typedef SymmetricCipher StreamCipher;
#endif
//! \class RandomNumberGenerator
//! \brief Interface for random number generators
//! \details The library provides a number of random number generators, from software based to hardware based generators.
//! \details All return values are uniformly distributed over the range specified.
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
{
public:
//! \brief Update RNG state with additional unpredictable values
//! \param input the entropy to add to the generator
//! \param length the size of the input buffer
//! \throws NotImplemented
//! \details A generator may or may not accept additional entropy. Call \p CanIncorporateEntropy to test for the
//! ability to use additional entropy.
//! \details If a derived class does not override \p IncorporateEntropy, then the base class throws
//! \p NotImplemented.
virtual void IncorporateEntropy(const byte *input, size_t length)
{
CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
}
//! \brief Determines if a generator can accept additional entropy
//! \returns true if IncorporateEntropy is implemented
virtual bool CanIncorporateEntropy() const {return false;}
//! \brief Generate new random byte and return it
//! \details default implementation is to call GenerateBlock() with one byte
virtual byte GenerateByte();
//! \brief Generate new random bit and return it
//! \returns a random bit
//! \details The default implementation calls GenerateByte() and return its lowest bit.
virtual unsigned int GenerateBit();
//! \brief Generate a random 32 bit word in the range min to max, inclusive
//! \param min the lower bound of the range
//! \param max the upper bound of the range
//! \returns a random 32-bit word
//! \details The default implementation calls \p Crop on the difference between \p max and
//! \p min, and then returns the result added to \p min.
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffL);
//! \brief Generate random array of bytes
//! \param output the byte buffer
//! \param size the length of the buffer, in bytes
//! \note A derived generator \a must override either \p GenerateBlock or
//! \p GenerateIntoBufferedTransformation. They can override both, or have one call the other.
virtual void GenerateBlock(byte *output, size_t size);
//! \brief Generate random bytes into a BufferedTransformation
//! \param target the BufferedTransformation object which receives the bytes
//! \param channel the channel on which the bytes should be pumped
//! \param length the number of bytes to generate
//! \details The default implementation calls \p GenerateBlock() and pumps the result into
//! the \p DEFAULT_CHANNEL of the target.
//! \note A derived generator \a must override either \p GenerateBlock or
//! \p GenerateIntoBufferedTransformation. They can override both, or have one call the other.
virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
//! \brief Generate and discard \p n bytes
//! \param n the number of bytes to generate and discard
virtual void DiscardBytes(size_t n);
//! \brief Randomly shuffle the specified array
//! \param begin an iterator to the first element in the array
//! \param end an iterator beyond the last element in the array
//! \details The resulting permutation is uniformly distributed.
template <class IT> void Shuffle(IT begin, IT end)
{
// TODO: What happens if there are more than 2^32 elements?
for (; begin != end; ++begin)
std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1));
}
#ifndef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY_562
virtual ~RandomNumberGenerator() {}
#endif
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
byte GetByte() {return GenerateByte();}
unsigned int GetBit() {return GenerateBit();}
word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);}
word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);}
void GetBlock(byte *output, size_t size) {GenerateBlock(output, size);}
#endif
};
//! returns a reference that can be passed to functions that ask for a RNG but doesn't actually use it
CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
//! \brief Interface for checking device state
//! \details Generally speaking, this class attempts to provide four states: (1) not available/not present,
//! (2) available/present, (3) offline/not ready, and (4) online/ready.
//! If a device is Available, then it generally means its present at the time of the call. For example,
//! a 2012 Ivy Bridge processor will return \a Available for RDRAND, and a Broadwell processor will return
//! \a Available for and RDSEED.
//! \details If a device is Not Available, then it could be missing. For example, RDRAND and RDSEED are not
//! present on a 2000 era X86 CPU, so it should never be Available. Or a Smartcard or YubiKey may not be
//! plugged into a computer.
//! \details If a device is Ready, then it can service requests at the time of the call. For example, a
//! 2012 Ivy Bridge processor will return \a Ready for RDRAND, and a Broadwell processor will return
//! \a Ready for and RDSEED.
//! \details If a device is Not Ready, then it could uninitialized or locked. For example, a Smartcard or YubiKey
//! may be present but unitiialized or locked. The device may be waiting on a driver to be installed,
//! may be waiting to be intialized, or may be waiting for a PIN or Passcode to unlock it, etc.
//! \details Ready should always follow Available; however, the converse is not true. That is, a device that
//! is Not Ready does not mean that its Not Available. Not Ready only indicates the device is offline
//! at the time of the call.
//! \details A not-so-apparent use case is a software implementation. For example, you can have a Crypto++
//! wrapper around Microsoft's CryptoNG or Apple's CommonCrypto for FIPS 140-2 validated cryptography.
//! The \p DeviceState could provide the standard interface to query the relevant Crypto++ implementation
//! for the feature.
class CRYPTOPP_NO_VTABLE DeviceState
{
public:
//! \enum State
//! \brief Enumeration of potential device states.
//! \details The library reserves the lower 8 bits. Derived classes are free to use the 24 unallocated bits.
enum State {
//! \brief the device is available or present
AVAILABLE = 1,
//! \brief the device is available or present
PRESENT = 1,
//! \brief the device is ready or online
READY = 2,
//! \brief the device is ready or online
ONLINE = 2,
//! \brief mask for Available and Ready bits
AR_MASK = 0x3,
//! \brief mask for bits reserved by the library