Security Scol plugin
cryptlib.h
Go to the documentation of this file.
1// cryptlib.h - originally written and placed in the public domain by Wei Dai
2
5
102#ifndef CRYPTOPP_CRYPTLIB_H
103#define CRYPTOPP_CRYPTLIB_H
104
105#include "config.h"
106#include "stdcpp.h"
107#include "trap.h"
108
109#if CRYPTOPP_MSC_VERSION
110# pragma warning(push)
111# pragma warning(disable: 4127 4189 4505 4702)
112#endif
113
114NAMESPACE_BEGIN(CryptoPP)
115
116// forward declarations
117class Integer;
120
128
130const unsigned long INFINITE_TIME = ULONG_MAX;
131
132// VC60 workaround: using enums as template parameters causes problems
134template <typename ENUM_TYPE, int VALUE>
136{
137 static ENUM_TYPE ToEnum() {return static_cast<ENUM_TYPE>(VALUE);}
138};
139
148
153
158class CRYPTOPP_DLL Exception : public std::exception
159{
160public:
179
180 virtual ~Exception() throw() {}
181
183 explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
184
186 const char *what() const throw() {return (m_what.c_str());}
188 const std::string &GetWhat() const {return m_what;}
190 void SetWhat(const std::string &s) {m_what = s;}
192 ErrorType GetErrorType() const {return m_errorType;}
194 void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
195
196private:
197 ErrorType m_errorType;
198 std::string m_what;
199};
200
202class CRYPTOPP_DLL InvalidArgument : public Exception
203{
204public:
208 explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
209};
210
212class CRYPTOPP_DLL InvalidDataFormat : public Exception
213{
214public:
218 explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
219};
220
222class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
223{
224public:
228 explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
229};
230
232class CRYPTOPP_DLL NotImplemented : public Exception
233{
234public:
238 explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
239};
240
242class CRYPTOPP_DLL CannotFlush : public Exception
243{
244public:
248 explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
249};
250
252class CRYPTOPP_DLL OS_Error : public Exception
253{
254public:
255 virtual ~OS_Error() throw() {}
256
263 OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
264 : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
265
267 const std::string & GetOperation() const {return m_operation;}
269 int GetErrorCode() const {return m_errorCode;}
270
271protected:
272 std::string m_operation;
273 int m_errorCode;
274};
275
277struct CRYPTOPP_DLL DecodingResult
278{
282 explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
286 explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
287
292 bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
298 bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
299
304};
305
322{
323public:
324 virtual ~NameValuePairs() {}
325
329 class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
330 {
331 public:
336 ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
337 : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
338 , m_stored(stored), m_retrieving(retrieving) {}
339
342 const std::type_info & GetStoredTypeInfo() const {return m_stored;}
343
346 const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
347
348 private:
349 const std::type_info &m_stored;
350 const std::type_info &m_retrieving;
351 };
352
356 template <class T>
357 bool GetThisObject(T &object) const
358 {
359 return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
360 }
361
365 template <class T>
366 bool GetThisPointer(T *&ptr) const
367 {
368 return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr);
369 }
370
378 template <class T>
379 bool GetValue(const char *name, T &value) const
380 {
381 return GetVoidValue(name, typeid(T), &value);
382 }
383
391 template <class T>
392 T GetValueWithDefault(const char *name, T defaultValue) const
393 {
394 T value;
395 bool result = GetValue(name, value);
396 // No assert... this recovers from failure
397 if (result) {return value;}
398 return defaultValue;
399 }
400
404 CRYPTOPP_DLL std::string GetValueNames() const
405 {std::string result; GetValue("ValueNames", result); return result;}
406
415 CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
416 {return GetValue(name, value);}
417
424 CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
425 {return GetValueWithDefault(name, defaultValue);}
426
433 CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const
434 {return GetValue(name, value);}
435
442 CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
443 {return GetValueWithDefault(name, defaultValue);}
444
454 CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
455 {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
456
467 template <class T>
468 void GetRequiredParameter(const char *className, const char *name, T &value) const
469 {
470 if (!GetValue(name, value))
471 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
472 }
473
483 CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
484 {
485 if (!GetIntValue(name, value))
486 throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
487 }
488
499 CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
500};
501
502// Doxygen cannot handle initialization
503#if CRYPTOPP_DOXYGEN_PROCESSING
511const std::string DEFAULT_CHANNEL;
512
520const std::string AAD_CHANNEL;
521
529const NameValuePairs& g_nullNameValuePairs;
530
531#else
532extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
533extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
534extern CRYPTOPP_DLL const NameValuePairs& g_nullNameValuePairs;
535#endif
536
537// Document additional name spaces which show up elsewhere in the sources.
538#if CRYPTOPP_DOXYGEN_PROCESSING
546DOCUMENTED_NAMESPACE_BEGIN(Name)
547// more names defined in argnames.h
548DOCUMENTED_NAMESPACE_END
549
561DOCUMENTED_NAMESPACE_BEGIN(Weak)
562// weak and wounded algorithms
563DOCUMENTED_NAMESPACE_END
564#endif
565
568DOCUMENTED_NAMESPACE_BEGIN(NaCl)
569// crypto_box, crypto_box_open, crypto_sign, and crypto_sign_open (and friends)
570DOCUMENTED_NAMESPACE_END
571
575DOCUMENTED_NAMESPACE_BEGIN(Test)
576// testing and benchmark classes
577DOCUMENTED_NAMESPACE_END
578
579// ********************************************************
580
584class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
585{
586public:
587 virtual ~Clonable() {}
588
594 virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
595};
596
598class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
599{
600public:
601 virtual ~Algorithm() {}
602
611 Algorithm(bool checkSelfTestStatus = true);
612
619 virtual std::string AlgorithmName() const {return "unknown";}
620
636 virtual std::string AlgorithmProvider() const {return "C++";}
637};
638
641class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
642{
643public:
644 virtual ~SimpleKeyingInterface() {}
645
648 virtual size_t MinKeyLength() const =0;
649
652 virtual size_t MaxKeyLength() const =0;
653
656 virtual size_t DefaultKeyLength() const =0;
657
666 virtual size_t GetValidKeyLength(size_t keylength) const =0;
667
672 virtual bool IsValidKeyLength(size_t keylength) const
673 {return keylength == GetValidKeyLength(keylength);}
674
679 virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
680
689 void SetKeyWithRounds(const byte *key, size_t length, int rounds);
690
699 void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
700
708 void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
709 {SetKeyWithIV(key, length, iv, IVSize());}
710
731
734 virtual IV_Requirement IVRequirement() const =0;
735
740 bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
741
744 bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
745
749 bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
750
755 bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
756
761 virtual unsigned int IVSize() const
762 {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
763
766 unsigned int DefaultIVLength() const {return IVSize();}
767
771 virtual unsigned int MinIVLength() const {return IVSize();}
772
776 virtual unsigned int MaxIVLength() const {return IVSize();}
777
783 virtual void Resynchronize(const byte *iv, int ivLength=-1) {
784 CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength);
785 throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");
786 }
787
797 virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
798
799protected:
802 virtual const Algorithm & GetAlgorithm() const =0;
803
809 virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
810
814 void ThrowIfInvalidKeyLength(size_t length);
815
821 void ThrowIfResynchronizable();
822
830 void ThrowIfInvalidIV(const byte *iv);
831
835 size_t ThrowIfInvalidIVLength(int length);
836
842 const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
843
846 inline void AssertValidKeyLength(size_t length) const
847 {CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));}
848};
849
855class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
856{
857public:
858 virtual ~BlockTransformation() {}
859
869 virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
870
879 void ProcessBlock(const byte *inBlock, byte *outBlock) const
880 {ProcessAndXorBlock(inBlock, NULLPTR, outBlock);}
881
888 void ProcessBlock(byte *inoutBlock) const
889 {ProcessAndXorBlock(inoutBlock, NULLPTR, inoutBlock);}
890
893 virtual unsigned int BlockSize() const =0;
894
898 virtual unsigned int OptimalDataAlignment() const;
899
902 virtual bool IsPermutation() const {return true;}
903
907 virtual bool IsForwardTransformation() const =0;
908
912 virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
913
917 BT_InBlockIsCounter=1,
919 BT_DontIncrementInOutPointers=2,
921 BT_XorInput=4,
923 BT_ReverseDirection=8,
925 BT_AllowParallel=16};
926
935 virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
936
940 inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
941};
942
945class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
946{
947public:
948 virtual ~StreamTransformation() {}
949
953 StreamTransformation& Ref() {return *this;}
954
965 virtual unsigned int MandatoryBlockSize() const {return 1;}
966
972 virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
973
976 virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
977
981 virtual unsigned int OptimalDataAlignment() const;
982
990 virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
991
1004 virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
1005
1021 virtual unsigned int MinLastBlockSize() const {return 0;}
1022
1054 virtual bool IsLastBlockSpecial() const {return false;}
1055
1060 inline void ProcessString(byte *inoutString, size_t length)
1061 {ProcessData(inoutString, inoutString, length);}
1062
1068 inline void ProcessString(byte *outString, const byte *inString, size_t length)
1069 {ProcessData(outString, inString, length);}
1070
1074 inline byte ProcessByte(byte input)
1075 {ProcessData(&input, &input, 1); return input;}
1076
1079 virtual bool IsRandomAccess() const =0;
1080
1086 virtual void Seek(lword pos)
1087 {
1088 CRYPTOPP_UNUSED(pos);
1089 CRYPTOPP_ASSERT(!IsRandomAccess());
1090 throw NotImplemented("StreamTransformation: this object doesn't support random access");
1091 }
1092
1097 virtual bool IsSelfInverting() const =0;
1098
1102 virtual bool IsForwardTransformation() const =0;
1103};
1104
1112class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
1113{
1114public:
1115 virtual ~HashTransformation() {}
1116
1120 HashTransformation& Ref() {return *this;}
1121
1125 virtual void Update(const byte *input, size_t length) =0;
1126
1135 virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULLPTR;}
1136
1142 virtual void Final(byte *digest)
1143 {TruncatedFinal(digest, DigestSize());}
1144
1147 virtual void Restart()
1148 {TruncatedFinal(NULLPTR, 0);}
1149
1152 virtual unsigned int DigestSize() const =0;
1153
1157 unsigned int TagSize() const {return DigestSize();}
1158
1165 virtual unsigned int BlockSize() const {return 0;}
1166
1172 virtual unsigned int OptimalBlockSize() const {return 1;}
1173
1177 virtual unsigned int OptimalDataAlignment() const;
1178
1188 virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
1189 {Update(input, length); Final(digest);}
1190
1200 virtual bool Verify(const byte *digest)
1201 {return TruncatedVerify(digest, DigestSize());}
1202
1216 virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
1217 {Update(input, length); return Verify(digest);}
1218
1226 virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
1227
1238 virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
1239 {Update(input, length); TruncatedFinal(digest, digestSize);}
1240
1253 virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
1254
1269 virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
1270 {Update(input, length); return TruncatedVerify(digest, digestLength);}
1271
1272protected:
1277 void ThrowIfInvalidTruncatedSize(size_t size) const;
1278};
1279
1282class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
1283{
1284protected:
1285 const Algorithm & GetAlgorithm() const {return *this;}
1286};
1287
1290class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
1291{
1292protected:
1293 const Algorithm & GetAlgorithm() const {return *this;}
1294};
1295
1298class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
1299{
1300protected:
1301 const Algorithm & GetAlgorithm() const {return *this;}
1302};
1303
1320class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
1321{
1322public:
1324
1328 class BadState : public Exception
1329 {
1330 public:
1331 explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
1332 explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
1333 };
1334
1337 virtual lword MaxHeaderLength() const =0;
1338
1341 virtual lword MaxMessageLength() const =0;
1342
1345 virtual lword MaxFooterLength() const {return 0;}
1346
1352 virtual bool NeedsPrespecifiedDataLengths() const {return false;}
1353
1363 void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
1364
1377 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);
1378
1394 virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength);
1395
1401 virtual std::string AlgorithmName() const;
1402
1418 virtual std::string AlgorithmProvider() const {return "C++";}
1419
1420protected:
1421 const Algorithm & GetAlgorithm() const
1422 {return *static_cast<const MessageAuthenticationCode *>(this);}
1423 virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
1424 {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);}
1425};
1426
1434class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
1435{
1436public:
1437 virtual ~RandomNumberGenerator() {}
1438
1447 virtual void IncorporateEntropy(const byte *input, size_t length)
1448 {
1449 CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
1450 throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
1451 }
1452
1455 virtual bool CanIncorporateEntropy() const {return false;}
1456
1462 virtual byte GenerateByte();
1463
1469 virtual unsigned int GenerateBit();
1470
1479 virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL);
1480
1488 virtual void GenerateBlock(byte *output, size_t size);
1489
1500 virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
1501
1504 virtual void DiscardBytes(size_t n);
1505
1510 template <class IT> void Shuffle(IT begin, IT end)
1511 {
1512 // TODO: What happens if there are more than 2^32 elements?
1513 for (; begin != end; ++begin)
1514 std::iter_swap(begin, begin + GenerateWord32(0, static_cast<word32>(end-begin-1)));
1515 }
1516};
1517
1522class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm
1523{
1524public:
1525 virtual ~KeyDerivationFunction() {}
1526
1529 virtual std::string AlgorithmName() const =0;
1530
1533 virtual size_t MinDerivedKeyLength() const;
1534
1537 virtual size_t MaxDerivedKeyLength() const;
1538
1542 virtual size_t GetValidDerivedLength(size_t keylength) const =0;
1543
1548 virtual bool IsValidDerivedLength(size_t keylength) const {
1549 return keylength == GetValidDerivedLength(keylength);
1550 }
1551
1565 virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params = g_nullNameValuePairs) const =0;
1566
1571 virtual void SetParameters(const NameValuePairs& params);
1572
1573protected:
1576 virtual const Algorithm & GetAlgorithm() const =0;
1577
1581 void ThrowIfInvalidDerivedKeyLength(size_t length) const;
1582};
1583
1589
1596CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
1597
1598class WaitObjectContainer;
1599class CallStack;
1600
1602class CRYPTOPP_NO_VTABLE Waitable
1603{
1604public:
1605 virtual ~Waitable() {}
1606
1609 virtual unsigned int GetMaxWaitObjectCount() const =0;
1610
1619 virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
1620
1625 bool Wait(unsigned long milliseconds, CallStack const& callStack);
1626};
1627
1651class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
1652{
1653public:
1654 virtual ~BufferedTransformation() {}
1655
1658
1662 BufferedTransformation& Ref() {return *this;}
1663
1665
1666
1673 size_t Put(byte inByte, bool blocking=true)
1674 {return Put(&inByte, 1, blocking);}
1675
1683 size_t Put(const byte *inString, size_t length, bool blocking=true)
1684 {return Put2(inString, length, 0, blocking);}
1685
1692 size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1693
1700 size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1701
1708 size_t PutWord64(word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
1709
1720 virtual byte * CreatePutSpace(size_t &size)
1721 {size=0; return NULLPTR;}
1722
1726 virtual bool CanModifyInput() const
1727 {return false;}
1728
1735 size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
1736 {return PutModifiable2(inString, length, 0, blocking);}
1737
1743 bool MessageEnd(int propagation=-1, bool blocking=true)
1744 {return !!Put2(NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
1745
1757 size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
1758 {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
1759
1768 virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
1769
1778 virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
1779 {return Put2(inString, length, messageEnd, blocking);}
1780
1784 {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
1786
1788
1789
1790 unsigned int GetMaxWaitObjectCount() const;
1791
1800 void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
1802
1804
1805
1816 virtual void IsolatedInitialize(const NameValuePairs &parameters) {
1817 CRYPTOPP_UNUSED(parameters);
1818 throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
1819 }
1820
1826 virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
1827
1832 virtual bool IsolatedMessageSeriesEnd(bool blocking)
1833 {CRYPTOPP_UNUSED(blocking); return false;}
1834
1843 virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
1844
1864 virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
1865
1875 virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
1876
1881 virtual void SetAutoSignalPropagation(int propagation)
1882 {CRYPTOPP_UNUSED(propagation);}
1883
1887 virtual int GetAutoSignalPropagation() const {return 0;}
1888public:
1889
1891
1892
1901 virtual lword MaxRetrievable() const;
1902
1905 virtual bool AnyRetrievable() const;
1906
1911 virtual size_t Get(byte &outByte);
1912
1918 virtual size_t Get(byte *outString, size_t getMax);
1919
1925 virtual size_t Peek(byte &outByte) const;
1926
1933 virtual size_t Peek(byte *outString, size_t peekMax) const;
1934
1940 size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1941
1947 size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1948
1955 size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER);
1956
1963 size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1964
1971 size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1972
1980 size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
1981
1983
1991 lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
1992 {TransferTo2(target, transferMax, channel); return transferMax;}
1993
2004 virtual lword Skip(lword skipMax=LWORD_MAX);
2005
2013 lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
2014 {return CopyRangeTo(target, 0, copyMax, channel);}
2015
2026 lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
2027 {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
2029
2031
2032
2035 virtual lword TotalBytesRetrievable() const;
2036
2041 virtual unsigned int NumberOfMessages() const;
2042
2046 virtual bool AnyMessages() const;
2047
2052 virtual bool GetNextMessage();
2053
2060 virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
2061
2071 unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
2072 {TransferMessagesTo2(target, count, channel); return count;}
2073
2083 unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
2084
2086 virtual void SkipAll();
2087
2093 void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
2094 {TransferAllTo2(target, channel);}
2095
2100 void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
2101
2105 virtual bool GetNextMessageSeries() {return false;}
2108 virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
2111 virtual unsigned int NumberOfMessageSeries() const {return 0;}
2113
2115
2116
2117 // upon return, byteCount contains number of bytes that have finished being transferred,
2118 // and returns the number of bytes left in the current transfer block
2119
2132 virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
2133
2134 // upon return, begin contains the start position of data yet to be finished copying,
2135 // and returns the number of bytes left in the current transfer block
2136
2151 virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
2152
2153 // upon return, messageCount contains number of messages that have finished being transferred,
2154 // and returns the number of bytes left in the current transfer block
2155
2166 size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2167
2168 // returns the number of bytes left in the current transfer block
2169
2176 size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
2178
2180
2181
2183 {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
2186 {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
2187
2194 size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
2195 {return ChannelPut(channel, &inByte, 1, blocking);}
2196
2204 size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
2205 {return ChannelPut2(channel, inString, length, 0, blocking);}
2206
2214 size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
2215 {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
2216
2224 size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2225
2233 size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2234
2242 size_t ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
2243
2252 bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
2253 {return !!ChannelPut2(channel, NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
2254
2264 size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
2265 {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
2266
2278 virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
2279
2287 virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
2288
2296 virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
2297
2306 virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
2307
2318 virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
2319
2323 virtual void SetRetrievalChannel(const std::string &channel);
2325
2330
2332
2335 virtual bool Attachable() {return false;}
2336
2341 virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;}
2342
2348 {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
2349
2356 virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) {
2357 CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable());
2358 throw NotImplemented("BufferedTransformation: this object is not attachable");
2359 }
2360
2363 virtual void Attach(BufferedTransformation *newAttachment);
2365
2366protected:
2369 static int DecrementPropagation(int propagation)
2370 {return propagation != 0 ? propagation - 1 : 0;}
2371
2372private:
2373 // for ChannelPutWord16, ChannelPutWord32 and ChannelPutWord64,
2374 // to ensure the buffer isn't deallocated before non-blocking
2375 // operation completes
2376 byte m_buf[8];
2377};
2378
2381CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
2382
2389class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
2390{
2391public:
2393 class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
2394 {
2395 public:
2396 explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
2397 };
2398
2399 virtual ~CryptoMaterial() {}
2400
2403 virtual void AssignFrom(const NameValuePairs &source) =0;
2404
2419 virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
2420
2427 virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
2428 {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
2429
2439 virtual void Save(BufferedTransformation &bt) const
2440 {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
2441
2457 {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
2458
2462 virtual bool SupportsPrecomputation() const {return false;}
2463
2472 virtual void Precompute(unsigned int precomputationStorage) {
2473 CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation());
2474 throw NotImplemented("CryptoMaterial: this object does not support precomputation");
2475 }
2476
2481 virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
2482 {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2483
2488 virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
2489 {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
2490
2493 void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
2494
2495#if defined(__SUNPRO_CC)
2496 // Sun Studio 11/CC 5.8 workaround: it generates incorrect code
2497 // when casting to an empty virtual base class. JW, 2018: It is
2498 // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable
2499 // it everywhere in case it affects SPARC (which we don't test).
2500 char m_sunCCworkaround;
2501#endif
2502};
2503
2509class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
2510{
2511public:
2512 virtual ~GeneratableCryptoMaterial() {}
2513
2520 virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs) {
2521 CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
2522 throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
2523 }
2524
2531 void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
2532};
2533
2535class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
2536{
2537};
2538
2540class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
2541{
2542};
2543
2545class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
2546{
2547};
2548
2550class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Certificate : virtual public CryptoMaterial
2551{
2552};
2553
2559class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
2560{
2561public:
2562 virtual ~AsymmetricAlgorithm() {}
2563
2567
2570 virtual const CryptoMaterial & GetMaterial() const =0;
2571
2572#if 0
2577 void BERDecode(BufferedTransformation &bt)
2578 {AccessMaterial().Load(bt);}
2579
2584 void DEREncode(BufferedTransformation &bt) const
2585 {GetMaterial().Save(bt);}
2586#endif
2587};
2588
2590class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
2591{
2592public:
2593 virtual ~PublicKeyAlgorithm() {}
2594
2595 // VC60 workaround: no co-variant return type
2596
2600 {return AccessPublicKey();}
2604 {return GetPublicKey();}
2605
2611 virtual const PublicKey & GetPublicKey() const
2612 {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
2613};
2614
2616class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
2617{
2618public:
2619 virtual ~PrivateKeyAlgorithm() {}
2620
2623 CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
2626 const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
2627
2633 virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
2634};
2635
2637class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
2638{
2639public:
2640 virtual ~KeyAgreementAlgorithm() {}
2641
2644 CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
2647 const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
2648
2654 virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
2655};
2656
2660class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
2661{
2662public:
2663 virtual ~PK_CryptoSystem() {}
2664
2668 virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
2669
2673 virtual size_t CiphertextLength(size_t plaintextLength) const =0;
2674
2680 virtual bool ParameterSupported(const char *name) const =0;
2681
2686 virtual size_t FixedCiphertextLength() const {return 0;}
2687
2693 virtual size_t FixedMaxPlaintextLength() const {return 0;}
2694};
2695
2697class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
2698{
2699public:
2701 class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
2702 {
2703 public:
2704 InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
2705 };
2706
2718 const byte *plaintext, size_t plaintextLength,
2719 byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2720
2727 virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
2728 BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2729};
2730
2732class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
2733{
2734public:
2735 virtual ~PK_Decryptor() {}
2736
2752 const byte *ciphertext, size_t ciphertextLength,
2753 byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
2754
2761 virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
2762 BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
2763
2777 DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
2778 {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
2779};
2780
2784class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
2785{
2786public:
2790 class CRYPTOPP_DLL InvalidKeyLength : public Exception
2791 {
2792 public:
2793 InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
2794 };
2795
2799 class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
2800 {
2801 public:
2802 KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
2803 };
2804
2805 virtual ~PK_SignatureScheme() {}
2806
2810 virtual size_t SignatureLength() const =0;
2811
2817 virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
2818 {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
2819
2824 virtual size_t MaxRecoverableLength() const =0;
2825
2832 virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
2833
2838 virtual bool IsProbabilistic() const =0;
2839
2842 virtual bool AllowNonrecoverablePart() const =0;
2843
2848 virtual bool SignatureUpfront() const {return false;}
2849
2854 virtual bool RecoverablePartFirst() const =0;
2855};
2856
2860class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
2861{
2862public:
2864 unsigned int DigestSize() const
2865 {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
2866
2868 void TruncatedFinal(byte *digest, size_t digestSize)
2869 {
2870 CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
2871 throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
2872 }
2873};
2874
2876class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
2877{
2878public:
2879 virtual ~PK_Signer() {}
2880
2887
2892 virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
2893
2901 virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
2902
2910 virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
2911
2919 virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
2920
2930 virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
2931 const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
2932};
2933
2940class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
2941{
2942public:
2943 virtual ~PK_Verifier() {}
2944
2950
2955 virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
2956
2961 virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
2962
2967 virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
2968
2975 virtual bool VerifyMessage(const byte *message, size_t messageLen,
2976 const byte *signature, size_t signatureLen) const;
2977
2984 virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
2985
2992 virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
2993
3002 virtual DecodingResult RecoverMessage(byte *recoveredMessage,
3003 const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
3004 const byte *signature, size_t signatureLength) const;
3005};
3006
3012class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
3013{
3014public:
3015 virtual ~SimpleKeyAgreementDomain() {}
3016
3019 virtual unsigned int AgreedValueLength() const =0;
3020
3023 virtual unsigned int PrivateKeyLength() const =0;
3024
3027 virtual unsigned int PublicKeyLength() const =0;
3028
3033 virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3034
3040 virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3041
3049 virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3050
3063 virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
3064};
3065
3071class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3072{
3073public:
3075
3078 virtual unsigned int AgreedValueLength() const =0;
3079
3082 virtual unsigned int StaticPrivateKeyLength() const =0;
3083
3086 virtual unsigned int StaticPublicKeyLength() const =0;
3087
3092 virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3093
3099 virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3100
3108 virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3109
3112 virtual unsigned int EphemeralPrivateKeyLength() const =0;
3113
3116 virtual unsigned int EphemeralPublicKeyLength() const =0;
3117
3122 virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
3123
3129 virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
3130
3136 virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
3137
3154 virtual bool Agree(byte *agreedValue,
3155 const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
3156 const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
3157 bool validateStaticOtherPublicKey=true) const =0;
3158};
3159
3160// interface for password authenticated key agreement protocols, not implemented yet
3161#if 0
3163
3183class ProtocolSession
3184{
3185public:
3187 class ProtocolError : public Exception
3188 {
3189 public:
3190 ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
3191 };
3192
3194
3195 class UnexpectedMethodCall : public Exception
3196 {
3197 public:
3198 UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
3199 };
3200
3201 virtual ~ProtocolSession() {}
3202
3203 ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {}
3204
3205 virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
3206
3207 bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
3208 void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
3209
3210 bool HasValidState() const {return m_validState;}
3211
3212 virtual bool OutgoingMessageAvailable() const =0;
3213 virtual unsigned int GetOutgoingMessageLength() const =0;
3214 virtual void GetOutgoingMessage(byte *message) =0;
3215
3216 virtual bool LastMessageProcessed() const =0;
3217 virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
3218
3219protected:
3220 void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
3221 void CheckAndHandleInvalidState() const;
3222 void SetValidState(bool valid) {m_validState = valid;}
3223
3224 RandomNumberGenerator *m_rng;
3225
3226private:
3227 bool m_throwOnProtocolError, m_validState;
3228};
3229
3230class KeyAgreementSession : public ProtocolSession
3231{
3232public:
3233 virtual ~KeyAgreementSession() {}
3234
3235 virtual unsigned int GetAgreedValueLength() const =0;
3236 virtual void GetAgreedValue(byte *agreedValue) const =0;
3237};
3238
3239class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
3240{
3241public:
3242 virtual ~PasswordAuthenticatedKeyAgreementSession() {}
3243
3244 void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
3245 const byte *myId, unsigned int myIdLength,
3246 const byte *counterPartyId, unsigned int counterPartyIdLength,
3247 const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
3248};
3249
3252class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
3253{
3254public:
3255 virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
3256
3258 virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
3259 {return GetCryptoParameters().Validate(rng, 2);}
3260
3261 virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
3262 virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
3263
3264 enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
3265
3266 virtual bool IsValidRole(unsigned int role) =0;
3267 virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
3268};
3269#endif
3270
3272class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
3273{
3274public:
3275 BERDecodeErr() : InvalidArgument("BER decode error") {}
3276 BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
3277};
3278
3283class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
3284{
3285public:
3286 virtual ~ASN1Object() {}
3287
3291 virtual void BERDecode(BufferedTransformation &bt) =0;
3292
3296 virtual void DEREncode(BufferedTransformation &bt) const =0;
3297
3302 virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
3303};
3304
3335extern "C" {
3336 int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT);
3337} // C linkage
3338
3366extern "C" {
3367inline int HeaderVersion()
3368{
3369 return CRYPTOPP_VERSION;
3370}
3371} // C linkage
3372
3373NAMESPACE_END
3374
3375#if CRYPTOPP_MSC_VERSION
3376# pragma warning(pop)
3377#endif
3378
3379#endif
Interface for encoding and decoding ASN1 objects.
Definition cryptlib.h:3284
virtual void DEREncode(BufferedTransformation &bt) const =0
Encode this object into a BufferedTransformation.
virtual void BEREncode(BufferedTransformation &bt) const
Encode this object into a BufferedTransformation.
Definition cryptlib.h:3302
virtual void BERDecode(BufferedTransformation &bt)=0
Decode this object from a BufferedTransformation.
Interface for all crypto algorithms.
Definition cryptlib.h:599
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition cryptlib.h:619
virtual std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition cryptlib.h:636
Interface for asymmetric algorithms.
Definition cryptlib.h:2560
virtual const CryptoMaterial & GetMaterial() const =0
Retrieves a reference to CryptoMaterial.
virtual CryptoMaterial & AccessMaterial()=0
Retrieves a reference to CryptoMaterial.
Interface for domains of authenticated key agreement protocols.
Definition cryptlib.h:3072
virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate static private key in this domain.
virtual unsigned int StaticPrivateKeyLength() const =0
Provides the size of the static private key.
virtual unsigned int EphemeralPublicKeyLength() const =0
Provides the size of ephemeral public key.
virtual unsigned int EphemeralPrivateKeyLength() const =0
Provides the size of ephemeral private key.
virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a static public key from a private key in this domain.
virtual unsigned int AgreedValueLength() const =0
Provides the size of the agreed value.
virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate ephemeral public key.
virtual unsigned int StaticPublicKeyLength() const =0
Provides the size of the static public key.
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate ephemeral private key.
virtual bool Agree(byte *agreedValue, const byte *staticPrivateKey, const byte *ephemeralPrivateKey, const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey, bool validateStaticOtherPublicKey=true) const =0
Derive agreed value.
Exception thrown when the object is in the wrong state for the operation.
Definition cryptlib.h:1329
Interface for authenticated encryption modes of operation.
Definition cryptlib.h:1321
virtual lword MaxHeaderLength() const =0
Provides the maximum length of AAD that can be input.
const Algorithm & GetAlgorithm() const
Returns the base class Algorithm.
Definition cryptlib.h:1421
virtual lword MaxFooterLength() const
Provides the maximum length of AAD.
Definition cryptlib.h:1345
virtual std::string AlgorithmProvider() const
Retrieve the provider of this algorithm.
Definition cryptlib.h:1418
virtual lword MaxMessageLength() const =0
Provides the maximum length of encrypted data.
virtual bool NeedsPrespecifiedDataLengths() const
Determines if data lengths must be specified prior to inputting data.
Definition cryptlib.h:1352
Exception thrown when an ASN.1 BER decoing error is encountered.
Definition cryptlib.h:3273
Interface for one direction (encryption or decryption) of a block cipher.
Definition cryptlib.h:1283
const Algorithm & GetAlgorithm() const
Returns the base class Algorithm.
Definition cryptlib.h:1285
Interface for the data processing part of block ciphers.
Definition cryptlib.h:856
virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0
Encrypt or decrypt a block.
virtual bool IsForwardTransformation() const =0
Determines if the cipher is being operated in its forward direction.
CipherDir GetCipherDirection() const
Provides the direction of the cipher.
Definition cryptlib.h:940
void ProcessBlock(const byte *inBlock, byte *outBlock) const
Encrypt or decrypt a block.
Definition cryptlib.h:879
virtual unsigned int OptimalNumberOfParallelBlocks() const
Determines the number of blocks that can be processed in parallel.
Definition cryptlib.h:912
virtual bool IsPermutation() const
Determines if the transformation is a permutation.
Definition cryptlib.h:902
void ProcessBlock(byte *inoutBlock) const
Encrypt or decrypt a block in place.
Definition cryptlib.h:888
FlagsForAdvancedProcessBlocks
Bit flags that control AdvancedProcessBlocks() behavior.
Definition cryptlib.h:915
virtual unsigned int BlockSize() const =0
Interface for buffered transformations.
Definition cryptlib.h:1652
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition cryptlib.h:2341
unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
Transfer messages from this object to another BufferedTransformation.
Definition cryptlib.h:2071
static int DecrementPropagation(int propagation)
Decrements the propagation count while clamping at 0.
Definition cryptlib.h:2369
virtual bool Attachable()
Determines whether the object allows attachment.
Definition cryptlib.h:2335
bool MessageEnd(int propagation=-1, bool blocking=true)
Signals the end of messages to the object.
Definition cryptlib.h:1743
virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)=0
Transfer bytes from this object to another BufferedTransformation.
size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
Input multiple bytes that may be modified by callee on a channel.
Definition cryptlib.h:2214
size_t Put(const byte *inString, size_t length, bool blocking=true)
Input a byte buffer for processing.
Definition cryptlib.h:1683
size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
Input a byte buffer for processing on a channel.
Definition cryptlib.h:2204
BufferedTransformation()
Construct a BufferedTransformation.
Definition cryptlib.h:1657
virtual bool IsolatedFlush(bool hardFlush, bool blocking)=0
Flushes data buffered by this object, without signal propagation.
lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
Copy bytes from this object to another BufferedTransformation.
Definition cryptlib.h:2013
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition cryptlib.h:1887
virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes that may be modified by callee.
Definition cryptlib.h:1778
lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
Copy bytes from this object using an index to another BufferedTransformation.
Definition cryptlib.h:2026
virtual void IsolatedInitialize(const NameValuePairs &parameters)
Initialize or reinitialize this object, without signal propagation.
Definition cryptlib.h:1816
virtual void Detach(BufferedTransformation *newAttachment=NULLPTR)
Delete the current attachment chain and attach a new one.
Definition cryptlib.h:2356
virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0
Copy bytes from this object to another BufferedTransformation.
void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
Transfer all bytes from this object to another BufferedTransformation.
Definition cryptlib.h:2093
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition cryptlib.h:1720
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition cryptlib.h:2194
size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
Input multiple bytes for processing and signal the end of a message.
Definition cryptlib.h:1757
virtual bool IsolatedMessageSeriesEnd(bool blocking)
Marks the end of a series of messages, without signal propagation.
Definition cryptlib.h:1832
lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
move transferMax bytes of the buffered output to target as input
Definition cryptlib.h:1991
virtual unsigned int NumberOfMessagesInThisSeries() const
Provides the number of messages in a series.
Definition cryptlib.h:2108
virtual unsigned int NumberOfMessageSeries() const
Provides the number of messages in a series.
Definition cryptlib.h:2111
virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)=0
Input multiple bytes for processing.
size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
Input multiple bytes for processing and signal the end of a message.
Definition cryptlib.h:2264
virtual const BufferedTransformation * AttachedTransformation() const
Returns the object immediately attached to this object.
Definition cryptlib.h:2347
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition cryptlib.h:2252
size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
Input multiple bytes that may be modified by callee.
Definition cryptlib.h:1735
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition cryptlib.h:1673
virtual void SetAutoSignalPropagation(int propagation)
Set propagation of automatically generated and transferred signals.
Definition cryptlib.h:1881
virtual bool GetNextMessageSeries()
Retrieve the next message in a series.
Definition cryptlib.h:2105
BufferedTransformation & Ref()
Provides a reference to this object.
Definition cryptlib.h:1662
virtual bool CanModifyInput() const
Determines whether input can be modified by the callee.
Definition cryptlib.h:1726
Flush(true) was called but it can't completely flush its buffers.
Definition cryptlib.h:243
CannotFlush(const std::string &s)
Construct an CannotFlush.
Definition cryptlib.h:248
Interface for certificates.
Definition cryptlib.h:2551
Namespace containing NaCl library functions.
Definition cryptlib.h:585
virtual Clonable * Clone() const
Copies this object.
Definition cryptlib.h:594
Exception thrown when invalid crypto material is detected.
Definition cryptlib.h:2394
Interface for crypto material.
Definition cryptlib.h:2390
virtual void Save(BufferedTransformation &bt) const
Saves a key to a BufferedTransformation.
Definition cryptlib.h:2439
virtual void AssignFrom(const NameValuePairs &source)=0
Assign values to this object.
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
Retrieve previously saved precomputation.
Definition cryptlib.h:2481
virtual bool SupportsPrecomputation() const
Determines whether the object supports precomputation.
Definition cryptlib.h:2462
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
Save precomputation for later use.
Definition cryptlib.h:2488
virtual void Precompute(unsigned int precomputationStorage)
Perform precomputation.
Definition cryptlib.h:2472
void DoQuickSanityCheck() const
Perform a quick sanity check.
Definition cryptlib.h:2493
virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0
Check this object for errors.
virtual void Load(BufferedTransformation &bt)
Loads a key from a BufferedTransformation.
Definition cryptlib.h:2456
virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
Check this object for errors.
Definition cryptlib.h:2427
Interface for crypto parameters.
Definition cryptlib.h:2546
Base class for all exceptions thrown by the library.
Definition cryptlib.h:159
void SetErrorType(ErrorType errorType)
Sets the error type for the exceptions.
Definition cryptlib.h:194
void SetWhat(const std::string &s)
Sets the error string for the exception.
Definition cryptlib.h:190
Exception(ErrorType errorType, const std::string &s)
Construct a new Exception.
Definition cryptlib.h:183
ErrorType
Error types or categories.
Definition cryptlib.h:163
@ CANNOT_FLUSH
BufferedTransformation received a Flush(true) signal but can't flush buffers.
Definition cryptlib.h:169
@ NOT_IMPLEMENTED
A method was called which was not implemented.
Definition cryptlib.h:165
@ INVALID_DATA_FORMAT
Input data was received that did not conform to expected format.
Definition cryptlib.h:173
@ DATA_INTEGRITY_CHECK_FAILED
Data integerity check, such as CRC or MAC, failed.
Definition cryptlib.h:171
@ INVALID_ARGUMENT
An invalid argument was detected.
Definition cryptlib.h:167
@ IO_ERROR
Error reading from input device or writing to output device.
Definition cryptlib.h:175
const char * what() const
Retrieves a C-string describing the exception.
Definition cryptlib.h:186
ErrorType GetErrorType() const
Retrieves the error type for the exception.
Definition cryptlib.h:192
const std::string & GetWhat() const
Retrieves a string describing the exception.
Definition cryptlib.h:188
Interface for crypto material.
Definition cryptlib.h:2510
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition cryptlib.h:2520
Interface for hash functions and data processing part of MACs.
Definition cryptlib.h:1113
virtual unsigned int BlockSize() const
Provides the block size of the compression function.
Definition cryptlib.h:1165
virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
Updates the hash with additional input and computes the hash of the current message.
Definition cryptlib.h:1238
virtual bool Verify(const byte *digest)
Verifies the hash of the current message.
Definition cryptlib.h:1200
HashTransformation & Ref()
Provides a reference to this object.
Definition cryptlib.h:1120
virtual void TruncatedFinal(byte *digest, size_t digestSize)=0
Computes the hash of the current message.
virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
Updates the hash with additional input and verifies the hash of the current message.
Definition cryptlib.h:1269
virtual void Restart()
Restart the hash.
Definition cryptlib.h:1147
virtual unsigned int DigestSize() const =0
virtual void Final(byte *digest)
Computes the hash of the current message.
Definition cryptlib.h:1142
virtual void Update(const byte *input, size_t length)=0
Updates a hash with additional input.
virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
Updates the hash with additional input and verifies the hash of the current message.
Definition cryptlib.h:1216
virtual byte * CreateUpdateSpace(size_t &size)
Request space which can be written into by the caller.
Definition cryptlib.h:1135
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this hash.
Definition cryptlib.h:1172
unsigned int TagSize() const
Definition cryptlib.h:1157
virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
Updates the hash with additional input and computes the hash of the current message.
Definition cryptlib.h:1188
Multiple precision integer with arithmetic operations.
Definition integer.h:50
An invalid argument was detected.
Definition cryptlib.h:203
InvalidArgument(const std::string &s)
Construct an InvalidArgument.
Definition cryptlib.h:208
A decryption filter encountered invalid ciphertext.
Definition cryptlib.h:223
InvalidCiphertext(const std::string &s)
Construct an InvalidCiphertext.
Definition cryptlib.h:228
Input data was received that did not conform to expected format.
Definition cryptlib.h:213
InvalidDataFormat(const std::string &s)
Construct an InvalidDataFormat.
Definition cryptlib.h:218
Interface for key agreement algorithms.
Definition cryptlib.h:2638
virtual CryptoParameters & AccessCryptoParameters()=0
Retrieves a reference to Crypto Parameters.
virtual const CryptoParameters & GetCryptoParameters() const
Retrieves a reference to Crypto Parameters.
Definition cryptlib.h:2654
CryptoMaterial & AccessMaterial()
Retrieves a reference to Crypto Parameters.
Definition cryptlib.h:2644
const CryptoMaterial & GetMaterial() const
Retrieves a reference to Crypto Parameters.
Definition cryptlib.h:2647
Interface for key derivation functions.
Definition cryptlib.h:1523
virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs &params=g_nullNameValuePairs) const =0
Derive a key from a seed.
virtual const Algorithm & GetAlgorithm() const =0
Returns the base class Algorithm.
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition cryptlib.h:1548
virtual size_t GetValidDerivedLength(size_t keylength) const =0
Returns a valid key length for the derivation function.
virtual std::string AlgorithmName() const =0
Provides the name of this algorithm.
Interface for message authentication codes.
Definition cryptlib.h:1299
const Algorithm & GetAlgorithm() const
Returns the base class Algorithm.
Definition cryptlib.h:1301
Thrown when an unexpected type is encountered.
Definition cryptlib.h:330
const std::type_info & GetRetrievingTypeInfo() const
Provides the retrieveing type.
Definition cryptlib.h:346
ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
Construct a ValueTypeMismatch.
Definition cryptlib.h:336
const std::type_info & GetStoredTypeInfo() const
Provides the stored type.
Definition cryptlib.h:342
Interface for retrieving values given their names.
Definition cryptlib.h:322
virtual CRYPTOPP_DLL bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0
Get a named value.
CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
Get a named value with type word64, with default.
Definition cryptlib.h:442
bool GetThisObject(T &object) const
Get a copy of this object or subobject.
Definition cryptlib.h:357
T GetValueWithDefault(const char *name, T defaultValue) const
Get a named value.
Definition cryptlib.h:392
bool GetValue(const char *name, T &value) const
Get a named value.
Definition cryptlib.h:379
static CRYPTOPP_DLL void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
Ensures an expected name and type is present.
Definition cryptlib.h:454
CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
Get a named value with type int, with default.
Definition cryptlib.h:424
CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const
Get a named value with type word64.
Definition cryptlib.h:433
CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
Get a named value with type int.
Definition cryptlib.h:415
CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
Retrieves a required name/value pair.
Definition cryptlib.h:483
bool GetThisPointer(T *&ptr) const
Get a pointer to this object.
Definition cryptlib.h:366
CRYPTOPP_DLL std::string GetValueNames() const
Get a list of value names that can be retrieved.
Definition cryptlib.h:404
void GetRequiredParameter(const char *className, const char *name, T &value) const
Retrieves a required name/value pair.
Definition cryptlib.h:468
A method was called which was not implemented.
Definition cryptlib.h:233
NotImplemented(const std::string &s)
Construct an NotImplemented.
Definition cryptlib.h:238
The operating system reported an error.
Definition cryptlib.h:253
OS_Error(ErrorType errorType, const std::string &s, const std::string &operation, int errorCode)
Construct an OS_Error.
Definition cryptlib.h:263
const std::string & GetOperation() const
Retrieve the operating system API that reported the error.
Definition cryptlib.h:267
int GetErrorCode() const
Retrieve the error code returned by the operating system.
Definition cryptlib.h:269
Interface for public-key encryptors and decryptors.
Definition cryptlib.h:2661
virtual bool ParameterSupported(const char *name) const =0
Determines whether this object supports the use of a named parameter.
virtual size_t FixedMaxPlaintextLength() const
Provides the maximum plaintext length given a fixed ciphertext length.
Definition cryptlib.h:2693
virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0
Provides the maximum length of plaintext for a given ciphertext length.
virtual size_t CiphertextLength(size_t plaintextLength) const =0
Calculate the length of ciphertext given length of plaintext.
virtual size_t FixedCiphertextLength() const
Provides the fixed ciphertext length, if one exists.
Definition cryptlib.h:2686
Interface for public-key decryptors.
Definition cryptlib.h:2733
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const
Decrypt a fixed size ciphertext.
Definition cryptlib.h:2777
virtual DecodingResult Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const =0
Decrypt a byte string.
Exception thrown when trying to encrypt plaintext of invalid length.
Definition cryptlib.h:2702
Interface for public-key encryptors.
Definition cryptlib.h:2698
virtual void Encrypt(RandomNumberGenerator &rng, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters=g_nullNameValuePairs) const =0
Encrypt a byte string.
Interface for accumulating messages to be signed or verified.
Definition cryptlib.h:2861
void TruncatedFinal(byte *digest, size_t digestSize)
Definition cryptlib.h:2868
unsigned int DigestSize() const
Definition cryptlib.h:2864
Exception throw when the private or public key has a length that can't be used.
Definition cryptlib.h:2791
Exception throw when the private or public key is too short to sign or verify.
Definition cryptlib.h:2800
Interface for public-key signers and verifiers.
Definition cryptlib.h:2785
virtual bool AllowNonrecoverablePart() const =0
Determines whether the non-recoverable message part can be signed.
virtual bool RecoverablePartFirst() const =0
Determines whether the recoverable part must be input before the non-recoverable part.
virtual size_t MaxRecoverableLength() const =0
Provides the length of longest message that can be recovered.
virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0
Provides the length of longest message that can be recovered from a signature of given length.
virtual size_t MaxSignatureLength(size_t recoverablePartLength=0) const
Provides the maximum signature length produced given the length of the recoverable message part.
Definition cryptlib.h:2817
virtual bool SignatureUpfront() const
Determines whether the signature must be input before the message.
Definition cryptlib.h:2848
virtual size_t SignatureLength() const =0
Provides the signature length if it only depends on the key.
virtual bool IsProbabilistic() const =0
Determines whether a signature scheme requires a random number generator.
Interface for public-key signers.
Definition cryptlib.h:2877
virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0
Input a recoverable message to an accumulator.
virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0
Create a new HashTransformation to accumulate the message to be signed.
virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0
Sign and restart messageAccumulator.
Interface for public-key signature verifiers.
Definition cryptlib.h:2941
virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0
Create a new HashTransformation to accumulate the message to be verified.
virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0
Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulat...
virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0
Input signature into a message accumulator.
virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0
Recover a message from its signature.
Interface for asymmetric algorithms using private keys.
Definition cryptlib.h:2617
virtual PrivateKey & AccessPrivateKey()=0
Retrieves a reference to a Private Key.
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Private Key.
Definition cryptlib.h:2626
virtual const PrivateKey & GetPrivateKey() const
Retrieves a reference to a Private Key.
Definition cryptlib.h:2633
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Private Key.
Definition cryptlib.h:2623
Interface for private keys.
Definition cryptlib.h:2541
Interface for asymmetric algorithms using public keys.
Definition cryptlib.h:2591
virtual PublicKey & AccessPublicKey()=0
Retrieves a reference to a Public Key.
virtual const PublicKey & GetPublicKey() const
Retrieves a reference to a Public Key.
Definition cryptlib.h:2611
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Public Key.
Definition cryptlib.h:2599
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Public Key.
Definition cryptlib.h:2603
Interface for public keys.
Definition cryptlib.h:2536
Interface for random number generators.
Definition cryptlib.h:1435
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition cryptlib.h:1447
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
Definition cryptlib.h:1455
void Shuffle(IT begin, IT end)
Randomly shuffle the specified array.
Definition cryptlib.h:1510
Interface for domains of simple key agreement protocols.
Definition cryptlib.h:3013
virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a public key from a private key in this domain.
virtual unsigned int PublicKeyLength() const =0
Provides the size of the public key.
virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0
Derive agreed value.
virtual unsigned int PrivateKeyLength() const =0
Provides the size of the private key.
virtual unsigned int AgreedValueLength() const =0
Provides the size of the agreed value.
virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate private key in this domain.
Interface for algorithms that take byte strings as keys.
Definition cryptlib.h:642
virtual size_t MinKeyLength() const =0
Returns smallest valid key length.
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition cryptlib.h:672
void AssertValidKeyLength(size_t length) const
Validates the key length.
Definition cryptlib.h:846
virtual const Algorithm & GetAlgorithm() const =0
Returns the base class Algorithm.
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition cryptlib.h:740
virtual IV_Requirement IVRequirement() const =0
Minimal requirement for secure IVs.
IV_Requirement
Secure IVs requirements as enumerated values.
Definition cryptlib.h:719
@ RANDOM_IV
The IV must be random and possibly predictable.
Definition cryptlib.h:723
@ INTERNALLY_GENERATED_IV
The IV is set by the object.
Definition cryptlib.h:727
@ UNPREDICTABLE_RANDOM_IV
The IV must be random and unpredictable.
Definition cryptlib.h:725
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition cryptlib.h:776
virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params)=0
Sets the key for this object without performing parameter validation.
bool CanUseRandomIVs() const
Determines if the object can use random IVs.
Definition cryptlib.h:744
virtual size_t GetValidKeyLength(size_t keylength) const =0
Returns a valid key length for the algorithm.
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition cryptlib.h:771
bool CanUsePredictableIVs() const
Determines if the object can use random but possibly predictable IVs.
Definition cryptlib.h:749
void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
Sets or reset the key of this object.
Definition cryptlib.h:708
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition cryptlib.h:761
virtual size_t MaxKeyLength() const =0
Returns largest valid key length.
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition cryptlib.h:783
virtual size_t DefaultKeyLength() const =0
Returns default key length.
unsigned int DefaultIVLength() const
Provides the default size of an IV.
Definition cryptlib.h:766
bool CanUseStructuredIVs() const
Determines if the object can use structured IVs.
Definition cryptlib.h:755
Interface for the data processing portion of stream ciphers.
Definition cryptlib.h:946
virtual unsigned int MinLastBlockSize() const
Provides the size of the last block.
Definition cryptlib.h:1021
void ProcessString(byte *outString, const byte *inString, size_t length)
Encrypt or decrypt a string of bytes.
Definition cryptlib.h:1068
virtual void ProcessData(byte *outString, const byte *inString, size_t length)=0
Encrypt or decrypt an array of bytes.
virtual bool IsForwardTransformation() const =0
Determines if the cipher is being operated in its forward direction.
virtual bool IsSelfInverting() const =0
Determines whether the cipher is self-inverting.
virtual bool IsLastBlockSpecial() const
Determines if the last block receives special processing.
Definition cryptlib.h:1054
byte ProcessByte(byte input)
Encrypt or decrypt a byte.
Definition cryptlib.h:1074
virtual void Seek(lword pos)
Seek to an absolute position.
Definition cryptlib.h:1086
virtual unsigned int GetOptimalBlockSizeUsed() const
Provides the number of bytes used in the current block when processing at optimal block size.
Definition cryptlib.h:976
void ProcessString(byte *inoutString, size_t length)
Encrypt or decrypt a string of bytes.
Definition cryptlib.h:1060
StreamTransformation & Ref()
Provides a reference to this object.
Definition cryptlib.h:953
virtual bool IsRandomAccess() const =0
Determines whether the cipher supports random access.
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition cryptlib.h:965
virtual unsigned int OptimalBlockSize() const
Provides the input block size most efficient for this cipher.
Definition cryptlib.h:972
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode.
Definition cryptlib.h:1291
const Algorithm & GetAlgorithm() const
Returns the base class Algorithm.
Definition cryptlib.h:1293
Interface for objects that can be waited on.
Definition cryptlib.h:1603
virtual unsigned int GetMaxWaitObjectCount() const =0
Maximum number of wait objects that this object can return.
virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const &callStack)=0
Retrieves waitable objects.
bool Wait(unsigned long milliseconds, CallStack const &callStack)
Wait on this object.
Library configuration file.
const lword LWORD_MAX
Large word type max value.
Definition config_int.h:164
unsigned int word32
32-bit unsigned datatype
Definition config_int.h:62
unsigned short word16
16-bit unsigned datatype
Definition config_int.h:59
word64 lword
Large word type.
Definition config_int.h:158
#define CRYPTOPP_VERSION
Full library version.
Definition config_ver.h:53
int HeaderVersion()
Specifies the runtime version of the library.
Definition cryptlib.h:3367
CRYPTOPP_DLL RandomNumberGenerator &CRYPTOPP_API NullRNG()
Random Number Generator that does not produce random numbers.
Definition cryptlib.cpp:400
CipherDir
Specifies a direction for a cipher to operate.
Definition cryptlib.h:123
@ ENCRYPTION
the cipher is performing encryption
Definition cryptlib.h:125
@ DECRYPTION
the cipher is performing decryption
Definition cryptlib.h:127
const unsigned long INFINITE_TIME
Represents infinite time.
Definition cryptlib.h:130
int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT)
Specifies the build-time version of the library.
CRYPTOPP_DLL BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
Definition cryptlib.cpp:40
ByteOrder
Provides the byte ordering.
Definition cryptlib.h:143
@ LITTLE_ENDIAN_ORDER
byte order is little-endian
Definition cryptlib.h:145
@ BIG_ENDIAN_ORDER
byte order is big-endian
Definition cryptlib.h:147
EnumToType< ByteOrder, LITTLE_ENDIAN_ORDER > LittleEndian
Provides a constant for LittleEndian.
Definition cryptlib.h:150
EnumToType< ByteOrder, BIG_ENDIAN_ORDER > BigEndian
Provides a constant for BigEndian.
Definition cryptlib.h:152
Common C++ header files.
Exception thrown by objects that have not implemented nonblocking input processing.
Definition cryptlib.h:1784
Exception thrown when a filter does not recognize a named channel.
Definition cryptlib.h:2186
Exception thrown when a filter does not support named channels.
Definition cryptlib.h:2183
Returns a decoding results.
Definition cryptlib.h:278
DecodingResult(size_t len)
Constructs a DecodingResult.
Definition cryptlib.h:286
bool operator!=(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition cryptlib.h:298
bool operator==(const DecodingResult &rhs) const
Compare two DecodingResult.
Definition cryptlib.h:292
DecodingResult()
Constructs a DecodingResult.
Definition cryptlib.h:282
bool isValidCoding
Flag to indicate the decoding is valid.
Definition cryptlib.h:301
size_t messageLength
Recovered message length if isValidCoding is true, undefined otherwise.
Definition cryptlib.h:303
Converts an enumeration to a type suitable for use as a template parameter.
Definition cryptlib.h:136
Interface for password based key derivation functions.
Definition cryptlib.h:1587
Debugging and diagnostic assertions.