cryptlib.h 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384
  1. // cryptlib.h - originally written and placed in the public domain by Wei Dai
  2. /// \file cryptlib.h
  3. /// \brief Abstract base classes that provide a uniform interface to this library.
  4. /*! \mainpage Crypto++ Library 8.9 API Reference
  5. <dl>
  6. <dt>Abstract Base Classes<dd>
  7. cryptlib.h
  8. <dt>Authenticated Encryption Modes<dd>
  9. CCM, EAX, \ref GCM "GCM (2K tables)", \ref GCM "GCM (64K tables)"
  10. <dt>Block Ciphers<dd>
  11. \ref Rijndael "AES", ARIA, Weak::ARC4, Blowfish, BTEA, \ref CHAM128 "CHAM (64/128)", Camellia,
  12. \ref CAST128 "CAST (128/256)", DES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES",
  13. \ref DES_XEX3 "DESX", GOST, HIGHT, IDEA, LEA, \ref LR "Luby-Rackoff", \ref Kalyna128 "Kalyna (128/256/512)",
  14. MARS, RC2, RC5, RC6, \ref SAFER_K "SAFER-K", \ref SAFER_SK "SAFER-SK", SEED, Serpent,
  15. \ref SHACAL2 "SHACAL-2", SHARK, \ref SIMECK64 "SIMECK (32/64)" SKIPJACK, SM4, Square, TEA,
  16. \ref ThreeWay "3-Way", \ref Threefish256 "Threefish (256/512/1024)", Twofish, XTEA
  17. <dt>Stream Ciphers<dd>
  18. \ref ChaCha "ChaCha (8/12/20)", \ref HC128 "HC-128/256", \ref Panama "Panama-LE", \ref Panama "Panama-BE",
  19. Rabbit, Salsa20, \ref SEAL "SEAL-LE", \ref SEAL "SEAL-BE", WAKE, XSalsa20
  20. <dt>Hash Functions<dd>
  21. BLAKE2s, BLAKE2b, \ref Keccak "Keccak (F1600)", SHA1, SHA224, SHA256, SHA384, SHA512,
  22. \ref SHA3 "SHA-3", SM3, LSH (256/512), Tiger, RIPEMD160, RIPEMD256, SipHash, Whirlpool,
  23. Weak::MD2, Weak::MD4, Weak::MD5
  24. <dt>Non-Cryptographic Checksums<dd>
  25. CRC32, CRC32C, Adler32
  26. <dt>Message Authentication Codes<dd>
  27. BLAKE2b, BLAKE2s, CBC_MAC, CMAC, DMAC, \ref GCM "GCM (GMAC)", HMAC, Poly1305, TTMAC, VMAC
  28. <dt>Random Number Generators<dd>
  29. NullRNG, LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG,
  30. NIST Hash_DRBG and HMAC_DRBG, \ref MersenneTwister "MersenneTwister (MT19937 and MT19937-AR)",
  31. DARN, RDRAND, RDSEED
  32. <dt>Key Derivation and Password-based Cryptography<dd>
  33. HKDF, \ref PKCS12_PBKDF "PBKDF (PKCS #12)", \ref PKCS5_PBKDF1 "PBKDF-1 (PKCS #5)",
  34. \ref PKCS5_PBKDF2_HMAC "PBKDF-2/HMAC (PKCS #5)"
  35. <dt>Public Key Cryptosystems<dd>
  36. DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
  37. <dt>Public Key Signature Schemes<dd>
  38. DSA, DSA2, \ref ed25519 "Ed25519", GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO,
  39. RabinSS, RWSS, ESIGN
  40. <dt>Key Agreement<dd>
  41. DH, DH2, \ref x25519 "X25519", \ref MQV_Domain "MQV", \ref HMQV_Domain "HMQV",
  42. \ref FHMQV_Domain "FHMQV", ECDH, x25519, ECMQV, ECHMQV, ECFHMQV, XTR_DH
  43. <dt>Algebraic Structures<dd>
  44. Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
  45. ModularArithmetic, MontgomeryRepresentation, GFP2_ONB, GF2NP, GF256, GF2_32, EC2N, ECP
  46. <dt>Secret Sharing and Information Dispersal<dd>
  47. SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
  48. <dt>Compression<dd>
  49. Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
  50. <dt>Input Source Classes<dd>
  51. StringSource, ArraySource, VectorSource, FileSource, RandomNumberSource
  52. <dt>Output Sink Classes<dd>
  53. StringSinkTemplate, StringSink, VectorSink, ArraySink, FileSink, RandomNumberSink
  54. <dt>Filter Wrappers<dd>
  55. StreamTransformationFilter, AuthenticatedEncryptionFilter, AuthenticatedDecryptionFilter, HashFilter,
  56. HashVerificationFilter, SignerFilter, SignatureVerificationFilter
  57. <dt>Binary to Text Encoders and Decoders<dd>
  58. HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base64URLEncoder, Base64URLDecoder, Base32Encoder,
  59. Base32Decoder
  60. <dt>Wrappers for OS features<dd>
  61. Timer, ThreadUserTimer
  62. </dl>
  63. <!--
  64. <dt>FIPS 140 validated cryptography<dd>
  65. fips140.h
  66. In the DLL version of Crypto++, only the following implementation class are available.
  67. <dl>
  68. <dt>Block Ciphers<dd>
  69. AES, \ref DES_EDE2 "2-key Triple-DES", \ref DES_EDE3 "3-key Triple-DES", SKIPJACK
  70. <dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
  71. \ref ECB_Mode "ECB_Mode<BC>", \ref CTR_Mode "CTR_Mode<BC>", \ref CBC_Mode "CBC_Mode<BC>",
  72. \ref CFB_FIPS_Mode "CFB_FIPS_Mode<BC>", \ref OFB_Mode "OFB_Mode<BC>", \ref GCM "GCM<AES>"
  73. <dt>Hash Functions<dd>
  74. SHA1, SHA224, SHA256, SHA384, SHA512
  75. <dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
  76. RSASS\<PKCS1v15, H\>, RSASS\<PSS, H\>, RSASS_ISO\<H\>, RWSS\<P1363_EMSA2, H\>, DSA, ECDSA\<ECP, H\>,
  77. ECDSA\<EC2N, H\>
  78. <dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
  79. HMAC\<H\>, CBC_MAC\<DES_EDE2\>, CBC_MAC\<DES_EDE3\>, GCM\<AES\>
  80. <dt>Random Number Generators<dd>
  81. DefaultAutoSeededRNG (AutoSeededX917RNG\<AES\>)
  82. <dt>Key Agreement<dd>
  83. DH, DH2
  84. <dt>Public Key Cryptosystems<dd>
  85. RSAES\<OAEP\<SHA1\> \>
  86. </dl>
  87. -->
  88. <p>This reference manual is a work in progress. Some classes lack detailed descriptions.
  89. <p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
  90. <p>Thanks to Ryan Phillips for providing the Doxygen configuration file
  91. and getting us started on the manual.
  92. */
  93. #ifndef CRYPTOPP_CRYPTLIB_H
  94. #define CRYPTOPP_CRYPTLIB_H
  95. #include "config.h"
  96. #include "stdcpp.h"
  97. #include "trap.h"
  98. // C5264 new for VS2022/v17.4, MSC v17.3.4
  99. // https://github.com/weidai11/cryptopp/issues/1185
  100. #if CRYPTOPP_MSC_VERSION
  101. # pragma warning(push)
  102. # pragma warning(disable: 4127 4189 4505 4702)
  103. # if (CRYPTOPP_MSC_VERSION >= 1933)
  104. # pragma warning(disable: 5264)
  105. # endif
  106. #endif
  107. NAMESPACE_BEGIN(CryptoPP)
  108. // forward declarations
  109. class Integer;
  110. class RandomNumberGenerator;
  111. class BufferedTransformation;
  112. /// \brief Specifies a direction for a cipher to operate
  113. /// \sa BlockTransformation::IsForwardTransformation(), BlockTransformation::IsPermutation(), BlockTransformation::GetCipherDirection()
  114. enum CipherDir {
  115. /// \brief the cipher is performing encryption
  116. ENCRYPTION,
  117. /// \brief the cipher is performing decryption
  118. DECRYPTION};
  119. /// \brief Represents infinite time
  120. CRYPTOPP_CONST_OR_CONSTEXPR unsigned long INFINITE_TIME = ULONG_MAX;
  121. // VC60 workaround: using enums as template parameters causes problems
  122. /// \brief Converts an enumeration to a type suitable for use as a template parameter
  123. template <typename ENUM_TYPE, int VALUE>
  124. struct EnumToType
  125. {
  126. static ENUM_TYPE ToEnum() {return static_cast<ENUM_TYPE>(VALUE);}
  127. };
  128. /// \brief Provides the byte ordering
  129. /// \details Big-endian and little-endian modes are supported. Bi-endian and PDP-endian modes
  130. /// are not supported.
  131. enum ByteOrder {
  132. /// \brief byte order is little-endian
  133. LITTLE_ENDIAN_ORDER = 0,
  134. /// \brief byte order is big-endian
  135. BIG_ENDIAN_ORDER = 1};
  136. /// \brief Provides a constant for LittleEndian
  137. typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian;
  138. /// \brief Provides a constant for BigEndian
  139. typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian;
  140. /// \brief Base class for all exceptions thrown by the library
  141. /// \details All library exceptions directly or indirectly inherit from the Exception class.
  142. /// The Exception class itself inherits from std::exception. The library does not use
  143. /// std::runtime_error derived classes.
  144. class CRYPTOPP_DLL Exception : public std::exception
  145. {
  146. public:
  147. /// \enum ErrorType
  148. /// \brief Error types or categories
  149. enum ErrorType {
  150. /// \brief A method was called which was not implemented
  151. NOT_IMPLEMENTED,
  152. /// \brief An invalid argument was detected
  153. INVALID_ARGUMENT,
  154. /// \brief BufferedTransformation received a Flush(true) signal but can't flush buffers
  155. CANNOT_FLUSH,
  156. /// \brief Data integerity check, such as CRC or MAC, failed
  157. DATA_INTEGRITY_CHECK_FAILED,
  158. /// \brief Input data was received that did not conform to expected format
  159. INVALID_DATA_FORMAT,
  160. /// \brief Error reading from input device or writing to output device
  161. IO_ERROR,
  162. /// \brief Some other error occurred not belonging to other categories
  163. OTHER_ERROR
  164. };
  165. virtual ~Exception() throw() {}
  166. /// \brief Construct a new Exception
  167. explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
  168. /// \brief Retrieves a C-string describing the exception
  169. const char *what() const throw() {return (m_what.c_str());}
  170. /// \brief Retrieves a string describing the exception
  171. const std::string &GetWhat() const {return m_what;}
  172. /// \brief Sets the error string for the exception
  173. void SetWhat(const std::string &s) {m_what = s;}
  174. /// \brief Retrieves the error type for the exception
  175. ErrorType GetErrorType() const {return m_errorType;}
  176. /// \brief Sets the error type for the exceptions
  177. void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
  178. private:
  179. ErrorType m_errorType;
  180. std::string m_what;
  181. };
  182. /// \brief An invalid argument was detected
  183. class CRYPTOPP_DLL InvalidArgument : public Exception
  184. {
  185. public:
  186. /// \brief Construct an InvalidArgument
  187. /// \param s the message for the exception
  188. /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
  189. explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
  190. };
  191. /// \brief Input data was received that did not conform to expected format
  192. class CRYPTOPP_DLL InvalidDataFormat : public Exception
  193. {
  194. public:
  195. /// \brief Construct an InvalidDataFormat
  196. /// \param s the message for the exception
  197. /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
  198. explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
  199. };
  200. /// \brief A decryption filter encountered invalid ciphertext
  201. class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
  202. {
  203. public:
  204. /// \brief Construct an InvalidCiphertext
  205. /// \param s the message for the exception
  206. /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
  207. explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
  208. };
  209. /// \brief A method was called which was not implemented
  210. class CRYPTOPP_DLL NotImplemented : public Exception
  211. {
  212. public:
  213. /// \brief Construct an NotImplemented
  214. /// \param s the message for the exception
  215. /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
  216. explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
  217. };
  218. /// \brief Flush(true) was called but it can't completely flush its buffers
  219. class CRYPTOPP_DLL CannotFlush : public Exception
  220. {
  221. public:
  222. /// \brief Construct an CannotFlush
  223. /// \param s the message for the exception
  224. /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
  225. explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
  226. };
  227. /// \brief The operating system reported an error
  228. class CRYPTOPP_DLL OS_Error : public Exception
  229. {
  230. public:
  231. virtual ~OS_Error() throw() {}
  232. /// \brief Construct an OS_Error
  233. /// \param errorType the error type
  234. /// \param s the message for the exception
  235. /// \param operation the operation for the exception
  236. /// \param errorCode the error code
  237. /// \details The member function <tt>what()</tt> returns <tt>s</tt>.
  238. OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
  239. : Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
  240. /// \brief Retrieve the operating system API that reported the error
  241. const std::string & GetOperation() const {return m_operation;}
  242. /// \brief Retrieve the error code returned by the operating system
  243. int GetErrorCode() const {return m_errorCode;}
  244. protected:
  245. std::string m_operation;
  246. int m_errorCode;
  247. };
  248. /// \brief Returns a decoding results
  249. struct CRYPTOPP_DLL DecodingResult
  250. {
  251. /// \brief Constructs a DecodingResult
  252. /// \details isValidCoding is initialized to false and messageLength is
  253. /// initialized to 0.
  254. explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
  255. /// \brief Constructs a DecodingResult
  256. /// \param len the message length
  257. /// \details isValidCoding is initialized to true.
  258. explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
  259. /// \brief Compare two DecodingResult
  260. /// \param rhs the other DecodingResult
  261. /// \return true if either isValidCoding or messageLength is \a not equal,
  262. /// false otherwise
  263. bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
  264. /// \brief Compare two DecodingResult
  265. /// \param rhs the other DecodingResult
  266. /// \return true if either isValidCoding or messageLength is \a not equal,
  267. /// false otherwise
  268. /// \details Returns <tt>!operator==(rhs)</tt>.
  269. bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
  270. /// \brief Flag to indicate the decoding is valid
  271. bool isValidCoding;
  272. /// \brief Recovered message length if isValidCoding is true, undefined otherwise
  273. size_t messageLength;
  274. };
  275. /// \brief Interface for retrieving values given their names
  276. /// \details This class is used to safely pass a variable number of arbitrarily
  277. /// typed arguments to functions and to read values from keys and crypto parameters.
  278. /// \details To obtain an object that implements NameValuePairs for the purpose of
  279. /// parameter passing, use the MakeParameters() function.
  280. /// \details To get a value from NameValuePairs, you need to know the name and the
  281. /// type of the value. Call GetValueNames() on a NameValuePairs object to obtain a
  282. /// list of value names that it supports. then look at the Name namespace
  283. /// documentation to see what the type of each value is, or alternatively, call
  284. /// GetIntValue() with the value name, and if the type is not int, a
  285. /// ValueTypeMismatch exception will be thrown and you can get the actual type from
  286. /// the exception object.
  287. /// \sa NullNameValuePairs, g_nullNameValuePairs,
  288. /// <A HREF="http://www.cryptopp.com/wiki/NameValuePairs">NameValuePairs</A> on the
  289. /// Crypto++ wiki
  290. class NameValuePairs
  291. {
  292. public:
  293. virtual ~NameValuePairs() {}
  294. /// \brief Thrown when an unexpected type is encountered
  295. /// \details Exception thrown when trying to retrieve a value using a different
  296. /// type than expected
  297. class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
  298. {
  299. public:
  300. /// \brief Construct a ValueTypeMismatch
  301. /// \param name the name of the value
  302. /// \param stored the \a actual type of the value stored
  303. /// \param retrieving the \a presumed type of the value retrieved
  304. ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
  305. : InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
  306. , m_stored(stored), m_retrieving(retrieving) {}
  307. /// \brief Provides the stored type
  308. /// \return the C++ mangled name of the type
  309. const std::type_info & GetStoredTypeInfo() const {return m_stored;}
  310. /// \brief Provides the retrieveing type
  311. /// \return the C++ mangled name of the type
  312. const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
  313. private:
  314. const std::type_info &m_stored;
  315. const std::type_info &m_retrieving;
  316. };
  317. /// \brief Get a copy of this object or subobject
  318. /// \tparam T class or type
  319. /// \param object reference to a variable that receives the value
  320. template <class T>
  321. bool GetThisObject(T &object) const
  322. {
  323. return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
  324. }
  325. /// \brief Get a pointer to this object
  326. /// \tparam T class or type
  327. /// \param ptr reference to a pointer to a variable that receives the value
  328. template <class T>
  329. bool GetThisPointer(T *&ptr) const
  330. {
  331. return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), ptr);
  332. }
  333. /// \brief Get a named value
  334. /// \tparam T class or type
  335. /// \param name the name of the object or value to retrieve
  336. /// \param value reference to a variable that receives the value
  337. /// \return true if the value was retrieved, false otherwise
  338. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  339. /// GetRequiredParameter() and GetRequiredIntParameter()
  340. template <class T>
  341. bool GetValue(const char *name, T &value) const
  342. {
  343. return GetVoidValue(name, typeid(T), &value);
  344. }
  345. /// \brief Get a named value
  346. /// \tparam T class or type
  347. /// \param name the name of the object or value to retrieve
  348. /// \param defaultValue the default value of the class or type if it does not exist
  349. /// \return the object or value
  350. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  351. /// GetRequiredParameter() and GetRequiredIntParameter()
  352. template <class T>
  353. T GetValueWithDefault(const char *name, T defaultValue) const
  354. {
  355. T value;
  356. bool result = GetValue(name, value);
  357. // No assert... this recovers from failure
  358. if (result) {return value;}
  359. return defaultValue;
  360. }
  361. /// \brief Get a list of value names that can be retrieved
  362. /// \return a list of names available to retrieve
  363. /// \details the items in the list are delimited with a colon.
  364. CRYPTOPP_DLL std::string GetValueNames() const
  365. {std::string result; GetValue("ValueNames", result); return result;}
  366. /// \brief Get a named value with type int
  367. /// \param name the name of the value to retrieve
  368. /// \param value the value retrieved upon success
  369. /// \return true if an int value was retrieved, false otherwise
  370. /// \details GetIntValue() is used to ensure we don't accidentally try to get an
  371. /// unsigned int or some other type when we mean int (which is the most common case)
  372. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  373. /// GetRequiredParameter() and GetRequiredIntParameter()
  374. CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
  375. {return GetValue(name, value);}
  376. /// \brief Get a named value with type int, with default
  377. /// \param name the name of the value to retrieve
  378. /// \param defaultValue the default value if the name does not exist
  379. /// \return the value retrieved on success or the default value
  380. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  381. /// GetRequiredParameter() and GetRequiredIntParameter()
  382. CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
  383. {return GetValueWithDefault(name, defaultValue);}
  384. /// \brief Get a named value with type word64
  385. /// \param name the name of the value to retrieve
  386. /// \param value the value retrieved upon success
  387. /// \return true if an word64 value was retrieved, false otherwise
  388. /// \sa GetValue(), GetValueWithDefault(), GetWord64ValueWithDefault(), GetIntValue(),
  389. /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredIntParameter()
  390. CRYPTOPP_DLL bool GetWord64Value(const char *name, word64 &value) const
  391. {return GetValue(name, value);}
  392. /// \brief Get a named value with type word64, with default
  393. /// \param name the name of the value to retrieve
  394. /// \param defaultValue the default value if the name does not exist
  395. /// \return the value retrieved on success or the default value
  396. /// \sa GetValue(), GetValueWithDefault(), GetWord64Value(), GetIntValue(),
  397. /// GetIntValueWithDefault(), GetRequiredParameter() and GetRequiredWord64Parameter()
  398. CRYPTOPP_DLL word64 GetWord64ValueWithDefault(const char *name, word64 defaultValue) const
  399. {return GetValueWithDefault(name, defaultValue);}
  400. /// \brief Ensures an expected name and type is present
  401. /// \param name the name of the value
  402. /// \param stored the type that was stored for the name
  403. /// \param retrieving the type that is being retrieved for the name
  404. /// \throw ValueTypeMismatch
  405. /// \details ThrowIfTypeMismatch() effectively performs a type safety check.
  406. /// stored and retrieving are C++ mangled names for the type.
  407. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  408. /// GetRequiredParameter() and GetRequiredIntParameter()
  409. CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
  410. {if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
  411. /// \brief Retrieves a required name/value pair
  412. /// \tparam T class or type
  413. /// \param className the name of the class
  414. /// \param name the name of the value
  415. /// \param value reference to a variable to receive the value
  416. /// \throw InvalidArgument
  417. /// \details GetRequiredParameter() throws InvalidArgument if the name
  418. /// is not present or not of the expected type T.
  419. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  420. /// GetRequiredParameter() and GetRequiredIntParameter()
  421. template <class T>
  422. void GetRequiredParameter(const char *className, const char *name, T &value) const
  423. {
  424. if (!GetValue(name, value))
  425. throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
  426. }
  427. /// \brief Retrieves a required name/value pair
  428. /// \param className the name of the class
  429. /// \param name the name of the value
  430. /// \param value reference to a variable to receive the value
  431. /// \throw InvalidArgument
  432. /// \details GetRequiredParameter() throws InvalidArgument if the name
  433. /// is not present or not of the expected type T.
  434. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  435. /// GetRequiredParameter() and GetRequiredIntParameter()
  436. CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
  437. {
  438. if (!GetIntValue(name, value))
  439. throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
  440. }
  441. /// \brief Get a named value
  442. /// \param name the name of the object or value to retrieve
  443. /// \param valueType reference to a variable that receives the value
  444. /// \param pValue void pointer to a variable that receives the value
  445. /// \return true if the value was retrieved, false otherwise
  446. /// \details GetVoidValue() retrieves the value of name if it exists.
  447. /// \note GetVoidValue() is an internal function and should be implemented
  448. /// by derived classes. Users should use one of the other functions instead.
  449. /// \sa GetValue(), GetValueWithDefault(), GetIntValue(), GetIntValueWithDefault(),
  450. /// GetRequiredParameter() and GetRequiredIntParameter()
  451. CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
  452. };
  453. // Doxygen cannot handle initialization
  454. #if CRYPTOPP_DOXYGEN_PROCESSING
  455. /// \brief Default channel for BufferedTransformation
  456. /// \details DEFAULT_CHANNEL is equal to an empty string
  457. /// \details The definition for DEFAULT_CHANNEL is in <tt>cryptlib.cpp</tt>.
  458. /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
  459. /// Initialization Order Fiasco</A>. If you experience a crash in
  460. /// DEFAULT_CHANNEL where the string object is NULL, then you probably have
  461. /// a global object using DEFAULT_CHANNEL before it has been constructed.
  462. const std::string DEFAULT_CHANNEL;
  463. /// \brief Channel for additional authenticated data
  464. /// \details AAD_CHANNEL is equal to "AAD"
  465. /// \details The definition for AAD_CHANNEL is in <tt>cryptlib.cpp</tt>.
  466. /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
  467. /// Initialization Order Fiasco</A>. If you experience a crash in
  468. /// AAD_CHANNEL where the string object is NULL, then you probably have a
  469. /// global object using AAD_CHANNEL before it has been constructed.
  470. const std::string AAD_CHANNEL;
  471. /// \brief An empty set of name-value pairs
  472. /// \details The definition for g_nullNameValuePairs is in <tt>cryptlib.cpp</tt>.
  473. /// It can be subject to <A HREF="https://isocpp.org/wiki/faq/ctors">Static
  474. /// Initialization Order Fiasco</A>. If you experience a crash in
  475. /// g_nullNameValuePairs where the string object is NULL, then you probably
  476. /// have a global object using g_nullNameValuePairs before it has been
  477. /// constructed.
  478. const NameValuePairs& g_nullNameValuePairs;
  479. #else
  480. extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
  481. extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
  482. extern CRYPTOPP_DLL const NameValuePairs& g_nullNameValuePairs;
  483. #endif
  484. // Document additional name spaces which show up elsewhere in the sources.
  485. #if CRYPTOPP_DOXYGEN_PROCESSING
  486. /// \brief Namespace containing value name definitions.
  487. /// \details Name is part of the CryptoPP namespace.
  488. /// \details The semantics of value names, types are:
  489. /// <pre>
  490. /// ThisObject:ClassName (ClassName, copy of this object or a subobject)
  491. /// ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
  492. /// </pre>
  493. DOCUMENTED_NAMESPACE_BEGIN(Name)
  494. // more names defined in argnames.h
  495. DOCUMENTED_NAMESPACE_END
  496. /// \brief Namespace containing weak and wounded algorithms.
  497. /// \details Weak is part of the CryptoPP namespace. Schemes and algorithms are moved into Weak
  498. /// when their security level is reduced to an unacceptable level by contemporary standards.
  499. /// \details To use an algorithm in the Weak namespace, you must <tt>\c \#define
  500. /// CRYPTOPP_ENABLE_NAMESPACE_WEAK 1</tt> before including a header for a weak or wounded
  501. /// algorithm. For example:
  502. /// <pre> \c \#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
  503. /// \c \#include <md5.h>
  504. /// ...
  505. /// CryptoPP::Weak::MD5 md5;
  506. /// </pre>
  507. DOCUMENTED_NAMESPACE_BEGIN(Weak)
  508. // weak and wounded algorithms
  509. DOCUMENTED_NAMESPACE_END
  510. #endif
  511. /// \brief Namespace containing NaCl library functions
  512. /// \details TweetNaCl is a compact and portable reimplementation of the NaCl library.
  513. DOCUMENTED_NAMESPACE_BEGIN(NaCl)
  514. // crypto_box, crypto_box_open, crypto_sign, and crypto_sign_open (and friends)
  515. DOCUMENTED_NAMESPACE_END
  516. /// \brief Namespace containing testing and benchmark classes.
  517. /// \details Source files for classes in the Test namespaces include
  518. /// <tt>test.cpp</tt>, <tt>validat#.cpp</tt> and <tt>bench#.cpp</tt>.
  519. DOCUMENTED_NAMESPACE_BEGIN(Test)
  520. // testing and benchmark classes
  521. DOCUMENTED_NAMESPACE_END
  522. // ********************************************************
  523. /// \brief Interface for cloning objects
  524. /// \note this is \a not implemented by most classes
  525. /// \sa ClonableImpl, NotCopyable
  526. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
  527. {
  528. public:
  529. virtual ~Clonable() {}
  530. /// \brief Copies this object
  531. /// \return a copy of this object
  532. /// \throw NotImplemented
  533. /// \note this is \a not implemented by most classes
  534. /// \sa NotCopyable
  535. virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
  536. };
  537. /// \brief Interface for all crypto algorithms
  538. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
  539. {
  540. public:
  541. virtual ~Algorithm() {}
  542. /// \brief Interface for all crypto algorithms
  543. /// \param checkSelfTestStatus determines whether the object can proceed if the self
  544. /// tests have not been run or failed.
  545. /// \details When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
  546. /// this constructor throws SelfTestFailure if the self test hasn't been run or fails.
  547. /// \details FIPS 140-2 compliance is disabled by default. It is only used by certain
  548. /// versions of the library when the library is built as a DLL on Windows. Also see
  549. /// CRYPTOPP_ENABLE_COMPLIANCE_WITH_FIPS_140_2 in config.h.
  550. Algorithm(bool checkSelfTestStatus = true);
  551. /// \brief Provides the name of this algorithm
  552. /// \return the standard algorithm name
  553. /// \details The standard algorithm name can be a name like <tt>AES</tt> or <tt>AES/GCM</tt>.
  554. /// Some algorithms do not have standard names yet. For example, there is no standard
  555. /// algorithm name for Shoup's ECIES.
  556. /// \note AlgorithmName is not universally implemented yet.
  557. virtual std::string AlgorithmName() const {return "unknown";}
  558. /// \brief Retrieve the provider of this algorithm
  559. /// \return the algorithm provider
  560. /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
  561. /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
  562. /// usually indicate a specialized implementation using instructions from a higher
  563. /// instruction set architecture (ISA). Future labels may include external hardware
  564. /// like a hardware security module (HSM).
  565. /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
  566. /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
  567. /// instead of ASM.
  568. /// \details Algorithms which combine different instructions or ISAs provide the
  569. /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
  570. /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
  571. /// \note Provider is not universally implemented yet.
  572. /// \since Crypto++ 8.0
  573. virtual std::string AlgorithmProvider() const {return "C++";}
  574. };
  575. /// \brief Interface for algorithms that take byte strings as keys
  576. /// \sa FixedKeyLength(), VariableKeyLength(), SameKeyLengthAs(), SimpleKeyingInterfaceImpl()
  577. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
  578. {
  579. public:
  580. virtual ~SimpleKeyingInterface() {}
  581. /// \brief Returns smallest valid key length
  582. /// \return the minimum key length, in bytes
  583. virtual size_t MinKeyLength() const =0;
  584. /// \brief Returns largest valid key length
  585. /// \return the maximum key length, in bytes
  586. virtual size_t MaxKeyLength() const =0;
  587. /// \brief Returns default key length
  588. /// \return the default key length, in bytes
  589. virtual size_t DefaultKeyLength() const =0;
  590. /// \brief Returns a valid key length for the algorithm
  591. /// \param keylength the size of the key, in bytes
  592. /// \return the valid key length, in bytes
  593. /// \details keylength is provided in bytes, not bits. If keylength is less than MIN_KEYLENGTH,
  594. /// then the function returns MIN_KEYLENGTH. If keylength is greater than MAX_KEYLENGTH,
  595. /// then the function returns MAX_KEYLENGTH. if If keylength is a multiple of KEYLENGTH_MULTIPLE,
  596. /// then keylength is returned. Otherwise, the function returns a \a lower multiple of
  597. /// KEYLENGTH_MULTIPLE.
  598. virtual size_t GetValidKeyLength(size_t keylength) const =0;
  599. /// \brief Returns whether keylength is a valid key length
  600. /// \param keylength the requested keylength
  601. /// \return true if keylength is valid, false otherwise
  602. /// \details Internally the function calls GetValidKeyLength()
  603. virtual bool IsValidKeyLength(size_t keylength) const
  604. {return keylength == GetValidKeyLength(keylength);}
  605. /// \brief Sets or reset the key of this object
  606. /// \param key the key to use when keying the object
  607. /// \param length the size of the key, in bytes
  608. /// \param params additional initialization parameters to configure this object
  609. virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params = g_nullNameValuePairs);
  610. /// \brief Sets or reset the key of this object
  611. /// \param key the key to use when keying the object
  612. /// \param length the size of the key, in bytes
  613. /// \param rounds the number of rounds to apply the transformation function,
  614. /// if applicable
  615. /// \details SetKeyWithRounds() calls SetKey() with a NameValuePairs
  616. /// object that only specifies rounds. rounds is an integer parameter,
  617. /// and <tt>-1</tt> means use the default number of rounds.
  618. void SetKeyWithRounds(const byte *key, size_t length, int rounds);
  619. /// \brief Sets or reset the key of this object
  620. /// \param key the key to use when keying the object
  621. /// \param length the size of the key, in bytes
  622. /// \param iv the initialization vector to use when keying the object
  623. /// \param ivLength the size of the iv, in bytes
  624. /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs
  625. /// that only specifies IV. The IV is a byte buffer with size ivLength.
  626. /// ivLength is an integer parameter, and <tt>-1</tt> means use IVSize().
  627. void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
  628. /// \brief Sets or reset the key of this object
  629. /// \param key the key to use when keying the object
  630. /// \param length the size of the key, in bytes
  631. /// \param iv the initialization vector to use when keying the object
  632. /// \details SetKeyWithIV() calls SetKey() with a NameValuePairs() object
  633. /// that only specifies iv. iv is a byte buffer, and it must have
  634. /// a size IVSize().
  635. void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
  636. {SetKeyWithIV(key, length, iv, IVSize());}
  637. /// \brief Secure IVs requirements as enumerated values.
  638. /// \details Provides secure IV requirements as a monotonically increasing enumerated values.
  639. /// Requirements can be compared using less than (&lt;) and greater than (&gt;). For example,
  640. /// <tt>UNIQUE_IV &lt; RANDOM_IV</tt> and <tt>UNPREDICTABLE_RANDOM_IV &gt; RANDOM_IV</tt>.
  641. /// \details Objects that use SimpleKeyingInterface do not support an optional IV. That is,
  642. /// an IV must be present or it must be absent. If you wish to support an optional IV then
  643. /// provide two classes - one with an IV and one without an IV.
  644. /// \sa IsResynchronizable(), CanUseRandomIVs(), CanUsePredictableIVs(), CanUseStructuredIVs()
  645. enum IV_Requirement {
  646. /// \brief The IV must be unique
  647. UNIQUE_IV = 0,
  648. /// \brief The IV must be random and possibly predictable
  649. RANDOM_IV,
  650. /// \brief The IV must be random and unpredictable
  651. UNPREDICTABLE_RANDOM_IV,
  652. /// \brief The IV is set by the object
  653. INTERNALLY_GENERATED_IV,
  654. /// \brief The object does not use an IV
  655. NOT_RESYNCHRONIZABLE
  656. };
  657. /// \brief Minimal requirement for secure IVs
  658. /// \return the secure IV requirement of the algorithm
  659. virtual IV_Requirement IVRequirement() const =0;
  660. /// \brief Determines if the object can be resynchronized
  661. /// \return true if the object can be resynchronized (i.e. supports initialization vectors), false otherwise
  662. /// \note If this function returns true, and no IV is passed to SetKey() and <tt>CanUseStructuredIVs()==true</tt>,
  663. /// an IV of all 0's will be assumed.
  664. bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
  665. /// \brief Determines if the object can use random IVs
  666. /// \return true if the object can use random IVs (in addition to ones returned by GetNextIV), false otherwise
  667. bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
  668. /// \brief Determines if the object can use random but possibly predictable IVs
  669. /// \return true if the object can use random but possibly predictable IVs (in addition to ones returned by
  670. /// GetNextIV), false otherwise
  671. bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
  672. /// \brief Determines if the object can use structured IVs
  673. /// \return true if the object can use structured IVs, false otherwise
  674. /// \details CanUseStructuredIVs() indicates whether the object can use structured IVs; for example a counter
  675. /// (in addition to ones returned by GetNextIV).
  676. bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
  677. /// \brief Returns length of the IV accepted by this object
  678. /// \return the size of an IV, in bytes
  679. /// \throw NotImplemented() if the object does not support resynchronization
  680. /// \details The default implementation throws NotImplemented
  681. virtual unsigned int IVSize() const
  682. {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
  683. /// \brief Provides the default size of an IV
  684. /// \return default length of IVs accepted by this object, in bytes
  685. unsigned int DefaultIVLength() const {return IVSize();}
  686. /// \brief Provides the minimum size of an IV
  687. /// \return minimal length of IVs accepted by this object, in bytes
  688. /// \throw NotImplemented() if the object does not support resynchronization
  689. virtual unsigned int MinIVLength() const {return IVSize();}
  690. /// \brief Provides the maximum size of an IV
  691. /// \return maximal length of IVs accepted by this object, in bytes
  692. /// \throw NotImplemented() if the object does not support resynchronization
  693. virtual unsigned int MaxIVLength() const {return IVSize();}
  694. /// \brief Resynchronize with an IV
  695. /// \param iv the initialization vector
  696. /// \param ivLength the size of the initialization vector, in bytes
  697. /// \details Resynchronize() resynchronizes with an IV provided by the caller. <tt>ivLength=-1</tt> means use IVSize().
  698. /// \throw NotImplemented() if the object does not support resynchronization
  699. virtual void Resynchronize(const byte *iv, int ivLength=-1) {
  700. CRYPTOPP_UNUSED(iv); CRYPTOPP_UNUSED(ivLength);
  701. throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");
  702. }
  703. /// \brief Retrieves a secure IV for the next message
  704. /// \param rng a RandomNumberGenerator to produce keying material
  705. /// \param iv a block of bytes to receive the IV
  706. /// \details The IV must be at least IVSize() in length.
  707. /// \details This method should be called after you finish encrypting one message and are ready
  708. /// to start the next one. After calling it, you must call SetKey() or Resynchronize().
  709. /// before using this object again.
  710. /// \details Internally, the base class implementation calls RandomNumberGenerator's GenerateBlock()
  711. /// \note This method is not implemented on decryption objects.
  712. virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv);
  713. protected:
  714. /// \brief Returns the base class Algorithm
  715. /// \return the base class Algorithm
  716. virtual const Algorithm & GetAlgorithm() const =0;
  717. /// \brief Sets the key for this object without performing parameter validation
  718. /// \param key a byte buffer used to key the cipher
  719. /// \param length the length of the byte buffer
  720. /// \param params additional parameters passed as NameValuePairs
  721. /// \details key must be at least DEFAULT_KEYLENGTH in length.
  722. virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs &params) =0;
  723. /// \brief Validates the key length
  724. /// \param length the size of the keying material, in bytes
  725. /// \throw InvalidKeyLength if the key length is invalid
  726. void ThrowIfInvalidKeyLength(size_t length);
  727. /// \brief Validates the object
  728. /// \throw InvalidArgument if the IV is present
  729. /// \details Internally, the default implementation calls IsResynchronizable() and throws
  730. /// InvalidArgument if the function returns true.
  731. /// \note called when no IV is passed
  732. void ThrowIfResynchronizable();
  733. /// \brief Validates the IV
  734. /// \param iv the IV with a length of IVSize, in bytes
  735. /// \throw InvalidArgument on failure
  736. /// \details Internally, the default implementation checks the iv. If iv is not NULL or nullptr,
  737. /// then the function succeeds. If iv is NULL, then IVRequirement is checked against
  738. /// UNPREDICTABLE_RANDOM_IV. If IVRequirement is UNPREDICTABLE_RANDOM_IV, then
  739. /// then the function succeeds. Otherwise, an exception is thrown.
  740. void ThrowIfInvalidIV(const byte *iv);
  741. /// \brief Validates the IV length
  742. /// \param length the size of an IV, in bytes
  743. /// \throw InvalidArgument if the IV length is invalid
  744. size_t ThrowIfInvalidIVLength(int length);
  745. /// \brief Retrieves and validates the IV
  746. /// \param params NameValuePairs with the IV supplied as a ConstByteArrayParameter
  747. /// \param size the length of the IV, in bytes
  748. /// \return a pointer to the first byte of the IV
  749. /// \throw InvalidArgument if the number of rounds are invalid
  750. const byte * GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size);
  751. /// \brief Validates the key length
  752. /// \param length the size of the keying material, in bytes
  753. inline void AssertValidKeyLength(size_t length) const
  754. {CRYPTOPP_UNUSED(length); CRYPTOPP_ASSERT(IsValidKeyLength(length));}
  755. };
  756. /// \brief Interface for the data processing part of block ciphers
  757. /// \details Classes derived from BlockTransformation are block ciphers
  758. /// in ECB mode (for example the DES::Encryption class), which are stateless.
  759. /// These classes should not be used directly, but only in combination with
  760. /// a mode class (see CipherModeDocumentation in modes.h).
  761. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
  762. {
  763. public:
  764. virtual ~BlockTransformation() {}
  765. /// \brief Encrypt or decrypt a block
  766. /// \param inBlock the input message before processing
  767. /// \param outBlock the output message after processing
  768. /// \param xorBlock an optional XOR mask
  769. /// \details ProcessAndXorBlock encrypts or decrypts inBlock, xor with xorBlock, and write to outBlock.
  770. /// \details The size of the block is determined by the block cipher and its documentation. Use
  771. /// BLOCKSIZE at compile time, or BlockSize() at runtime.
  772. /// \note The message can be transformed in-place, or the buffers must \a not overlap
  773. /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
  774. virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
  775. /// \brief Encrypt or decrypt a block
  776. /// \param inBlock the input message before processing
  777. /// \param outBlock the output message after processing
  778. /// \details ProcessBlock encrypts or decrypts inBlock and write to outBlock.
  779. /// \details The size of the block is determined by the block cipher and its documentation.
  780. /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
  781. /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
  782. /// \note The message can be transformed in-place, or the buffers must \a not overlap
  783. void ProcessBlock(const byte *inBlock, byte *outBlock) const
  784. {ProcessAndXorBlock(inBlock, NULLPTR, outBlock);}
  785. /// \brief Encrypt or decrypt a block in place
  786. /// \param inoutBlock the input message before processing
  787. /// \details ProcessBlock encrypts or decrypts inoutBlock in-place.
  788. /// \details The size of the block is determined by the block cipher and its documentation.
  789. /// Use BLOCKSIZE at compile time, or BlockSize() at runtime.
  790. /// \sa FixedBlockSize, BlockCipherFinal from seckey.h and BlockSize()
  791. void ProcessBlock(byte *inoutBlock) const
  792. {ProcessAndXorBlock(inoutBlock, NULLPTR, inoutBlock);}
  793. /// Provides the block size of the cipher
  794. /// \return the block size of the cipher, in bytes
  795. virtual unsigned int BlockSize() const =0;
  796. /// \brief Provides input and output data alignment for optimal performance.
  797. /// \return the input data alignment that provides optimal performance
  798. /// \sa GetAlignment() and OptimalBlockSize()
  799. virtual unsigned int OptimalDataAlignment() const;
  800. /// \brief Determines if the transformation is a permutation
  801. /// \return true if this is a permutation (i.e. there is an inverse transformation)
  802. virtual bool IsPermutation() const {return true;}
  803. /// \brief Determines if the cipher is being operated in its forward direction
  804. /// \return true if DIR is ENCRYPTION, false otherwise
  805. /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
  806. virtual bool IsForwardTransformation() const =0;
  807. /// \brief Determines the number of blocks that can be processed in parallel
  808. /// \return the number of blocks that can be processed in parallel, for bit-slicing implementations
  809. /// \details Bit-slicing is often used to improve throughput and minimize timing attacks.
  810. virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
  811. /// \brief Bit flags that control AdvancedProcessBlocks() behavior
  812. enum FlagsForAdvancedProcessBlocks {
  813. /// \brief inBlock is a counter
  814. BT_InBlockIsCounter=1,
  815. /// \brief should not modify block pointers
  816. BT_DontIncrementInOutPointers=2,
  817. /// \brief Xor inputs before transformation
  818. BT_XorInput=4,
  819. /// \brief perform the transformation in reverse
  820. BT_ReverseDirection=8,
  821. /// \brief Allow parallel transformations
  822. BT_AllowParallel=16};
  823. /// \brief Encrypt and xor multiple blocks using additional flags
  824. /// \param inBlocks the input message before processing
  825. /// \param xorBlocks an optional XOR mask
  826. /// \param outBlocks the output message after processing
  827. /// \param length the size of the blocks, in bytes
  828. /// \param flags additional flags to control processing
  829. /// \details Encrypt and xor multiple blocks according to FlagsForAdvancedProcessBlocks flags.
  830. /// \note If BT_InBlockIsCounter is set, then the last byte of inBlocks may be modified.
  831. virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
  832. /// \brief Provides the direction of the cipher
  833. /// \return ENCRYPTION if IsForwardTransformation() is true, DECRYPTION otherwise
  834. /// \sa IsForwardTransformation(), IsPermutation()
  835. inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
  836. };
  837. /// \brief Interface for the data processing portion of stream ciphers
  838. /// \sa StreamTransformationFilter()
  839. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
  840. {
  841. public:
  842. virtual ~StreamTransformation() {}
  843. /// \brief Provides a reference to this object
  844. /// \return A reference to this object
  845. /// \details Useful for passing a temporary object to a function that takes a non-const reference
  846. StreamTransformation& Ref() {return *this;}
  847. /// \brief Provides the mandatory block size of the cipher
  848. /// \return The block size of the cipher if input must be processed in blocks, 1 otherwise
  849. /// \details Stream ciphers and some block ciphers modes of operation return 1. Modes that
  850. /// return 1 must be able to process a single byte at a time, like counter mode. If a
  851. /// mode of operation or block cipher cannot stream then it must not return 1.
  852. /// \details When filters operate the mode or cipher, ProcessData will be called with a
  853. /// string of bytes that is determined by MandatoryBlockSize and OptimalBlockSize. When a
  854. /// policy is set, like 16-byte strings for a 16-byte block cipher, the filter will buffer
  855. /// bytes until the specified number of bytes is available to the object.
  856. /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
  857. virtual unsigned int MandatoryBlockSize() const {return 1;}
  858. /// \brief Provides the input block size most efficient for this cipher
  859. /// \return The input block size that is most efficient for the cipher
  860. /// \details The base class implementation returns MandatoryBlockSize().
  861. /// \note Optimal input length is
  862. /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>.
  863. virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
  864. /// \brief Provides the number of bytes used in the current block when processing at optimal block size.
  865. /// \return the number of bytes used in the current block when processing at the optimal block size
  866. virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
  867. /// \brief Provides input and output data alignment for optimal performance
  868. /// \return the input data alignment that provides optimal performance
  869. /// \sa GetAlignment() and OptimalBlockSize()
  870. virtual unsigned int OptimalDataAlignment() const;
  871. /// \brief Encrypt or decrypt an array of bytes
  872. /// \param outString the output byte buffer
  873. /// \param inString the input byte buffer
  874. /// \param length the size of the input and output byte buffers, in bytes
  875. /// \details ProcessData is called with a string of bytes whose size depends on MandatoryBlockSize.
  876. /// Either <tt>inString == outString</tt>, or they must not overlap.
  877. /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
  878. virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
  879. /// \brief Encrypt or decrypt the last block of data
  880. /// \param outString the output byte buffer
  881. /// \param outLength the size of the output byte buffer, in bytes
  882. /// \param inString the input byte buffer
  883. /// \param inLength the size of the input byte buffer, in bytes
  884. /// \return the number of bytes used in outString
  885. /// \details ProcessLastBlock is used when the last block of data is special and requires handling
  886. /// by the cipher. The current implementation provides an output buffer with a size
  887. /// <tt>inLength+2*MandatoryBlockSize()</tt>. The return value allows the cipher to expand cipher
  888. /// text during encryption or shrink plain text during decryption.
  889. /// \details This member function is used by CBC-CTS and OCB modes.
  890. /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
  891. virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength);
  892. /// \brief Provides the size of the last block
  893. /// \return the minimum size of the last block
  894. /// \details MinLastBlockSize() returns the minimum size of the last block. 0 indicates the last
  895. /// block is not special.
  896. /// \details MandatoryBlockSize() enlists one of two behaviors. First, if MandatoryBlockSize()
  897. /// returns 1, then the cipher can be streamed and ProcessData() is called with the tail bytes.
  898. /// Second, if MandatoryBlockSize() returns non-0, then the string of bytes is padded to
  899. /// MandatoryBlockSize() according to the padding mode. Then, ProcessData() is called with the
  900. /// padded string of bytes.
  901. /// \details Some authenticated encryption modes are not expressed well with MandatoryBlockSize()
  902. /// and MinLastBlockSize(). For example, AES/OCB uses 16-byte blocks (MandatoryBlockSize = 16)
  903. /// and the last block requires special processing (MinLastBlockSize = 0). However, 0 is a valid
  904. /// last block size for OCB and the special processing is custom padding, and not standard PKCS
  905. /// padding. In response an unambiguous IsLastBlockSpecial() was added.
  906. /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
  907. virtual unsigned int MinLastBlockSize() const {return 0;}
  908. /// \brief Determines if the last block receives special processing
  909. /// \return true if the last block receives special processing, false otherwise.
  910. /// \details Some authenticated encryption modes are not expressed well with
  911. /// MandatoryBlockSize() and MinLastBlockSize(). For example, AES/OCB uses
  912. /// 16-byte blocks (MandatoryBlockSize = 16) and the last block requires special processing
  913. /// (MinLastBlockSize = 0). However, 0 is a valid last block size for OCB and the special
  914. /// processing is custom padding, and not standard PKCS padding. In response an
  915. /// unambiguous IsLastBlockSpecial() was added.
  916. /// \details When IsLastBlockSpecial() returns false nothing special happens. All the former
  917. /// rules and behaviors apply. This is the default behavior of IsLastBlockSpecial().
  918. /// \details When IsLastBlockSpecial() returns true four things happen. First, MinLastBlockSize = 0
  919. /// means 0 is a valid block size that should be processed. Second, standard block cipher padding is
  920. /// \a not \a applied. Third, the caller supplies an outString is larger than inString by
  921. /// <tt>2*MandatoryBlockSize()</tt>. That is, there's a reserve available when processing the last block.
  922. /// Fourth, the cipher is responsible for finalization like custom padding. The cipher will tell
  923. /// the library how many bytes were processed or used by returning the appropriate value from
  924. /// ProcessLastBlock().
  925. /// \details The return value of ProcessLastBlock() indicates how many bytes were written to
  926. /// <tt>outString</tt>. A filter pipelining data will send <tt>outString</tt> and up to <tt>outLength</tt>
  927. /// to an <tt>AttachedTransformation()</tt> for additional processing. Below is an example of the code
  928. /// used in <tt>StreamTransformationFilter::LastPut</tt>.
  929. /// <pre> if (m_cipher.IsLastBlockSpecial())
  930. /// {
  931. /// size_t reserve = 2*m_cipher.MandatoryBlockSize();
  932. /// space = HelpCreatePutSpace(*AttachedTransformation(), DEFAULT_CHANNEL, length+reserve);
  933. /// length = m_cipher.ProcessLastBlock(space, length+reserve, inString, length);
  934. /// AttachedTransformation()->Put(space, length);
  935. /// return;
  936. /// }</pre>
  937. /// \sa ProcessData, ProcessLastBlock, MandatoryBlockSize, MinLastBlockSize, BlockPaddingSchemeDef, IsLastBlockSpecial
  938. /// \since Crypto++ 6.0
  939. virtual bool IsLastBlockSpecial() const {return false;}
  940. /// \brief Encrypt or decrypt a string of bytes
  941. /// \param inoutString the string to process
  942. /// \param length the size of the inoutString, in bytes
  943. /// \details Internally, the base class implementation calls ProcessData().
  944. inline void ProcessString(byte *inoutString, size_t length)
  945. {ProcessData(inoutString, inoutString, length);}
  946. /// \brief Encrypt or decrypt a string of bytes
  947. /// \param outString the output string to process
  948. /// \param inString the input string to process
  949. /// \param length the size of the input and output strings, in bytes
  950. /// \details Internally, the base class implementation calls ProcessData().
  951. inline void ProcessString(byte *outString, const byte *inString, size_t length)
  952. {ProcessData(outString, inString, length);}
  953. /// \brief Encrypt or decrypt a byte
  954. /// \param input the input byte to process
  955. /// \details Internally, the base class implementation calls ProcessData() with a size of 1.
  956. inline byte ProcessByte(byte input)
  957. {ProcessData(&input, &input, 1); return input;}
  958. /// \brief Determines whether the cipher supports random access
  959. /// \return true if the cipher supports random access, false otherwise
  960. virtual bool IsRandomAccess() const =0;
  961. /// \brief Seek to an absolute position
  962. /// \param pos position to seek
  963. /// \throw NotImplemented
  964. /// \details The base class implementation throws NotImplemented. The function
  965. /// \ref CRYPTOPP_ASSERT "asserts" IsRandomAccess() in debug builds.
  966. virtual void Seek(lword pos)
  967. {
  968. CRYPTOPP_UNUSED(pos);
  969. CRYPTOPP_ASSERT(!IsRandomAccess());
  970. throw NotImplemented("StreamTransformation: this object doesn't support random access");
  971. }
  972. /// \brief Determines whether the cipher is self-inverting
  973. /// \return true if the cipher is self-inverting, false otherwise
  974. /// \details IsSelfInverting determines whether this transformation is
  975. /// self-inverting (e.g. xor with a keystream).
  976. virtual bool IsSelfInverting() const =0;
  977. /// \brief Determines if the cipher is being operated in its forward direction
  978. /// \return true if DIR is ENCRYPTION, false otherwise
  979. /// \sa IsForwardTransformation(), IsPermutation(), GetCipherDirection()
  980. virtual bool IsForwardTransformation() const =0;
  981. };
  982. /// \brief Interface for hash functions and data processing part of MACs
  983. /// \details HashTransformation objects are stateful. They are created in an initial state,
  984. /// change state as Update() is called, and return to the initial
  985. /// state when Final() is called. This interface allows a large message to
  986. /// be hashed in pieces by calling Update() on each piece followed by
  987. /// calling Final().
  988. /// \sa HashFilter(), HashVerificationFilter()
  989. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
  990. {
  991. public:
  992. virtual ~HashTransformation() {}
  993. /// \brief Provides a reference to this object
  994. /// \return A reference to this object
  995. /// \details Useful for passing a temporary object to a function that takes a non-const reference
  996. HashTransformation& Ref() {return *this;}
  997. /// \brief Updates a hash with additional input
  998. /// \param input the additional input as a buffer
  999. /// \param length the size of the buffer, in bytes
  1000. virtual void Update(const byte *input, size_t length) =0;
  1001. /// \brief Request space which can be written into by the caller
  1002. /// \param size the requested size of the buffer
  1003. /// \details The purpose of this method is to help avoid extra memory allocations.
  1004. /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
  1005. /// size is the requested size of the buffer. When the call returns, size is the size of
  1006. /// the array returned to the caller.
  1007. /// \details The base class implementation sets size to 0 and returns NULL or nullptr.
  1008. /// \note Some objects, like ArraySink, cannot create a space because its fixed.
  1009. virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULLPTR;}
  1010. /// \brief Computes the hash of the current message
  1011. /// \param digest a pointer to the buffer to receive the hash
  1012. /// \details Final() restarts the hash for a new message.
  1013. /// \pre <tt>COUNTOF(digest) <= DigestSize()</tt> or <tt>COUNTOF(digest) <= HASH::DIGESTSIZE</tt> ensures
  1014. /// the output byte buffer is large enough for the digest.
  1015. virtual void Final(byte *digest)
  1016. {TruncatedFinal(digest, DigestSize());}
  1017. /// \brief Restart the hash
  1018. /// \details Discards the current state, and restart for a new message
  1019. virtual void Restart()
  1020. {TruncatedFinal(NULLPTR, 0);}
  1021. /// Provides the digest size of the hash
  1022. /// \return the digest size of the hash.
  1023. virtual unsigned int DigestSize() const =0;
  1024. /// Provides the tag size of the hash
  1025. /// \return the tag size of the hash.
  1026. /// \details Same as DigestSize().
  1027. unsigned int TagSize() const {return DigestSize();}
  1028. /// \brief Provides the block size of the compression function
  1029. /// \return block size of the compression function, in bytes
  1030. /// \details BlockSize() will return 0 if the hash is not block based
  1031. /// or does not have an equivalent block size. For example, Keccak
  1032. /// and SHA-3 do not have a block size, but they do have an equivalent
  1033. /// block size called rate expressed as <tt>r</tt>.
  1034. virtual unsigned int BlockSize() const {return 0;}
  1035. /// \brief Provides the input block size most efficient for this hash.
  1036. /// \return The input block size that is most efficient for the cipher
  1037. /// \details The base class implementation returns MandatoryBlockSize().
  1038. /// \details Optimal input length is
  1039. /// <tt>n * OptimalBlockSize() - GetOptimalBlockSizeUsed()</tt> for any <tt>n \> 0</tt>.
  1040. virtual unsigned int OptimalBlockSize() const {return 1;}
  1041. /// \brief Provides input and output data alignment for optimal performance
  1042. /// \return the input data alignment that provides optimal performance
  1043. /// \sa GetAlignment() and OptimalBlockSize()
  1044. virtual unsigned int OptimalDataAlignment() const;
  1045. /// \brief Updates the hash with additional input and computes the hash of the current message
  1046. /// \param digest a pointer to the buffer to receive the hash
  1047. /// \param input the additional input as a buffer
  1048. /// \param length the size of the buffer, in bytes
  1049. /// \details Use this if your input is in one piece and you don't want to call Update()
  1050. /// and Final() separately
  1051. /// \details CalculateDigest() restarts the hash for the next message.
  1052. /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
  1053. /// the output byte buffer is a valid size.
  1054. virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
  1055. {Update(input, length); Final(digest);}
  1056. /// \brief Verifies the hash of the current message
  1057. /// \param digest a pointer to the buffer of an \a existing hash
  1058. /// \return \p true if the existing hash matches the computed hash, \p false otherwise
  1059. /// \throw InvalidArgument() if the existing hash's size exceeds DigestSize()
  1060. /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
  1061. /// a constant time comparison function. digestLength cannot exceed DigestSize().
  1062. /// \details Verify() restarts the hash for the next message.
  1063. /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
  1064. /// the input byte buffer is a valid size.
  1065. virtual bool Verify(const byte *digest)
  1066. {return TruncatedVerify(digest, DigestSize());}
  1067. /// \brief Updates the hash with additional input and verifies the hash of the current message
  1068. /// \param digest a pointer to the buffer of an \a existing hash
  1069. /// \param input the additional input as a buffer
  1070. /// \param length the size of the buffer, in bytes
  1071. /// \return \p true if the existing hash matches the computed hash, \p false otherwise
  1072. /// \throw InvalidArgument() if the existing hash's size exceeds DigestSize()
  1073. /// \details Use this if your input is in one piece and you don't want to call Update()
  1074. /// and Verify() separately
  1075. /// \details VerifyDigest() performs a bitwise compare on the buffers using VerifyBufsEqual(),
  1076. /// which is a constant time comparison function.
  1077. /// \details VerifyDigest() restarts the hash for the next message.
  1078. /// \pre <tt>COUNTOF(digest) == DigestSize()</tt> or <tt>COUNTOF(digest) == HASH::DIGESTSIZE</tt> ensures
  1079. /// the output byte buffer is a valid size.
  1080. virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
  1081. {Update(input, length); return Verify(digest);}
  1082. /// \brief Computes the hash of the current message
  1083. /// \param digest a pointer to the buffer to receive the hash
  1084. /// \param digestSize the size of the truncated digest, in bytes
  1085. /// \details TruncatedFinal() calls Final() and then copies digestSize bytes to digest.
  1086. /// The hash is restarted the hash for the next message.
  1087. /// \pre <tt>COUNTOF(digest) <= DigestSize()</tt> or <tt>COUNTOF(digest) <= HASH::DIGESTSIZE</tt> ensures
  1088. /// the output byte buffer is a valid size.
  1089. virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
  1090. /// \brief Updates the hash with additional input and computes the hash of the current message
  1091. /// \param digest a pointer to the buffer to receive the hash
  1092. /// \param digestSize the length of the truncated hash, in bytes
  1093. /// \param input the additional input as a buffer
  1094. /// \param length the size of the buffer, in bytes
  1095. /// \details Use this if your input is in one piece and you don't want to call Update()
  1096. /// and CalculateDigest() separately.
  1097. /// \details CalculateTruncatedDigest() restarts the hash for the next message.
  1098. /// \pre <tt>digestSize <= DigestSize()</tt> or <tt>digestSize <= HASH::DIGESTSIZE</tt> ensures
  1099. /// the output byte buffer is a valid size.
  1100. virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
  1101. {Update(input, length); TruncatedFinal(digest, digestSize);}
  1102. /// \brief Verifies the hash of the current message
  1103. /// \param digest a pointer to the buffer of an \a existing hash
  1104. /// \param digestLength the size of the truncated hash, in bytes
  1105. /// \return \p true if the existing hash matches the computed hash, \p false otherwise
  1106. /// \throw InvalidArgument() if digestLength exceeds DigestSize()
  1107. /// \details TruncatedVerify() is a truncated version of Verify(). It can operate on a
  1108. /// buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
  1109. /// \details Verify() performs a bitwise compare on the buffers using VerifyBufsEqual(), which is
  1110. /// a constant time comparison function. digestLength cannot exceed DigestSize().
  1111. /// \details TruncatedVerify() restarts the hash for the next message.
  1112. /// \pre <tt>digestLength <= DigestSize()</tt> or <tt>digestLength <= HASH::DIGESTSIZE</tt> ensures
  1113. /// the input byte buffer is a valid size.
  1114. virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
  1115. /// \brief Updates the hash with additional input and verifies the hash of the current message
  1116. /// \param digest a pointer to the buffer of an \a existing hash
  1117. /// \param digestLength the size of the truncated hash, in bytes
  1118. /// \param input the additional input as a buffer
  1119. /// \param length the size of the buffer, in bytes
  1120. /// \return \p true if the existing hash matches the computed hash, \p false otherwise
  1121. /// \throw InvalidArgument() if digestLength exceeds DigestSize()
  1122. /// \details Use this if your input is in one piece and you don't want to call Update()
  1123. /// and TruncatedVerify() separately.
  1124. /// \details VerifyTruncatedDigest() is a truncated version of VerifyDigest(). It can operate
  1125. /// on a buffer smaller than DigestSize(). However, digestLength cannot exceed DigestSize().
  1126. /// \details VerifyTruncatedDigest() restarts the hash for the next message.
  1127. /// \pre <tt>digestLength <= DigestSize()</tt> or <tt>digestLength <= HASH::DIGESTSIZE</tt> ensures
  1128. /// the input byte buffer is a valid size.
  1129. virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
  1130. {Update(input, length); return TruncatedVerify(digest, digestLength);}
  1131. protected:
  1132. /// \brief Validates a truncated digest size
  1133. /// \param size the requested digest size
  1134. /// \throw InvalidArgument if the algorithm's digest size cannot be truncated to the requested size
  1135. /// \details Throws an exception when the truncated digest size is greater than DigestSize()
  1136. void ThrowIfInvalidTruncatedSize(size_t size) const;
  1137. };
  1138. /// \brief Interface for one direction (encryption or decryption) of a block cipher
  1139. /// \details These objects usually should not be used directly. See BlockTransformation for more details.
  1140. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
  1141. {
  1142. protected:
  1143. const Algorithm & GetAlgorithm() const {return *this;}
  1144. };
  1145. /// \brief Interface for one direction (encryption or decryption) of a stream cipher or cipher mode
  1146. /// \details These objects usually should not be used directly. See StreamTransformation for more details.
  1147. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
  1148. {
  1149. protected:
  1150. const Algorithm & GetAlgorithm() const {return *this;}
  1151. };
  1152. /// \brief Interface for message authentication codes
  1153. /// \details These objects usually should not be used directly. See HashTransformation for more details.
  1154. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
  1155. {
  1156. protected:
  1157. const Algorithm & GetAlgorithm() const {return *this;}
  1158. };
  1159. /// \brief Interface for authenticated encryption modes of operation
  1160. /// \details AuthenticatedSymmetricCipher() provides the interface for one direction
  1161. /// (encryption or decryption) of a stream cipher or block cipher mode with authentication. The
  1162. /// StreamTransformation() part of this interface is used to encrypt or decrypt the data. The
  1163. /// MessageAuthenticationCode() part of the interface is used to input additional authenticated
  1164. /// data (AAD), which is MAC'ed but not encrypted. The MessageAuthenticationCode() part is also
  1165. /// used to generate and verify the MAC.
  1166. /// \details Crypto++ provides four authenticated encryption modes of operation - CCM, EAX, GCM
  1167. /// and OCB mode. All modes implement AuthenticatedSymmetricCipher() and the motivation for
  1168. /// the API, like calling AAD a &quot;header&quot;, can be found in Bellare, Rogaway and
  1169. /// Wagner's <A HREF="http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf">The EAX Mode of
  1170. /// Operation</A>. The EAX paper suggested a basic API to help standardize AEAD schemes in
  1171. /// software and promote adoption of the modes.
  1172. /// \sa <A HREF="http://www.cryptopp.com/wiki/Authenticated_Encryption">Authenticated
  1173. /// Encryption</A> on the Crypto++ wiki.
  1174. /// \since Crypto++ 5.6.0
  1175. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
  1176. {
  1177. public:
  1178. virtual ~AuthenticatedSymmetricCipher() {}
  1179. /// \brief Exception thrown when the object is in the wrong state for the operation
  1180. /// \details this indicates that a member function was called in the wrong state, for example trying to encrypt
  1181. /// a message before having set the key or IV
  1182. class BadState : public Exception
  1183. {
  1184. public:
  1185. explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
  1186. explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
  1187. };
  1188. /// \brief Provides the maximum length of AAD that can be input
  1189. /// \return the maximum length of AAD that can be input before the encrypted data
  1190. virtual lword MaxHeaderLength() const =0;
  1191. /// \brief Provides the maximum length of encrypted data
  1192. /// \return the maximum length of encrypted data
  1193. virtual lword MaxMessageLength() const =0;
  1194. /// \brief Provides the maximum length of AAD
  1195. /// \return the maximum length of AAD that can be input after the encrypted data
  1196. virtual lword MaxFooterLength() const {return 0;}
  1197. /// \brief Determines if data lengths must be specified prior to inputting data
  1198. /// \return true if the data lengths are required before inputting data, false otherwise
  1199. /// \details if this function returns true, SpecifyDataLengths() must be called before attempting to input data.
  1200. /// This is the case for some schemes, such as CCM.
  1201. /// \sa SpecifyDataLengths()
  1202. virtual bool NeedsPrespecifiedDataLengths() const {return false;}
  1203. /// \brief Prescribes the data lengths
  1204. /// \param headerLength size of data before message is input, in bytes
  1205. /// \param messageLength size of the message, in bytes
  1206. /// \param footerLength size of data after message is input, in bytes
  1207. /// \details SpecifyDataLengths() only needs to be called if NeedsPrespecifiedDataLengths() returns <tt>true</tt>.
  1208. /// If <tt>true</tt>, then <tt>headerLength</tt> will be validated against <tt>MaxHeaderLength()</tt>,
  1209. /// <tt>messageLength</tt> will be validated against <tt>MaxMessageLength()</tt>, and
  1210. /// <tt>footerLength</tt> will be validated against <tt>MaxFooterLength()</tt>.
  1211. /// \sa NeedsPrespecifiedDataLengths()
  1212. void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
  1213. /// \brief Encrypts and calculates a MAC in one call
  1214. /// \param ciphertext the encryption buffer
  1215. /// \param mac the mac buffer
  1216. /// \param macSize the size of the MAC buffer, in bytes
  1217. /// \param iv the iv buffer
  1218. /// \param ivLength the size of the IV buffer, in bytes
  1219. /// \param header the AAD buffer
  1220. /// \param headerLength the size of the AAD buffer, in bytes
  1221. /// \param message the message buffer
  1222. /// \param messageLength the size of the messagetext buffer, in bytes
  1223. /// \details EncryptAndAuthenticate() encrypts and generates the MAC in one call. The function
  1224. /// truncates the MAC if <tt>macSize < TagSize()</tt>.
  1225. 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);
  1226. /// \brief Decrypts and verifies a MAC in one call
  1227. /// \param message the decryption buffer
  1228. /// \param mac the mac buffer
  1229. /// \param macSize the size of the MAC buffer, in bytes
  1230. /// \param iv the iv buffer
  1231. /// \param ivLength the size of the IV buffer, in bytes
  1232. /// \param header the AAD buffer
  1233. /// \param headerLength the size of the AAD buffer, in bytes
  1234. /// \param ciphertext the ciphertext buffer
  1235. /// \param ciphertextLength the size of the ciphertext buffer, in bytes
  1236. /// \return true if the MAC is valid and the decoding succeeded, false otherwise
  1237. /// \details DecryptAndVerify() decrypts and verifies the MAC in one call.
  1238. /// <tt>message</tt> is a decryption buffer and should be at least as large as the ciphertext buffer.
  1239. /// \details The function returns true iff MAC is valid. DecryptAndVerify() assumes the MAC
  1240. /// is truncated if <tt>macLength < TagSize()</tt>.
  1241. 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);
  1242. /// \brief Provides the name of this algorithm
  1243. /// \return the standard algorithm name
  1244. /// \details The standard algorithm name can be a name like \a AES or \a AES/GCM. Some algorithms
  1245. /// do not have standard names yet. For example, there is no standard algorithm name for
  1246. /// Shoup's ECIES.
  1247. virtual std::string AlgorithmName() const;
  1248. /// \brief Retrieve the provider of this algorithm
  1249. /// \return the algorithm provider
  1250. /// \details The algorithm provider can be a name like "C++", "SSE", "NEON", "AESNI",
  1251. /// "ARMv8" and "Power8". C++ is standard C++ code. Other labels, like SSE,
  1252. /// usually indicate a specialized implementation using instructions from a higher
  1253. /// instruction set architecture (ISA). Future labels may include external hardware
  1254. /// like a hardware security module (HSM).
  1255. /// \details Generally speaking Wei Dai's original IA-32 ASM code falls under "SSE2".
  1256. /// Labels like "SSSE3" and "SSE4.1" follow after Wei's code and use intrinsics
  1257. /// instead of ASM.
  1258. /// \details Algorithms which combine different instructions or ISAs provide the
  1259. /// dominant one. For example on x86 <tt>AES/GCM</tt> returns "AESNI" rather than
  1260. /// "CLMUL" or "AES+SSE4.1" or "AES+CLMUL" or "AES+SSE4.1+CLMUL".
  1261. /// \note Provider is not universally implemented yet.
  1262. /// \since Crypto++ 8.0
  1263. virtual std::string AlgorithmProvider() const {return "C++";}
  1264. protected:
  1265. const Algorithm & GetAlgorithm() const
  1266. {return *static_cast<const MessageAuthenticationCode *>(this);}
  1267. virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
  1268. {CRYPTOPP_UNUSED(headerLength); CRYPTOPP_UNUSED(messageLength); CRYPTOPP_UNUSED(footerLength);}
  1269. };
  1270. /// \brief Interface for random number generators
  1271. /// \details The library provides a number of random number generators, from software based
  1272. /// to hardware based generators.
  1273. /// \details All generated values are uniformly distributed over the range specified.
  1274. /// \since Crypto++ 3.1
  1275. /// \sa <A HREF="https://www.cryptopp.com/wiki/RandomNumberGenerator">RandomNumberGenerator</A>
  1276. /// on the Crypto++ wiki
  1277. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
  1278. {
  1279. public:
  1280. virtual ~RandomNumberGenerator() {}
  1281. /// \brief Update RNG state with additional unpredictable values
  1282. /// \param input the entropy to add to the generator
  1283. /// \param length the size of the input buffer
  1284. /// \throw NotImplemented
  1285. /// \details A generator may or may not accept additional entropy. Call CanIncorporateEntropy()
  1286. /// to test for the ability to use additional entropy.
  1287. /// \details If a derived class does not override IncorporateEntropy(), then the base class
  1288. /// throws NotImplemented.
  1289. virtual void IncorporateEntropy(const byte *input, size_t length)
  1290. {
  1291. CRYPTOPP_UNUSED(input); CRYPTOPP_UNUSED(length);
  1292. throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");
  1293. }
  1294. /// \brief Determines if a generator can accept additional entropy
  1295. /// \return true if IncorporateEntropy() is implemented
  1296. virtual bool CanIncorporateEntropy() const {return false;}
  1297. /// \brief Generate new random byte and return it
  1298. /// \return a random 8-bit byte
  1299. /// \details Default implementation calls GenerateBlock() with one byte.
  1300. /// \details All generated values are uniformly distributed over the range specified within the
  1301. /// the constraints of a particular generator.
  1302. virtual byte GenerateByte();
  1303. /// \brief Generate new random bit and return it
  1304. /// \return a random bit
  1305. /// \details The default implementation calls GenerateByte() and return its lowest bit.
  1306. /// \details All generated values are uniformly distributed over the range specified within the
  1307. /// the constraints of a particular generator.
  1308. virtual unsigned int GenerateBit();
  1309. /// \brief Generate a random 32 bit word in the range min to max, inclusive
  1310. /// \param min the lower bound of the range
  1311. /// \param max the upper bound of the range
  1312. /// \return a random 32-bit word
  1313. /// \details The default implementation calls Crop() on the difference between max and
  1314. /// min, and then returns the result added to min.
  1315. /// \details All generated values are uniformly distributed over the range specified within the
  1316. /// the constraints of a particular generator.
  1317. virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL);
  1318. /// \brief Generate random array of bytes
  1319. /// \param output the byte buffer
  1320. /// \param size the length of the buffer, in bytes
  1321. /// \details All generated values are uniformly distributed over the range specified within the
  1322. /// the constraints of a particular generator.
  1323. /// \note A derived generator \a must override either GenerateBlock() or
  1324. /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
  1325. virtual void GenerateBlock(byte *output, size_t size);
  1326. /// \brief Generate random bytes into a BufferedTransformation
  1327. /// \param target the BufferedTransformation object which receives the bytes
  1328. /// \param channel the channel on which the bytes should be pumped
  1329. /// \param length the number of bytes to generate
  1330. /// \details The default implementation calls GenerateBlock() and pumps the result into
  1331. /// the DEFAULT_CHANNEL of the target.
  1332. /// \details All generated values are uniformly distributed over the range specified within the
  1333. /// the constraints of a particular generator.
  1334. /// \note A derived generator \a must override either GenerateBlock() or
  1335. /// GenerateIntoBufferedTransformation(). They can override both, or have one call the other.
  1336. virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
  1337. /// \brief Generate and discard n bytes
  1338. /// \param n the number of bytes to generate and discard
  1339. virtual void DiscardBytes(size_t n);
  1340. /// \brief Randomly shuffle the specified array
  1341. /// \param begin an iterator to the first element in the array
  1342. /// \param end an iterator beyond the last element in the array
  1343. /// \details The resulting permutation is uniformly distributed.
  1344. template <class IT> void Shuffle(IT begin, IT end)
  1345. {
  1346. // TODO: What happens if there are more than 2^32 elements?
  1347. for (; begin != end; ++begin)
  1348. std::iter_swap(begin, begin + GenerateWord32(0, static_cast<word32>(end-begin-1)));
  1349. }
  1350. };
  1351. /// \brief Interface for key derivation functions
  1352. /// \since Crypto++ 7.0
  1353. /// \sa <A HREF="https://www.cryptopp.com/wiki/KeyDerivationFunction">KeyDerivationFunction</A>
  1354. /// on the Crypto++ wiki
  1355. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyDerivationFunction : public Algorithm
  1356. {
  1357. public:
  1358. virtual ~KeyDerivationFunction() {}
  1359. /// \brief Provides the name of this algorithm
  1360. /// \return the standard algorithm name
  1361. virtual std::string AlgorithmName() const =0;
  1362. /// \brief Determine minimum number of bytes
  1363. /// \return Minimum number of bytes which can be derived
  1364. virtual size_t MinDerivedKeyLength() const;
  1365. /// \brief Determine maximum number of bytes
  1366. /// \return Maximum number of bytes which can be derived
  1367. virtual size_t MaxDerivedKeyLength() const;
  1368. /// \brief Returns a valid key length for the derivation function
  1369. /// \param keylength the size of the derived key, in bytes
  1370. /// \return the valid key length, in bytes
  1371. virtual size_t GetValidDerivedLength(size_t keylength) const =0;
  1372. /// \brief Returns whether keylength is a valid key length
  1373. /// \param keylength the requested keylength
  1374. /// \return true if the derived keylength is valid, false otherwise
  1375. /// \details Internally the function calls GetValidKeyLength()
  1376. virtual bool IsValidDerivedLength(size_t keylength) const {
  1377. return keylength == GetValidDerivedLength(keylength);
  1378. }
  1379. /// \brief Derive a key from a seed
  1380. /// \param derived the derived output buffer
  1381. /// \param derivedLen the size of the derived buffer, in bytes
  1382. /// \param secret the seed input buffer
  1383. /// \param secretLen the size of the secret buffer, in bytes
  1384. /// \param params additional initialization parameters to configure this object
  1385. /// \return the number of iterations performed
  1386. /// \throw InvalidDerivedKeyLength if <tt>derivedLen</tt> is invalid for the scheme
  1387. /// \details DeriveKey() provides a standard interface to derive a key from
  1388. /// a secret seed and other parameters. Each class that derives from KeyDerivationFunction
  1389. /// provides an overload that accepts most parameters used by the derivation function.
  1390. /// \details the number of iterations performed by DeriveKey() may be 1. For example, a
  1391. /// scheme like HKDF does not use the iteration count so it returns 1.
  1392. virtual size_t DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const NameValuePairs& params = g_nullNameValuePairs) const =0;
  1393. /// \brief Set or change parameters
  1394. /// \param params additional initialization parameters to configure this object
  1395. /// \details SetParameters() is useful for setting common parameters when an object is
  1396. /// reused. Some derivation function classes may choose to implement it.
  1397. virtual void SetParameters(const NameValuePairs& params);
  1398. protected:
  1399. /// \brief Returns the base class Algorithm
  1400. /// \return the base class Algorithm
  1401. virtual const Algorithm & GetAlgorithm() const =0;
  1402. /// \brief Validates the derived key length
  1403. /// \param length the size of the derived key material, in bytes
  1404. /// \throw InvalidKeyLength if the key length is invalid
  1405. void ThrowIfInvalidDerivedKeyLength(size_t length) const;
  1406. };
  1407. /// \brief Interface for password based key derivation functions
  1408. /// \since Crypto++ 7.0
  1409. struct PasswordBasedKeyDerivationFunction : public KeyDerivationFunction
  1410. {
  1411. };
  1412. /// \brief Random Number Generator that does not produce random numbers
  1413. /// \return reference that can be passed to functions that require a RandomNumberGenerator
  1414. /// \details NullRNG() returns a reference that can be passed to functions that require a
  1415. /// RandomNumberGenerator but don't actually use it. The NullRNG() throws NotImplemented
  1416. /// when a generation function is called.
  1417. /// \sa ClassNullRNG, PK_SignatureScheme::IsProbabilistic()
  1418. CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
  1419. class WaitObjectContainer;
  1420. class CallStack;
  1421. /// \brief Interface for objects that can be waited on.
  1422. class CRYPTOPP_NO_VTABLE Waitable
  1423. {
  1424. public:
  1425. virtual ~Waitable() {}
  1426. /// \brief Maximum number of wait objects that this object can return
  1427. /// \return the maximum number of wait objects
  1428. virtual unsigned int GetMaxWaitObjectCount() const =0;
  1429. /// \brief Retrieves waitable objects
  1430. /// \param container the wait container to receive the references to the objects.
  1431. /// \param callStack CallStack() object used to select waitable objects
  1432. /// \details GetWaitObjects() is usually called in one of two ways. First, it can
  1433. /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
  1434. /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
  1435. /// parameter, it can be called like
  1436. /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
  1437. virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
  1438. /// \brief Wait on this object
  1439. /// \return true if the wait succeeded, false otherwise
  1440. /// \details Wait() is the same as creating an empty container, calling GetWaitObjects(), and then calling
  1441. /// Wait() on the container.
  1442. bool Wait(unsigned long milliseconds, CallStack const& callStack);
  1443. };
  1444. /// \brief Interface for buffered transformations
  1445. /// \details BufferedTransformation is a generalization of BlockTransformation,
  1446. /// StreamTransformation and HashTransformation.
  1447. /// \details A buffered transformation is an object that takes a stream of bytes as input (this may
  1448. /// be done in stages), does some computation on them, and then places the result into an internal
  1449. /// buffer for later retrieval. Any partial result already in the output buffer is not modified
  1450. /// by further input.
  1451. /// \details If a method takes a "blocking" parameter, and you pass false for it, then the method
  1452. /// will return before all input has been processed if the input cannot be processed without waiting
  1453. /// (for network buffers to become available, for example). In this case the method will return true
  1454. /// or a non-zero integer value. When this happens you must continue to call the method with the same
  1455. /// parameters until it returns false or zero, before calling any other method on it or attached
  1456. /// BufferedTransformation. The integer return value in this case is approximately
  1457. /// the number of bytes left to be processed, and can be used to implement a progress bar.
  1458. /// \details For functions that take a "propagation" parameter, <tt>propagation != 0</tt> means pass on
  1459. /// the signal to attached BufferedTransformation objects, with propagation decremented at each
  1460. /// step until it reaches <tt>0</tt>. <tt>-1</tt> means unlimited propagation.
  1461. /// \details \a All of the retrieval functions, like Get() and GetWord32(), return the actual
  1462. /// number of bytes retrieved, which is the lesser of the request number and MaxRetrievable().
  1463. /// \details \a Most of the input functions, like Put() and PutWord32(), return the number of
  1464. /// bytes remaining to be processed. A 0 value means all bytes were processed, and a non-0 value
  1465. /// means bytes remain to be processed.
  1466. /// \nosubgrouping
  1467. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
  1468. {
  1469. public:
  1470. virtual ~BufferedTransformation() {}
  1471. /// \brief Construct a BufferedTransformation
  1472. BufferedTransformation() : Algorithm(false) {}
  1473. /// \brief Provides a reference to this object
  1474. /// \return A reference to this object
  1475. /// \details Useful for passing a temporary object to a function that takes a non-const reference
  1476. BufferedTransformation& Ref() {return *this;}
  1477. /// \name INPUT
  1478. //@{
  1479. /// \brief Input a byte for processing
  1480. /// \param inByte the 8-bit byte (octet) to be processed.
  1481. /// \param blocking specifies whether the object should block when processing input.
  1482. /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
  1483. /// 0 indicates all bytes were processed.
  1484. /// \details <tt>Put(byte)</tt> calls <tt>Put(byte*, size_t)</tt>.
  1485. size_t Put(byte inByte, bool blocking=true)
  1486. {return Put(&inByte, 1, blocking);}
  1487. /// \brief Input a byte buffer for processing
  1488. /// \param inString the byte buffer to process
  1489. /// \param length the size of the string, in bytes
  1490. /// \param blocking specifies whether the object should block when processing input
  1491. /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
  1492. /// 0 indicates all bytes were processed.
  1493. /// \details Internally, Put() calls Put2().
  1494. size_t Put(const byte *inString, size_t length, bool blocking=true)
  1495. {return Put2(inString, length, 0, blocking);}
  1496. /// Input a 16-bit word for processing.
  1497. /// \param value the 16-bit value to be processed
  1498. /// \param order the ByteOrder of the value to be processed.
  1499. /// \param blocking specifies whether the object should block when processing input
  1500. /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
  1501. /// 0 indicates all bytes were processed.
  1502. size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1503. /// Input a 32-bit word for processing.
  1504. /// \param value the 32-bit value to be processed.
  1505. /// \param order the ByteOrder of the value to be processed.
  1506. /// \param blocking specifies whether the object should block when processing input.
  1507. /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
  1508. /// 0 indicates all bytes were processed.
  1509. size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1510. /// Input a 64-bit word for processing.
  1511. /// \param value the 64-bit value to be processed.
  1512. /// \param order the ByteOrder of the value to be processed.
  1513. /// \param blocking specifies whether the object should block when processing input.
  1514. /// \return the number of bytes that remain to be processed (i.e., bytes not processed).
  1515. /// 0 indicates all bytes were processed.
  1516. size_t PutWord64(word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1517. /// \brief Request space which can be written into by the caller
  1518. /// \param size the requested size of the buffer
  1519. /// \return byte pointer to the space to input data
  1520. /// \details The purpose of this method is to help avoid extra memory allocations.
  1521. /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
  1522. /// size is the requested size of the buffer. When the call returns, size is the size of
  1523. /// the array returned to the caller.
  1524. /// \details The base class implementation sets size to 0 and returns NULL.
  1525. /// \note Some objects, like ArraySink, cannot create a space because its fixed. In the case of
  1526. /// an ArraySink, the pointer to the array is returned and the size is remaining size.
  1527. virtual byte * CreatePutSpace(size_t &size)
  1528. {size=0; return NULLPTR;}
  1529. /// \brief Determines whether input can be modified by the callee
  1530. /// \return true if input can be modified, false otherwise
  1531. /// \details The base class implementation returns false.
  1532. virtual bool CanModifyInput() const
  1533. {return false;}
  1534. /// \brief Input multiple bytes that may be modified by callee.
  1535. /// \param inString the byte buffer to process
  1536. /// \param length the size of the string, in bytes
  1537. /// \param blocking specifies whether the object should block when processing input
  1538. /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
  1539. /// bytes were processed.
  1540. size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
  1541. {return PutModifiable2(inString, length, 0, blocking);}
  1542. /// \brief Signals the end of messages to the object
  1543. /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
  1544. /// \param blocking specifies whether the object should block when processing input
  1545. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1546. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1547. bool MessageEnd(int propagation=-1, bool blocking=true)
  1548. {return !!Put2(NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
  1549. /// \brief Input multiple bytes for processing and signal the end of a message
  1550. /// \param inString the byte buffer to process
  1551. /// \param length the size of the string, in bytes
  1552. /// \param propagation the number of attached transformations the MessageEnd() signal should be passed
  1553. /// \param blocking specifies whether the object should block when processing input
  1554. /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
  1555. /// bytes were processed.
  1556. /// \details Internally, PutMessageEnd() calls Put2() with a modified propagation to
  1557. /// ensure all attached transformations finish processing the message.
  1558. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1559. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1560. size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
  1561. {return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
  1562. /// \brief Input multiple bytes for processing
  1563. /// \param inString the byte buffer to process
  1564. /// \param length the size of the string, in bytes
  1565. /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
  1566. /// \param blocking specifies whether the object should block when processing input
  1567. /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
  1568. /// bytes were processed.
  1569. /// \details Derived classes must implement Put2().
  1570. virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
  1571. /// \brief Input multiple bytes that may be modified by callee.
  1572. /// \param inString the byte buffer to process.
  1573. /// \param length the size of the string, in bytes.
  1574. /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
  1575. /// \param blocking specifies whether the object should block when processing input.
  1576. /// \return the number of bytes that remain to be processed (i.e., bytes not processed). 0 indicates all
  1577. /// bytes were processed.
  1578. /// \details Internally, PutModifiable2() calls Put2().
  1579. virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
  1580. {return Put2(inString, length, messageEnd, blocking);}
  1581. /// \brief Exception thrown by objects that have \a not implemented nonblocking input processing
  1582. /// \details BlockingInputOnly inherits from NotImplemented
  1583. struct BlockingInputOnly : public NotImplemented
  1584. {BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
  1585. //@}
  1586. /// \name WAITING
  1587. //@{
  1588. /// \brief Retrieves the maximum number of waitable objects
  1589. unsigned int GetMaxWaitObjectCount() const;
  1590. /// \brief Retrieves waitable objects
  1591. /// \param container the wait container to receive the references to the objects
  1592. /// \param callStack CallStack() object used to select waitable objects
  1593. /// \details GetWaitObjects is usually called in one of two ways. First, it can
  1594. /// be called like <tt>something.GetWaitObjects(c, CallStack("my func after X", 0));</tt>.
  1595. /// Second, if in an outer GetWaitObjects() method that itself takes a callStack
  1596. /// parameter, it can be called like
  1597. /// <tt>innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack));</tt>.
  1598. void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
  1599. //@} // WAITING
  1600. /// \name SIGNALS
  1601. //@{
  1602. /// \brief Initialize or reinitialize this object, without signal propagation
  1603. /// \param parameters a set of NameValuePairs to initialize this object
  1604. /// \throw NotImplemented
  1605. /// \details IsolatedInitialize() is used to initialize or reinitialize an object using a variable
  1606. /// number of arbitrarily typed arguments. The function avoids the need for multiple constructors providing
  1607. /// all possible combintations of configurable parameters.
  1608. /// \details IsolatedInitialize() does not call Initialize() on attached transformations. If initialization
  1609. /// should be propagated, then use the Initialize() function.
  1610. /// \details If a derived class does not override IsolatedInitialize(), then the base class throws
  1611. /// NotImplemented.
  1612. virtual void IsolatedInitialize(const NameValuePairs &parameters) {
  1613. CRYPTOPP_UNUSED(parameters);
  1614. throw NotImplemented("BufferedTransformation: this object can't be reinitialized");
  1615. }
  1616. /// \brief Flushes data buffered by this object, without signal propagation
  1617. /// \param hardFlush indicates whether all data should be flushed
  1618. /// \param blocking specifies whether the object should block when processing input
  1619. /// \return true if the flush was successful, false otherwise
  1620. /// \note hardFlush must be used with care
  1621. virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
  1622. /// \brief Marks the end of a series of messages, without signal propagation
  1623. /// \param blocking specifies whether the object should block when completing the processing on
  1624. /// the current series of messages
  1625. /// \return true if the message was successful, false otherwise
  1626. virtual bool IsolatedMessageSeriesEnd(bool blocking)
  1627. {CRYPTOPP_UNUSED(blocking); return false;}
  1628. /// \brief Initialize or reinitialize this object, with signal propagation
  1629. /// \param parameters a set of NameValuePairs to initialize or reinitialize this object
  1630. /// \param propagation the number of attached transformations the Initialize() signal should be passed
  1631. /// \details Initialize() is used to initialize or reinitialize an object using a variable number of
  1632. /// arbitrarily typed arguments. The function avoids the need for multiple constructors providing
  1633. /// all possible combintations of configurable parameters.
  1634. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1635. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1636. virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1);
  1637. /// \brief Flush buffered input and/or output, with signal propagation
  1638. /// \param hardFlush is used to indicate whether all data should be flushed
  1639. /// \param propagation the number of attached transformations the Flush()
  1640. /// signal should be passed
  1641. /// \param blocking specifies whether the object should block when processing input
  1642. /// \return true if the flush was successful, false otherwise
  1643. /// \details propagation count includes this object. Setting propagation to
  1644. /// <tt>1</tt> means this object only. Setting propagation to <tt>-1</tt>
  1645. /// means unlimited propagation.
  1646. /// \note Hard flushes must be used with care. It means try to process and
  1647. /// output everything, even if there may not be enough data to complete the
  1648. /// action. For example, hard flushing a HexDecoder would cause an error if
  1649. /// you do it after inputing an odd number of hex encoded characters.
  1650. /// \note For some types of filters, like ZlibDecompressor, hard flushes can
  1651. /// only be done at "synchronization points". These synchronization points
  1652. /// are positions in the data stream that are created by hard flushes on the
  1653. /// corresponding reverse filters, in this example ZlibCompressor. This is
  1654. /// useful when zlib compressed data is moved across a network in packets
  1655. /// and compression state is preserved across packets, as in the SSH2 protocol.
  1656. virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
  1657. /// \brief Marks the end of a series of messages, with signal propagation
  1658. /// \param propagation the number of attached transformations the MessageSeriesEnd() signal should be passed
  1659. /// \param blocking specifies whether the object should block when processing input
  1660. /// \return true if the message was successful, false otherwise
  1661. /// \details Each object that receives the signal will perform its processing, decrement
  1662. /// propagation, and then pass the signal on to attached transformations if the value is not 0.
  1663. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1664. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1665. /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
  1666. virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
  1667. /// \brief Set propagation of automatically generated and transferred signals
  1668. /// \param propagation then new value
  1669. /// \details Setting propagation to <tt>0</tt> means do not automatically generate signals. Setting
  1670. /// propagation to <tt>-1</tt> means unlimited propagation.
  1671. virtual void SetAutoSignalPropagation(int propagation)
  1672. {CRYPTOPP_UNUSED(propagation);}
  1673. /// \brief Retrieve automatic signal propagation value
  1674. /// \return the number of attached transformations the signal is propagated to. 0 indicates
  1675. /// the signal is only witnessed by this object
  1676. virtual int GetAutoSignalPropagation() const {return 0;}
  1677. public:
  1678. /// \name RETRIEVAL OF ONE MESSAGE
  1679. //@{
  1680. /// \brief Provides the number of bytes ready for retrieval
  1681. /// \return the number of bytes ready for retrieval
  1682. /// \details The number of bytes available are dependent on the source. If an exact value is
  1683. /// available, then the exact value is returned. The exact value can include 0 if the source
  1684. /// is exhausted.
  1685. /// \details Some stream-based sources do not allow seeking() on the underlying stream, such
  1686. /// as some FileSource(). If the stream does not allow seeking() then MaxRetrievable()
  1687. /// returns LWORD_MAX to indicate there are still bytes to be retrieved.
  1688. virtual lword MaxRetrievable() const;
  1689. /// \brief Determines whether bytes are ready for retrieval
  1690. /// \return true if bytes are available for retrieval, false otherwise
  1691. virtual bool AnyRetrievable() const;
  1692. /// \brief Retrieve a 8-bit byte
  1693. /// \param outByte the 8-bit value to be retrieved
  1694. /// \return the number of bytes consumed during the call.
  1695. /// \details Use the return value of Get to detect short reads.
  1696. virtual size_t Get(byte &outByte);
  1697. /// \brief Retrieve a block of bytes
  1698. /// \param outString a block of bytes
  1699. /// \param getMax the number of bytes to Get
  1700. /// \return the number of bytes consumed during the call.
  1701. /// \details Use the return value of Get to detect short reads.
  1702. virtual size_t Get(byte *outString, size_t getMax);
  1703. /// \brief Peek a 8-bit byte
  1704. /// \param outByte the 8-bit value to be retrieved
  1705. /// \return the number of bytes read during the call.
  1706. /// \details Peek does not remove bytes from the object. Use the return value of
  1707. /// Get() to detect short reads.
  1708. virtual size_t Peek(byte &outByte) const;
  1709. /// \brief Peek a block of bytes
  1710. /// \param outString a block of bytes
  1711. /// \param peekMax the number of bytes to Peek
  1712. /// \return the number of bytes read during the call.
  1713. /// \details Peek does not remove bytes from the object. Use the return value of
  1714. /// Peek() to detect short reads.
  1715. virtual size_t Peek(byte *outString, size_t peekMax) const;
  1716. /// \brief Retrieve a 16-bit word
  1717. /// \param value the 16-bit value to be retrieved
  1718. /// \param order the ByteOrder of the value to be processed.
  1719. /// \return the number of bytes consumed during the call.
  1720. /// \details Use the return value of GetWord16() to detect short reads.
  1721. size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
  1722. /// \brief Retrieve a 32-bit word
  1723. /// \param value the 32-bit value to be retrieved
  1724. /// \param order the ByteOrder of the value to be processed.
  1725. /// \return the number of bytes consumed during the call.
  1726. /// \details Use the return value of GetWord32() to detect short reads.
  1727. size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
  1728. /// \brief Retrieve a 64-bit word
  1729. /// \param value the 64-bit value to be retrieved
  1730. /// \param order the ByteOrder of the value to be processed.
  1731. /// \return the number of bytes consumed during the call.
  1732. /// \details Use the return value of GetWord64() to detect short reads.
  1733. /// \since Crypto++ 8.3
  1734. size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER);
  1735. /// \brief Peek a 16-bit word
  1736. /// \param value the 16-bit value to be retrieved
  1737. /// \param order the ByteOrder of the value to be processed.
  1738. /// \return the number of bytes consumed during the call.
  1739. /// \details Peek does not consume bytes in the stream. Use the return value
  1740. /// of PeekWord16() to detect short reads.
  1741. size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
  1742. /// \brief Peek a 32-bit word
  1743. /// \param value the 32-bit value to be retrieved
  1744. /// \param order the ByteOrder of the value to be processed.
  1745. /// \return the number of bytes consumed during the call.
  1746. /// \details Peek does not consume bytes in the stream. Use the return value
  1747. /// of PeekWord32() to detect short reads.
  1748. size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
  1749. /// \brief Peek a 64-bit word
  1750. /// \param value the 64-bit value to be retrieved
  1751. /// \param order the ByteOrder of the value to be processed.
  1752. /// \return the number of bytes consumed during the call.
  1753. /// \details Peek does not consume bytes in the stream. Use the return value
  1754. /// of PeekWord64() to detect short reads.
  1755. /// \since Crypto++ 8.3
  1756. size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
  1757. /// move transferMax bytes of the buffered output to target as input
  1758. /// \brief Transfer bytes from this object to another BufferedTransformation
  1759. /// \param target the destination BufferedTransformation
  1760. /// \param transferMax the number of bytes to transfer
  1761. /// \param channel the channel on which the transfer should occur
  1762. /// \return the number of bytes transferred during the call.
  1763. /// \details TransferTo removes bytes from this object and moves them to the destination.
  1764. /// \details The function always returns transferMax. If an accurate count is needed, then use TransferTo2().
  1765. lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
  1766. {TransferTo2(target, transferMax, channel); return transferMax;}
  1767. /// \brief Discard skipMax bytes from the output buffer
  1768. /// \param skipMax the number of bytes to discard
  1769. /// \details Skip() discards bytes from the output buffer, which is the AttachedTransformation(), if present.
  1770. /// The function always returns the parameter <tt>skipMax</tt>.
  1771. /// \details If you want to skip bytes from a Source, then perform the following.
  1772. /// <pre> StringSource ss(str, false, new Redirector(TheBitBucket()));
  1773. /// ss.Pump(10); // Skip 10 bytes from Source
  1774. /// ss.Detach(new FilterChain(...));
  1775. /// ss.PumpAll();
  1776. /// </pre>
  1777. virtual lword Skip(lword skipMax=LWORD_MAX);
  1778. /// \brief Copy bytes from this object to another BufferedTransformation
  1779. /// \param target the destination BufferedTransformation
  1780. /// \param copyMax the number of bytes to copy
  1781. /// \param channel the channel on which the transfer should occur
  1782. /// \return the number of bytes copied during the call.
  1783. /// \details CopyTo copies bytes from this object to the destination. The bytes are not removed from this object.
  1784. /// \details The function always returns copyMax. If an accurate count is needed, then use CopyRangeTo2().
  1785. lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
  1786. {return CopyRangeTo(target, 0, copyMax, channel);}
  1787. /// \brief Copy bytes from this object using an index to another BufferedTransformation
  1788. /// \param target the destination BufferedTransformation
  1789. /// \param position the 0-based index of the byte stream to begin the copying
  1790. /// \param copyMax the number of bytes to copy
  1791. /// \param channel the channel on which the transfer should occur
  1792. /// \return the number of bytes copied during the call.
  1793. /// \details CopyTo copies bytes from this object to the destination. The bytes remain in this
  1794. /// object. Copying begins at the index position in the current stream, and not from an absolute
  1795. /// position in the stream.
  1796. /// \details The function returns the new position in the stream after transferring the bytes starting at the index.
  1797. lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
  1798. {lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
  1799. //@}
  1800. /// \name RETRIEVAL OF MULTIPLE MESSAGES
  1801. //@{
  1802. /// \brief Provides the number of bytes ready for retrieval
  1803. /// \return the number of bytes ready for retrieval
  1804. virtual lword TotalBytesRetrievable() const;
  1805. /// \brief Provides the number of meesages processed by this object
  1806. /// \return the number of meesages processed by this object
  1807. /// \details NumberOfMessages returns number of times MessageEnd() has been
  1808. /// received minus messages retrieved or skipped
  1809. virtual unsigned int NumberOfMessages() const;
  1810. /// \brief Determines if any messages are available for retrieval
  1811. /// \return true if <tt>NumberOfMessages() &gt; 0</tt>, false otherwise
  1812. /// \details AnyMessages returns true if <tt>NumberOfMessages() &gt; 0</tt>
  1813. virtual bool AnyMessages() const;
  1814. /// \brief Start retrieving the next message
  1815. /// \return true if a message is ready for retrieval
  1816. /// \details GetNextMessage() returns true if a message is ready for retrieval; false
  1817. /// if no more messages exist or this message is not completely retrieved.
  1818. virtual bool GetNextMessage();
  1819. /// \brief Skip a number of meessages
  1820. /// \param count number of messages to skip
  1821. /// \return 0 if the requested number of messages was skipped, non-0 otherwise
  1822. /// \details SkipMessages() skips count number of messages. If there is an AttachedTransformation()
  1823. /// then SkipMessages() is called on the attached transformation. If there is no attached
  1824. /// transformation, then count number of messages are sent to TheBitBucket() using TransferMessagesTo().
  1825. virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
  1826. /// \brief Transfer messages from this object to another BufferedTransformation
  1827. /// \param target the destination BufferedTransformation
  1828. /// \param count the number of messages to transfer
  1829. /// \param channel the channel on which the transfer should occur
  1830. /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1831. /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
  1832. /// If all bytes are not transferred for a message, then processing stops and the number of remaining
  1833. /// bytes is returned. TransferMessagesTo() does not proceed to the next message.
  1834. /// \details A return value of 0 indicates all messages were successfully transferred.
  1835. unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
  1836. {TransferMessagesTo2(target, count, channel); return count;}
  1837. /// \brief Copy messages from this object to another BufferedTransformation
  1838. /// \param target the destination BufferedTransformation
  1839. /// \param count the number of messages to copy
  1840. /// \param channel the channel on which the copy should occur
  1841. /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1842. /// \details CopyMessagesTo copies messages from this object to the destination.
  1843. /// If all bytes are not transferred for a message, then processing stops and the number of remaining
  1844. /// bytes is returned. CopyMessagesTo() does not proceed to the next message.
  1845. /// \details A return value of 0 indicates all messages were successfully copied.
  1846. unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
  1847. /// \brief Skip all messages in the series
  1848. virtual void SkipAll();
  1849. /// \brief Transfer all bytes from this object to another BufferedTransformation
  1850. /// \param target the destination BufferedTransformation
  1851. /// \param channel the channel on which the transfer should occur
  1852. /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
  1853. /// Internally TransferAllTo() calls TransferAllTo2().
  1854. void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
  1855. {TransferAllTo2(target, channel);}
  1856. /// \brief Copy messages from this object to another BufferedTransformation
  1857. /// \param target the destination BufferedTransformation
  1858. /// \param channel the channel on which the transfer should occur
  1859. /// \details CopyAllTo copies messages from this object and copies them to the destination.
  1860. void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
  1861. /// \brief Retrieve the next message in a series
  1862. /// \return true if a message was retrieved, false otherwise
  1863. /// \details Internally, the base class implementation returns false.
  1864. virtual bool GetNextMessageSeries() {return false;}
  1865. /// \brief Provides the number of messages in a series
  1866. /// \return the number of messages in this series
  1867. virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
  1868. /// \brief Provides the number of messages in a series
  1869. /// \return the number of messages in this series
  1870. virtual unsigned int NumberOfMessageSeries() const {return 0;}
  1871. //@}
  1872. /// \name NON-BLOCKING TRANSFER OF OUTPUT
  1873. //@{
  1874. // upon return, byteCount contains number of bytes that have finished being transferred,
  1875. // and returns the number of bytes left in the current transfer block
  1876. /// \brief Transfer bytes from this object to another BufferedTransformation
  1877. /// \param target the destination BufferedTransformation
  1878. /// \param byteCount the number of bytes to transfer
  1879. /// \param channel the channel on which the transfer should occur
  1880. /// \param blocking specifies whether the object should block when processing input
  1881. /// \return the number of bytes that remain in the transfer block (i.e., bytes not transferred)
  1882. /// \details TransferTo2() removes bytes from this object and moves them to the destination.
  1883. /// Transfer begins at the index position in the current stream, and not from an absolute
  1884. /// position in the stream.
  1885. /// \details byteCount is an \a IN and \a OUT parameter. When the call is made,
  1886. /// byteCount is the requested size of the transfer. When the call returns, byteCount is
  1887. /// the number of bytes that were transferred.
  1888. virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
  1889. // upon return, begin contains the start position of data yet to be finished copying,
  1890. // and returns the number of bytes left in the current transfer block
  1891. /// \brief Copy bytes from this object to another BufferedTransformation
  1892. /// \param target the destination BufferedTransformation
  1893. /// \param begin the 0-based index of the first byte to copy in the stream
  1894. /// \param end the 0-based index of the last byte to copy in the stream
  1895. /// \param channel the channel on which the transfer should occur
  1896. /// \param blocking specifies whether the object should block when processing input
  1897. /// \return the number of bytes that remain in the copy block (i.e., bytes not copied)
  1898. /// \details CopyRangeTo2 copies bytes from this object to the destination. The bytes are not
  1899. /// removed from this object. Copying begins at the index position in the current stream, and
  1900. /// not from an absolute position in the stream.
  1901. /// \details begin is an \a IN and \a OUT parameter. When the call is made, begin is the
  1902. /// starting position of the copy. When the call returns, begin is the position of the first
  1903. /// byte that was \a not copied (which may be different than end). begin can be used for
  1904. /// subsequent calls to CopyRangeTo2().
  1905. virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
  1906. // upon return, messageCount contains number of messages that have finished being transferred,
  1907. // and returns the number of bytes left in the current transfer block
  1908. /// \brief Transfer messages from this object to another BufferedTransformation
  1909. /// \param target the destination BufferedTransformation
  1910. /// \param messageCount the number of messages to transfer
  1911. /// \param channel the channel on which the transfer should occur
  1912. /// \param blocking specifies whether the object should block when processing input
  1913. /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1914. /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
  1915. /// \details messageCount is an \a IN and \a OUT parameter. When the call is made, messageCount is the
  1916. /// the number of messages requested to be transferred. When the call returns, messageCount is the
  1917. /// number of messages actually transferred.
  1918. size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
  1919. // returns the number of bytes left in the current transfer block
  1920. /// \brief Transfer all bytes from this object to another BufferedTransformation
  1921. /// \param target the destination BufferedTransformation
  1922. /// \param channel the channel on which the transfer should occur
  1923. /// \param blocking specifies whether the object should block when processing input
  1924. /// \return the number of bytes that remain in the current transfer block (i.e., bytes not transferred)
  1925. /// \details TransferMessagesTo2() removes messages from this object and moves them to the destination.
  1926. size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
  1927. //@}
  1928. /// \name CHANNELS
  1929. //@{
  1930. /// \brief Exception thrown when a filter does not support named channels
  1931. struct NoChannelSupport : public NotImplemented
  1932. {NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
  1933. /// \brief Exception thrown when a filter does not recognize a named channel
  1934. struct InvalidChannelName : public InvalidArgument
  1935. {InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
  1936. /// \brief Input a byte for processing on a channel
  1937. /// \param channel the channel to process the data.
  1938. /// \param inByte the 8-bit byte (octet) to be processed.
  1939. /// \param blocking specifies whether the object should block when processing input.
  1940. /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
  1941. /// number of bytes that were not processed.
  1942. size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
  1943. {return ChannelPut(channel, &inByte, 1, blocking);}
  1944. /// \brief Input a byte buffer for processing on a channel
  1945. /// \param channel the channel to process the data
  1946. /// \param inString the byte buffer to process
  1947. /// \param length the size of the string, in bytes
  1948. /// \param blocking specifies whether the object should block when processing input
  1949. /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
  1950. /// number of bytes that were not processed.
  1951. size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
  1952. {return ChannelPut2(channel, inString, length, 0, blocking);}
  1953. /// \brief Input multiple bytes that may be modified by callee on a channel
  1954. /// \param channel the channel to process the data.
  1955. /// \param inString the byte buffer to process
  1956. /// \param length the size of the string, in bytes
  1957. /// \param blocking specifies whether the object should block when processing input
  1958. /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
  1959. /// number of bytes that were not processed.
  1960. size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
  1961. {return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
  1962. /// \brief Input a 16-bit word for processing on a channel.
  1963. /// \param channel the channel to process the data.
  1964. /// \param value the 16-bit value to be processed.
  1965. /// \param order the ByteOrder of the value to be processed.
  1966. /// \param blocking specifies whether the object should block when processing input.
  1967. /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
  1968. /// number of bytes that were not processed.
  1969. size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1970. /// \brief Input a 32-bit word for processing on a channel.
  1971. /// \param channel the channel to process the data.
  1972. /// \param value the 32-bit value to be processed.
  1973. /// \param order the ByteOrder of the value to be processed.
  1974. /// \param blocking specifies whether the object should block when processing input.
  1975. /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
  1976. /// number of bytes that were not processed.
  1977. size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1978. /// \brief Input a 64-bit word for processing on a channel.
  1979. /// \param channel the channel to process the data.
  1980. /// \param value the 64-bit value to be processed.
  1981. /// \param order the ByteOrder of the value to be processed.
  1982. /// \param blocking specifies whether the object should block when processing input.
  1983. /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
  1984. /// number of bytes that were not processed.
  1985. size_t ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
  1986. /// \brief Signal the end of a message
  1987. /// \param channel the channel to process the data.
  1988. /// \param propagation the number of attached transformations the ChannelMessageEnd() signal should be passed
  1989. /// \param blocking specifies whether the object should block when processing input
  1990. /// \return 0 indicates all bytes were processed during the call. Non-0 indicates the
  1991. /// number of bytes that were not processed.
  1992. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  1993. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  1994. bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
  1995. {return !!ChannelPut2(channel, NULLPTR, 0, propagation < 0 ? -1 : propagation+1, blocking);}
  1996. /// \brief Input multiple bytes for processing and signal the end of a message
  1997. /// \param channel the channel to process the data.
  1998. /// \param inString the byte buffer to process
  1999. /// \param length the size of the string, in bytes
  2000. /// \param propagation the number of attached transformations the ChannelPutMessageEnd() signal should be passed
  2001. /// \param blocking specifies whether the object should block when processing input
  2002. /// \return the number of bytes that remain to be processed (i.e., bytes not processed)
  2003. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  2004. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  2005. size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
  2006. {return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
  2007. /// \brief Request space which can be written into by the caller
  2008. /// \param channel the channel to process the data
  2009. /// \param size the requested size of the buffer
  2010. /// \return a pointer to a memory block with length size
  2011. /// \details The purpose of this method is to help avoid extra memory allocations.
  2012. /// \details size is an \a IN and \a OUT parameter and used as a hint. When the call is made,
  2013. /// size is the requested size of the buffer. When the call returns, size is the size of
  2014. /// the array returned to the caller.
  2015. /// \details The base class implementation sets size to 0 and returns NULL.
  2016. /// \note Some objects, like ArraySink(), cannot create a space because its fixed. In the case of
  2017. /// an ArraySink(), the pointer to the array is returned and the size is remaining size.
  2018. virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
  2019. /// \brief Input multiple bytes for processing on a channel.
  2020. /// \param channel the channel to process the data.
  2021. /// \param inString the byte buffer to process.
  2022. /// \param length the size of the string, in bytes.
  2023. /// \param messageEnd means how many filters to signal MessageEnd() to, including this one.
  2024. /// \param blocking specifies whether the object should block when processing input.
  2025. /// \return the number of bytes that remain to be processed (i.e., bytes not processed)
  2026. virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking);
  2027. /// \brief Input multiple bytes that may be modified by callee on a channel
  2028. /// \param channel the channel to process the data
  2029. /// \param inString the byte buffer to process
  2030. /// \param length the size of the string, in bytes
  2031. /// \param messageEnd means how many filters to signal MessageEnd() to, including this one
  2032. /// \param blocking specifies whether the object should block when processing input
  2033. /// \return the number of bytes that remain to be processed (i.e., bytes not processed)
  2034. virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking);
  2035. /// \brief Flush buffered input and/or output on a channel
  2036. /// \param channel the channel to flush the data
  2037. /// \param hardFlush is used to indicate whether all data should be flushed
  2038. /// \param propagation the number of attached transformations the ChannelFlush() signal should be passed
  2039. /// \param blocking specifies whether the object should block when processing input
  2040. /// \return true of the Flush was successful
  2041. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  2042. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  2043. virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
  2044. /// \brief Marks the end of a series of messages on a channel
  2045. /// \param channel the channel to signal the end of a series of messages
  2046. /// \param propagation the number of attached transformations the ChannelMessageSeriesEnd() signal should be passed
  2047. /// \param blocking specifies whether the object should block when processing input
  2048. /// \return true if the message was successful, false otherwise
  2049. /// \details Each object that receives the signal will perform its processing, decrement
  2050. /// propagation, and then pass the signal on to attached transformations if the value is not 0.
  2051. /// \details propagation count includes this object. Setting propagation to <tt>1</tt> means this
  2052. /// object only. Setting propagation to <tt>-1</tt> means unlimited propagation.
  2053. /// \note There should be a MessageEnd() immediately before MessageSeriesEnd().
  2054. virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
  2055. /// \brief Sets the default retrieval channel
  2056. /// \param channel the channel to signal the end of a series of messages
  2057. /// \note this function may not be implemented in all objects that should support it.
  2058. virtual void SetRetrievalChannel(const std::string &channel);
  2059. //@}
  2060. /// \name ATTACHMENT
  2061. /// \details Some BufferedTransformation objects (e.g. Filter objects) allow other BufferedTransformation objects to be
  2062. /// attached. When this is done, the first object instead of buffering its output, sends that output to the attached
  2063. /// object as input. The entire attachment chain is deleted when the anchor object is destructed.
  2064. //@{
  2065. /// \brief Determines whether the object allows attachment
  2066. /// \return true if the object allows an attachment, false otherwise
  2067. /// \details Sources and Filters will returns true, while Sinks and other objects will return false.
  2068. virtual bool Attachable() {return false;}
  2069. /// \brief Returns the object immediately attached to this object
  2070. /// \return the attached transformation
  2071. /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
  2072. /// version of AttachedTransformation() always returns NULL.
  2073. virtual BufferedTransformation *AttachedTransformation() {CRYPTOPP_ASSERT(!Attachable()); return NULLPTR;}
  2074. /// \brief Returns the object immediately attached to this object
  2075. /// \return the attached transformation
  2076. /// \details AttachedTransformation() returns NULL if there is no attachment. The non-const
  2077. /// version of AttachedTransformation() always returns NULL.
  2078. virtual const BufferedTransformation *AttachedTransformation() const
  2079. {return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
  2080. /// \brief Delete the current attachment chain and attach a new one
  2081. /// \param newAttachment the new BufferedTransformation to attach
  2082. /// \throw NotImplemented
  2083. /// \details Detach() deletes the current attachment chain and replace it with an optional newAttachment
  2084. /// \details If a derived class does not override Detach(), then the base class throws
  2085. /// NotImplemented.
  2086. virtual void Detach(BufferedTransformation *newAttachment = NULLPTR) {
  2087. CRYPTOPP_UNUSED(newAttachment); CRYPTOPP_ASSERT(!Attachable());
  2088. throw NotImplemented("BufferedTransformation: this object is not attachable");
  2089. }
  2090. /// \brief Add newAttachment to the end of attachment chain
  2091. /// \param newAttachment the attachment to add to the end of the chain
  2092. virtual void Attach(BufferedTransformation *newAttachment);
  2093. //@}
  2094. protected:
  2095. /// \brief Decrements the propagation count while clamping at 0
  2096. /// \return the decremented propagation or 0
  2097. static int DecrementPropagation(int propagation)
  2098. {return propagation != 0 ? propagation - 1 : 0;}
  2099. private:
  2100. // for ChannelPutWord16, ChannelPutWord32 and ChannelPutWord64,
  2101. // to ensure the buffer isn't deallocated before non-blocking
  2102. // operation completes
  2103. byte m_buf[8];
  2104. };
  2105. /// \brief An input discarding BufferedTransformation
  2106. /// \return a reference to a BufferedTransformation object that discards all input
  2107. CRYPTOPP_DLL BufferedTransformation & TheBitBucket();
  2108. /// \brief Interface for crypto material
  2109. /// \details CryptoMaterial() is an interface for crypto material, such as
  2110. /// public keys, private keys and crypto parameters. Derived classes generally
  2111. /// do not offer public methods such as GenerateRandom() and
  2112. /// GenerateRandomWithKeySize().
  2113. /// \sa GeneratableCryptoMaterial()
  2114. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
  2115. {
  2116. public:
  2117. /// Exception thrown when invalid crypto material is detected
  2118. class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
  2119. {
  2120. public:
  2121. explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
  2122. };
  2123. virtual ~CryptoMaterial() {}
  2124. /// \brief Assign values to this object
  2125. /// \details This function can be used to create a public key from a private key.
  2126. virtual void AssignFrom(const NameValuePairs &source) =0;
  2127. /// \brief Check this object for errors
  2128. /// \param rng a RandomNumberGenerator for objects which use randomized testing
  2129. /// \param level the level of thoroughness
  2130. /// \return true if the tests succeed, false otherwise
  2131. /// \details There are four levels of thoroughness:
  2132. /// <ul>
  2133. /// <li>0 - using this object won't cause a crash or exception
  2134. /// <li>1 - this object will probably function, and encrypt, sign, other operations correctly
  2135. /// <li>2 - ensure this object will function correctly, and perform reasonable security checks
  2136. /// <li>3 - perform reasonable security checks, and do checks that may take a long time
  2137. /// </ul>
  2138. /// \details Level 0 does not require a RandomNumberGenerator. A NullRNG() can be used for level 0.
  2139. /// Level 1 may not check for weak keys and such. Levels 2 and 3 are recommended.
  2140. /// \sa ThrowIfInvalid()
  2141. virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
  2142. /// \brief Check this object for errors
  2143. /// \param rng a RandomNumberGenerator for objects which use randomized testing
  2144. /// \param level the level of thoroughness
  2145. /// \throw InvalidMaterial
  2146. /// \details Internally, ThrowIfInvalid() calls Validate() and throws InvalidMaterial() if validation fails.
  2147. /// \sa Validate()
  2148. virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
  2149. {if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
  2150. /// \brief Saves a key to a BufferedTransformation
  2151. /// \param bt the destination BufferedTransformation
  2152. /// \throw NotImplemented
  2153. /// \details Save() writes the material to a BufferedTransformation.
  2154. /// \details If the material is a key, then the key is written with ASN.1 DER encoding. The key
  2155. /// includes an object identifier with an algorithm id, like a subjectPublicKeyInfo.
  2156. /// \details A "raw" key without the "key info" can be saved using a key's DEREncode() method.
  2157. /// \details If a derived class does not override Save(), then the base class throws
  2158. /// NotImplemented().
  2159. virtual void Save(BufferedTransformation &bt) const
  2160. {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support saving");}
  2161. /// \brief Loads a key from a BufferedTransformation
  2162. /// \param bt the source BufferedTransformation
  2163. /// \throw KeyingErr
  2164. /// \details Load() attempts to read material from a BufferedTransformation. If the
  2165. /// material is a key that was generated outside the library, then the following
  2166. /// usually applies:
  2167. /// <ul>
  2168. /// <li>the key should be ASN.1 BER encoded
  2169. /// <li>the key should be a "key info"
  2170. /// </ul>
  2171. /// \details "key info" means the key should have an object identifier with an algorithm id,
  2172. /// like a subjectPublicKeyInfo.
  2173. /// \details To read a "raw" key without the "key info", then call the key's BERDecode() method.
  2174. /// \note Load() generally does not check that the key is valid. Call Validate(), if needed.
  2175. virtual void Load(BufferedTransformation &bt)
  2176. {CRYPTOPP_UNUSED(bt); throw NotImplemented("CryptoMaterial: this object does not support loading");}
  2177. /// \brief Determines whether the object supports precomputation
  2178. /// \return true if the object supports precomputation, false otherwise
  2179. /// \sa Precompute()
  2180. virtual bool SupportsPrecomputation() const {return false;}
  2181. /// \brief Perform precomputation
  2182. /// \param precomputationStorage the suggested number of objects for the precompute table
  2183. /// \throw NotImplemented
  2184. /// \details The exact semantics of Precompute() varies, but it typically means calculate
  2185. /// a table of n objects that can be used later to speed up computation.
  2186. /// \details If a derived class does not override Precompute(), then the base class throws
  2187. /// NotImplemented.
  2188. /// \sa SupportsPrecomputation(), LoadPrecomputation(), SavePrecomputation()
  2189. virtual void Precompute(unsigned int precomputationStorage) {
  2190. CRYPTOPP_UNUSED(precomputationStorage); CRYPTOPP_ASSERT(!SupportsPrecomputation());
  2191. throw NotImplemented("CryptoMaterial: this object does not support precomputation");
  2192. }
  2193. /// \brief Retrieve previously saved precomputation
  2194. /// \param storedPrecomputation BufferedTransformation with the saved precomputation
  2195. /// \throw NotImplemented
  2196. /// \sa SupportsPrecomputation(), Precompute()
  2197. virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
  2198. {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
  2199. /// \brief Save precomputation for later use
  2200. /// \param storedPrecomputation BufferedTransformation to write the precomputation
  2201. /// \throw NotImplemented
  2202. /// \sa SupportsPrecomputation(), Precompute()
  2203. virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
  2204. {CRYPTOPP_UNUSED(storedPrecomputation); CRYPTOPP_ASSERT(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
  2205. /// \brief Perform a quick sanity check
  2206. /// \details DoQuickSanityCheck() is for internal library use, and it should not be called by library users.
  2207. void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
  2208. #if defined(__SUNPRO_CC)
  2209. // Sun Studio 11/CC 5.8 workaround: it generates incorrect code
  2210. // when casting to an empty virtual base class. JW, 2018: It is
  2211. // still a problem in Sun Studio 12.6/CC 5.15 on i386. Just enable
  2212. // it everywhere in case it affects SPARC (which we don't test).
  2213. char m_sunCCworkaround;
  2214. #endif
  2215. };
  2216. /// \brief Interface for crypto material
  2217. /// \details GeneratableCryptoMaterial() is an interface for crypto material,
  2218. /// such as private keys and crypto parameters. Derived classes offer public
  2219. /// methods such as GenerateRandom() and GenerateRandomWithKeySize().
  2220. /// \sa CryptoMaterial()
  2221. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
  2222. {
  2223. public:
  2224. virtual ~GeneratableCryptoMaterial() {}
  2225. /// \brief Generate a random key or crypto parameters
  2226. /// \param rng a RandomNumberGenerator to produce keying material
  2227. /// \param params additional initialization parameters
  2228. /// \throw KeyingErr if a key can't be generated or algorithm parameters are invalid
  2229. /// \details If a derived class does not override GenerateRandom(), then the base class throws
  2230. /// NotImplemented.
  2231. virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params = g_nullNameValuePairs) {
  2232. CRYPTOPP_UNUSED(rng); CRYPTOPP_UNUSED(params);
  2233. throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");
  2234. }
  2235. /// \brief Generate a random key or crypto parameters
  2236. /// \param rng a RandomNumberGenerator to produce keying material
  2237. /// \param keySize the size of the key, in bits
  2238. /// \throw KeyingErr if a key can't be generated or algorithm parameters are invalid
  2239. /// \details GenerateRandomWithKeySize calls GenerateRandom() with a NameValuePairs
  2240. /// object with only "KeySize"
  2241. void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
  2242. };
  2243. /// \brief Interface for public keys
  2244. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
  2245. {
  2246. };
  2247. /// \brief Interface for private keys
  2248. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
  2249. {
  2250. };
  2251. /// \brief Interface for crypto parameters
  2252. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
  2253. {
  2254. };
  2255. /// \brief Interface for certificates
  2256. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Certificate : virtual public CryptoMaterial
  2257. {
  2258. };
  2259. /// \brief Interface for asymmetric algorithms
  2260. /// \details BERDecode() and DEREncode() were removed under Issue 569
  2261. /// and Commit 9b174e84de7a. Programs should use <tt>AccessMaterial().Load(bt)</tt>
  2262. /// or <tt>GetMaterial().Save(bt)</tt> instead.
  2263. /// \sa <A HREF="https://github.com/weidai11/cryptopp/issues/569">Issue 569</A>
  2264. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
  2265. {
  2266. public:
  2267. virtual ~AsymmetricAlgorithm() {}
  2268. /// \brief Retrieves a reference to CryptoMaterial
  2269. /// \return a reference to the crypto material
  2270. virtual CryptoMaterial & AccessMaterial() =0;
  2271. /// \brief Retrieves a reference to CryptoMaterial
  2272. /// \return a const reference to the crypto material
  2273. virtual const CryptoMaterial & GetMaterial() const =0;
  2274. #if 0
  2275. /// \brief Loads this object from a BufferedTransformation
  2276. /// \param bt a BufferedTransformation object
  2277. /// \details Use of BERDecode() changed to Load() at Issue 569.
  2278. /// \deprecated for backwards compatibility, calls <tt>AccessMaterial().Load(bt)</tt>
  2279. void BERDecode(BufferedTransformation &bt)
  2280. {AccessMaterial().Load(bt);}
  2281. /// \brief Saves this object to a BufferedTransformation
  2282. /// \param bt a BufferedTransformation object
  2283. /// \details Use of DEREncode() changed to Save() at Issue 569.
  2284. /// \deprecated for backwards compatibility, calls GetMaterial().Save(bt)
  2285. void DEREncode(BufferedTransformation &bt) const
  2286. {GetMaterial().Save(bt);}
  2287. #endif
  2288. };
  2289. /// \brief Interface for asymmetric algorithms using public keys
  2290. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
  2291. {
  2292. public:
  2293. virtual ~PublicKeyAlgorithm() {}
  2294. // VC60 workaround: no co-variant return type
  2295. /// \brief Retrieves a reference to a Public Key
  2296. /// \return a reference to the public key
  2297. CryptoMaterial & AccessMaterial()
  2298. {return AccessPublicKey();}
  2299. /// \brief Retrieves a reference to a Public Key
  2300. /// \return a const reference the public key
  2301. const CryptoMaterial & GetMaterial() const
  2302. {return GetPublicKey();}
  2303. /// \brief Retrieves a reference to a Public Key
  2304. /// \return a reference to the public key
  2305. virtual PublicKey & AccessPublicKey() =0;
  2306. /// \brief Retrieves a reference to a Public Key
  2307. /// \return a const reference the public key
  2308. virtual const PublicKey & GetPublicKey() const
  2309. {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
  2310. };
  2311. /// \brief Interface for asymmetric algorithms using private keys
  2312. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
  2313. {
  2314. public:
  2315. virtual ~PrivateKeyAlgorithm() {}
  2316. /// \brief Retrieves a reference to a Private Key
  2317. /// \return a reference the private key
  2318. CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
  2319. /// \brief Retrieves a reference to a Private Key
  2320. /// \return a const reference the private key
  2321. const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
  2322. /// \brief Retrieves a reference to a Private Key
  2323. /// \return a reference the private key
  2324. virtual PrivateKey & AccessPrivateKey() =0;
  2325. /// \brief Retrieves a reference to a Private Key
  2326. /// \return a const reference the private key
  2327. virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
  2328. };
  2329. /// \brief Interface for key agreement algorithms
  2330. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
  2331. {
  2332. public:
  2333. virtual ~KeyAgreementAlgorithm() {}
  2334. /// \brief Retrieves a reference to Crypto Parameters
  2335. /// \return a reference the crypto parameters
  2336. CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
  2337. /// \brief Retrieves a reference to Crypto Parameters
  2338. /// \return a const reference the crypto parameters
  2339. const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
  2340. /// \brief Retrieves a reference to Crypto Parameters
  2341. /// \return a reference the crypto parameters
  2342. virtual CryptoParameters & AccessCryptoParameters() =0;
  2343. /// \brief Retrieves a reference to Crypto Parameters
  2344. /// \return a const reference the crypto parameters
  2345. virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
  2346. };
  2347. /// \brief Interface for public-key encryptors and decryptors
  2348. /// \details This class provides an interface common to encryptors and decryptors
  2349. /// for querying their plaintext and ciphertext lengths.
  2350. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
  2351. {
  2352. public:
  2353. virtual ~PK_CryptoSystem() {}
  2354. /// \brief Provides the maximum length of plaintext for a given ciphertext length
  2355. /// \return the maximum size of the plaintext, in bytes
  2356. /// \details This function returns 0 if ciphertextLength is not valid (too long or too short).
  2357. virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
  2358. /// \brief Calculate the length of ciphertext given length of plaintext
  2359. /// \return the maximum size of the ciphertext, in bytes
  2360. /// \details This function returns 0 if plaintextLength is not valid (too long).
  2361. virtual size_t CiphertextLength(size_t plaintextLength) const =0;
  2362. /// \brief Determines whether this object supports the use of a named parameter
  2363. /// \param name the name of the parameter
  2364. /// \return true if the parameter name is supported, false otherwise
  2365. /// \details Some possible parameter names: EncodingParameters(), KeyDerivationParameters()
  2366. /// and others Parameters listed in argnames.h
  2367. virtual bool ParameterSupported(const char *name) const =0;
  2368. /// \brief Provides the fixed ciphertext length, if one exists
  2369. /// \return the fixed ciphertext length if one exists, otherwise 0
  2370. /// \details "Fixed" here means length of ciphertext does not depend on length of plaintext.
  2371. /// In this case, it usually does depend on the key length.
  2372. virtual size_t FixedCiphertextLength() const {return 0;}
  2373. /// \brief Provides the maximum plaintext length given a fixed ciphertext length
  2374. /// \return maximum plaintext length given the fixed ciphertext length, if one exists,
  2375. /// otherwise return 0.
  2376. /// \details FixedMaxPlaintextLength(0 returns the maximum plaintext length given the fixed ciphertext
  2377. /// length, if one exists, otherwise return 0.
  2378. virtual size_t FixedMaxPlaintextLength() const {return 0;}
  2379. };
  2380. /// \brief Interface for public-key encryptors
  2381. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
  2382. {
  2383. public:
  2384. /// \brief Exception thrown when trying to encrypt plaintext of invalid length
  2385. class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
  2386. {
  2387. public:
  2388. InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
  2389. };
  2390. /// \brief Encrypt a byte string
  2391. /// \param rng a RandomNumberGenerator derived class
  2392. /// \param plaintext the plaintext byte buffer
  2393. /// \param plaintextLength the size of the plaintext byte buffer
  2394. /// \param ciphertext a byte buffer to hold the encrypted string
  2395. /// \param parameters a set of NameValuePairs to initialize this object
  2396. /// \pre <tt>CiphertextLength(plaintextLength) != 0</tt> ensures the plaintext isn't too large
  2397. /// \pre <tt>COUNTOF(ciphertext) == CiphertextLength(plaintextLength)</tt> ensures the output
  2398. /// byte buffer is large enough.
  2399. /// \sa PK_Decryptor
  2400. virtual void Encrypt(RandomNumberGenerator &rng,
  2401. const byte *plaintext, size_t plaintextLength,
  2402. byte *ciphertext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
  2403. /// \brief Create a new encryption filter
  2404. /// \param rng a RandomNumberGenerator derived class
  2405. /// \param attachment an attached transformation
  2406. /// \param parameters a set of NameValuePairs to initialize this object
  2407. /// \details \p attachment can be \p NULL. The caller is responsible for deleting the returned pointer.
  2408. /// Encoding parameters should be passed in the "EP" channel.
  2409. virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
  2410. BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
  2411. };
  2412. /// \brief Interface for public-key decryptors
  2413. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
  2414. {
  2415. public:
  2416. virtual ~PK_Decryptor() {}
  2417. /// \brief Decrypt a byte string
  2418. /// \param rng a RandomNumberGenerator derived class
  2419. /// \param ciphertext the encrypted byte buffer
  2420. /// \param ciphertextLength the size of the encrypted byte buffer
  2421. /// \param plaintext a byte buffer to hold the decrypted string
  2422. /// \param parameters a set of NameValuePairs to initialize this object
  2423. /// \return the result of the decryption operation
  2424. /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
  2425. /// is valid and holds the actual length of the plaintext recovered. The result is undefined
  2426. /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
  2427. /// is undefined.
  2428. /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
  2429. /// byte buffer is large enough
  2430. /// \sa PK_Encryptor
  2431. virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
  2432. const byte *ciphertext, size_t ciphertextLength,
  2433. byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const =0;
  2434. /// \brief Create a new decryption filter
  2435. /// \param rng a RandomNumberGenerator derived class
  2436. /// \param attachment an attached transformation
  2437. /// \param parameters a set of NameValuePairs to initialize this object
  2438. /// \return the newly created decryption filter
  2439. /// \note the caller is responsible for deleting the returned pointer
  2440. virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
  2441. BufferedTransformation *attachment=NULLPTR, const NameValuePairs &parameters = g_nullNameValuePairs) const;
  2442. /// \brief Decrypt a fixed size ciphertext
  2443. /// \param rng a RandomNumberGenerator derived class
  2444. /// \param ciphertext the encrypted byte buffer
  2445. /// \param plaintext a byte buffer to hold the decrypted string
  2446. /// \param parameters a set of NameValuePairs to initialize this object
  2447. /// \return the result of the decryption operation
  2448. /// \details If DecodingResult::isValidCoding is true, then DecodingResult::messageLength
  2449. /// is valid and holds the actual length of the plaintext recovered. The result is undefined
  2450. /// if decryption failed. If DecodingResult::isValidCoding is false, then DecodingResult::messageLength
  2451. /// is undefined.
  2452. /// \pre <tt>COUNTOF(plaintext) == MaxPlaintextLength(ciphertextLength)</tt> ensures the output
  2453. /// byte buffer is large enough
  2454. /// \sa PK_Encryptor
  2455. DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs &parameters = g_nullNameValuePairs) const
  2456. {return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
  2457. };
  2458. /// \brief Interface for public-key signers and verifiers
  2459. /// \details This class provides an interface common to signers and verifiers for querying scheme properties
  2460. /// \sa DL_SignatureSchemeBase, TF_SignatureSchemeBase, DL_SignerBase, TF_SignerBase
  2461. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
  2462. {
  2463. public:
  2464. /// \brief Exception throw when the private or public key has a length that can't be used
  2465. /// \details InvalidKeyLength() may be thrown by any function in this class if the private
  2466. /// or public key has a length that can't be used
  2467. class CRYPTOPP_DLL InvalidKeyLength : public Exception
  2468. {
  2469. public:
  2470. InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
  2471. };
  2472. /// \brief Exception throw when the private or public key is too short to sign or verify
  2473. /// \details KeyTooShort() may be thrown by any function in this class if the private or public
  2474. /// key is too short to sign or verify anything
  2475. class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
  2476. {
  2477. public:
  2478. KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
  2479. };
  2480. virtual ~PK_SignatureScheme() {}
  2481. /// \brief Provides the signature length if it only depends on the key
  2482. /// \return the signature length if it only depends on the key, in bytes
  2483. /// \details SignatureLength() returns the signature length if it only depends on the key, otherwise 0.
  2484. virtual size_t SignatureLength() const =0;
  2485. /// \brief Provides the maximum signature length produced given the length of the recoverable message part
  2486. /// \param recoverablePartLength the length of the recoverable message part, in bytes
  2487. /// \return the maximum signature length produced for a given length of recoverable message part, in bytes
  2488. /// \details MaxSignatureLength() returns the maximum signature length produced given the length of the
  2489. /// recoverable message part.
  2490. virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const
  2491. {CRYPTOPP_UNUSED(recoverablePartLength); return SignatureLength();}
  2492. /// \brief Provides the length of longest message that can be recovered
  2493. /// \return the length of longest message that can be recovered, in bytes
  2494. /// \details MaxRecoverableLength() returns the length of longest message that can be recovered, or 0 if
  2495. /// this signature scheme does not support message recovery.
  2496. virtual size_t MaxRecoverableLength() const =0;
  2497. /// \brief Provides the length of longest message that can be recovered from a signature of given length
  2498. /// \param signatureLength the length of the signature, in bytes
  2499. /// \return the length of longest message that can be recovered from a signature of given length, in bytes
  2500. /// \details MaxRecoverableLengthFromSignatureLength() returns the length of longest message that can be
  2501. /// recovered from a signature of given length, or 0 if this signature scheme does not support message
  2502. /// recovery.
  2503. virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
  2504. /// \brief Determines whether a signature scheme requires a random number generator
  2505. /// \return true if the signature scheme requires a RandomNumberGenerator() to sign
  2506. /// \details if IsProbabilistic() returns false, then NullRNG() can be passed to functions that take
  2507. /// RandomNumberGenerator().
  2508. virtual bool IsProbabilistic() const =0;
  2509. /// \brief Determines whether the non-recoverable message part can be signed
  2510. /// \return true if the non-recoverable message part can be signed
  2511. virtual bool AllowNonrecoverablePart() const =0;
  2512. /// \brief Determines whether the signature must be input before the message
  2513. /// \return true if the signature must be input before the message during verifcation
  2514. /// \details if SignatureUpfront() returns true, then you must input the signature before the message
  2515. /// during verification. Otherwise you can input the signature at anytime.
  2516. virtual bool SignatureUpfront() const {return false;}
  2517. /// \brief Determines whether the recoverable part must be input before the non-recoverable part
  2518. /// \return true if the recoverable part must be input before the non-recoverable part during signing
  2519. /// \details RecoverablePartFirst() determines whether you must input the recoverable part before the
  2520. /// non-recoverable part during signing
  2521. virtual bool RecoverablePartFirst() const =0;
  2522. };
  2523. /// \brief Interface for accumulating messages to be signed or verified
  2524. /// \details Only Update() should be called from the PK_MessageAccumulator() class. No other functions
  2525. /// inherited from HashTransformation, like DigestSize() and TruncatedFinal(), should be called.
  2526. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
  2527. {
  2528. public:
  2529. /// \warning DigestSize() should not be called on PK_MessageAccumulator
  2530. unsigned int DigestSize() const
  2531. {throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
  2532. /// \warning TruncatedFinal() should not be called on PK_MessageAccumulator
  2533. void TruncatedFinal(byte *digest, size_t digestSize)
  2534. {
  2535. CRYPTOPP_UNUSED(digest); CRYPTOPP_UNUSED(digestSize);
  2536. throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");
  2537. }
  2538. };
  2539. /// \brief Interface for public-key signers
  2540. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
  2541. {
  2542. public:
  2543. virtual ~PK_Signer() {}
  2544. /// \brief Create a new HashTransformation to accumulate the message to be signed
  2545. /// \param rng a RandomNumberGenerator derived class
  2546. /// \return a pointer to a PK_MessageAccumulator
  2547. /// \details NewSignatureAccumulator() can be used with all signing methods. Sign() will automatically delete the
  2548. /// accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
  2549. virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
  2550. /// \brief Input a recoverable message to an accumulator
  2551. /// \param messageAccumulator a reference to a PK_MessageAccumulator
  2552. /// \param recoverableMessage a pointer to the recoverable message part to be signed
  2553. /// \param recoverableMessageLength the size of the recoverable message part
  2554. virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
  2555. /// \brief Sign and delete the messageAccumulator
  2556. /// \param rng a RandomNumberGenerator derived class
  2557. /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
  2558. /// \param signature a block of bytes for the signature
  2559. /// \return actual signature length
  2560. /// \details Sign() deletes the messageAccumulator, even if an exception is thrown.
  2561. /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
  2562. virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
  2563. /// \brief Sign and restart messageAccumulator
  2564. /// \param rng a RandomNumberGenerator derived class
  2565. /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
  2566. /// \param signature a block of bytes for the signature
  2567. /// \param restart flag indicating whether the messageAccumulator should be restarted
  2568. /// \return actual signature length
  2569. /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
  2570. virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
  2571. /// \brief Sign a message
  2572. /// \param rng a RandomNumberGenerator derived class
  2573. /// \param message a pointer to the message
  2574. /// \param messageLen the size of the message to be signed
  2575. /// \param signature a block of bytes for the signature
  2576. /// \return actual signature length
  2577. /// \pre <tt>COUNTOF(signature) == MaxSignatureLength()</tt>
  2578. virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
  2579. /// \brief Sign a recoverable message
  2580. /// \param rng a RandomNumberGenerator derived class
  2581. /// \param recoverableMessage a pointer to the recoverable message part to be signed
  2582. /// \param recoverableMessageLength the size of the recoverable message part
  2583. /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
  2584. /// \param nonrecoverableMessageLength the size of the non-recoverable message part
  2585. /// \param signature a block of bytes for the signature
  2586. /// \return actual signature length
  2587. /// \pre <tt>COUNTOF(signature) == MaxSignatureLength(recoverableMessageLength)</tt>
  2588. virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
  2589. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
  2590. };
  2591. /// \brief Interface for public-key signature verifiers
  2592. /// \details The Recover* functions throw NotImplemented if the signature scheme does not support
  2593. /// message recovery.
  2594. /// \details The Verify* functions throw InvalidDataFormat if the scheme does support message
  2595. /// recovery and the signature contains a non-empty recoverable message part. The
  2596. /// Recover* functions should be used in that case.
  2597. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
  2598. {
  2599. public:
  2600. virtual ~PK_Verifier() {}
  2601. /// \brief Create a new HashTransformation to accumulate the message to be verified
  2602. /// \return a pointer to a PK_MessageAccumulator
  2603. /// \details NewVerificationAccumulator() can be used with all verification methods. Verify() will automatically delete
  2604. /// the accumulator pointer. The caller is responsible for deletion if a method is called that takes a reference.
  2605. virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
  2606. /// \brief Input signature into a message accumulator
  2607. /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
  2608. /// \param signature the signature on the message
  2609. /// \param signatureLength the size of the signature
  2610. virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
  2611. /// \brief Check whether messageAccumulator contains a valid signature and message
  2612. /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
  2613. /// \return true if the signature is valid, false otherwise
  2614. /// \details Verify() deletes the messageAccumulator, even if an exception is thrown.
  2615. virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
  2616. /// \brief Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
  2617. /// \param messageAccumulator a reference to a PK_MessageAccumulator derived class
  2618. /// \return true if the signature is valid, false otherwise
  2619. /// \details VerifyAndRestart() restarts the messageAccumulator
  2620. virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
  2621. /// \brief Check whether input signature is a valid signature for input message
  2622. /// \param message a pointer to the message to be verified
  2623. /// \param messageLen the size of the message
  2624. /// \param signature a pointer to the signature over the message
  2625. /// \param signatureLen the size of the signature
  2626. /// \return true if the signature is valid, false otherwise
  2627. virtual bool VerifyMessage(const byte *message, size_t messageLen,
  2628. const byte *signature, size_t signatureLen) const;
  2629. /// \brief Recover a message from its signature
  2630. /// \param recoveredMessage a pointer to the recoverable message part to be verified
  2631. /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
  2632. /// \return the result of the verification operation
  2633. /// \details Recover() deletes the messageAccumulator, even if an exception is thrown.
  2634. /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
  2635. virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
  2636. /// \brief Recover a message from its signature
  2637. /// \param recoveredMessage a pointer to the recoverable message part to be verified
  2638. /// \param messageAccumulator a pointer to a PK_MessageAccumulator derived class
  2639. /// \return the result of the verification operation
  2640. /// \details RecoverAndRestart() restarts the messageAccumulator
  2641. /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
  2642. virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
  2643. /// \brief Recover a message from its signature
  2644. /// \param recoveredMessage a pointer for the recovered message
  2645. /// \param nonrecoverableMessage a pointer to the non-recoverable message part to be signed
  2646. /// \param nonrecoverableMessageLength the size of the non-recoverable message part
  2647. /// \param signature the signature on the message
  2648. /// \param signatureLength the size of the signature
  2649. /// \return the result of the verification operation
  2650. /// \pre <tt>COUNTOF(recoveredMessage) == MaxRecoverableLengthFromSignatureLength(signatureLength)</tt>
  2651. virtual DecodingResult RecoverMessage(byte *recoveredMessage,
  2652. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
  2653. const byte *signature, size_t signatureLength) const;
  2654. };
  2655. /// \brief Interface for domains of simple key agreement protocols
  2656. /// \details A key agreement domain is a set of parameters that must be shared
  2657. /// by two parties in a key agreement protocol, along with the algorithms
  2658. /// for generating key pairs and deriving agreed values.
  2659. /// \since Crypto++ 3.0
  2660. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
  2661. {
  2662. public:
  2663. virtual ~SimpleKeyAgreementDomain() {}
  2664. /// \brief Provides the size of the agreed value
  2665. /// \return size of agreed value produced in this domain
  2666. virtual unsigned int AgreedValueLength() const =0;
  2667. /// \brief Provides the size of the private key
  2668. /// \return size of private keys in this domain
  2669. virtual unsigned int PrivateKeyLength() const =0;
  2670. /// \brief Provides the size of the public key
  2671. /// \return size of public keys in this domain
  2672. virtual unsigned int PublicKeyLength() const =0;
  2673. /// \brief Generate private key in this domain
  2674. /// \param rng a RandomNumberGenerator derived class
  2675. /// \param privateKey a byte buffer for the generated private key in this domain
  2676. /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
  2677. virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  2678. /// \brief Generate a public key from a private key in this domain
  2679. /// \param rng a RandomNumberGenerator derived class
  2680. /// \param privateKey a byte buffer with the previously generated private key
  2681. /// \param publicKey a byte buffer for the generated public key in this domain
  2682. /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
  2683. virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  2684. /// \brief Generate a private/public key pair
  2685. /// \param rng a RandomNumberGenerator derived class
  2686. /// \param privateKey a byte buffer for the generated private key in this domain
  2687. /// \param publicKey a byte buffer for the generated public key in this domain
  2688. /// \details GenerateKeyPair() is equivalent to calling GeneratePrivateKey() and then GeneratePublicKey().
  2689. /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
  2690. /// \pre <tt>COUNTOF(publicKey) == PublicKeyLength()</tt>
  2691. virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  2692. /// \brief Derive agreed value
  2693. /// \param agreedValue a byte buffer for the shared secret
  2694. /// \param privateKey a byte buffer with your private key in this domain
  2695. /// \param otherPublicKey a byte buffer with the other party's public key in this domain
  2696. /// \param validateOtherPublicKey a flag indicating if the other party's public key should be validated
  2697. /// \return true upon success, false in case of failure
  2698. /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
  2699. /// \details The other party's public key is validated by default. If you have previously validated the
  2700. /// static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
  2701. /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
  2702. /// \pre <tt>COUNTOF(privateKey) == PrivateKeyLength()</tt>
  2703. /// \pre <tt>COUNTOF(otherPublicKey) == PublicKeyLength()</tt>
  2704. virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
  2705. };
  2706. /// \brief Interface for domains of authenticated key agreement protocols
  2707. /// \details In an authenticated key agreement protocol, each party has two
  2708. /// key pairs. The long-lived key pair is called the static key pair,
  2709. /// and the short-lived key pair is called the ephemeral key pair.
  2710. /// \since Crypto++ 3.0
  2711. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
  2712. {
  2713. public:
  2714. virtual ~AuthenticatedKeyAgreementDomain() {}
  2715. /// \brief Provides the size of the agreed value
  2716. /// \return size of agreed value produced in this domain
  2717. virtual unsigned int AgreedValueLength() const =0;
  2718. /// \brief Provides the size of the static private key
  2719. /// \return size of static private keys in this domain
  2720. virtual unsigned int StaticPrivateKeyLength() const =0;
  2721. /// \brief Provides the size of the static public key
  2722. /// \return size of static public keys in this domain
  2723. virtual unsigned int StaticPublicKeyLength() const =0;
  2724. /// \brief Generate static private key in this domain
  2725. /// \param rng a RandomNumberGenerator derived class
  2726. /// \param privateKey a byte buffer for the generated private key in this domain
  2727. /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
  2728. virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  2729. /// \brief Generate a static public key from a private key in this domain
  2730. /// \param rng a RandomNumberGenerator derived class
  2731. /// \param privateKey a byte buffer with the previously generated private key
  2732. /// \param publicKey a byte buffer for the generated public key in this domain
  2733. /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
  2734. virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  2735. /// \brief Generate a static private/public key pair
  2736. /// \param rng a RandomNumberGenerator derived class
  2737. /// \param privateKey a byte buffer for the generated private key in this domain
  2738. /// \param publicKey a byte buffer for the generated public key in this domain
  2739. /// \details GenerateStaticKeyPair() is equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey().
  2740. /// \pre <tt>COUNTOF(privateKey) == PrivateStaticKeyLength()</tt>
  2741. /// \pre <tt>COUNTOF(publicKey) == PublicStaticKeyLength()</tt>
  2742. virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  2743. /// \brief Provides the size of ephemeral private key
  2744. /// \return the size of ephemeral private key in this domain
  2745. virtual unsigned int EphemeralPrivateKeyLength() const =0;
  2746. /// \brief Provides the size of ephemeral public key
  2747. /// \return the size of ephemeral public key in this domain
  2748. virtual unsigned int EphemeralPublicKeyLength() const =0;
  2749. /// \brief Generate ephemeral private key
  2750. /// \param rng a RandomNumberGenerator derived class
  2751. /// \param privateKey a byte buffer for the generated private key in this domain
  2752. /// \pre <tt>COUNTOF(privateKey) == PrivateEphemeralKeyLength()</tt>
  2753. virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
  2754. /// \brief Generate ephemeral public key
  2755. /// \param rng a RandomNumberGenerator derived class
  2756. /// \param privateKey a byte buffer for the generated private key in this domain
  2757. /// \param publicKey a byte buffer for the generated public key in this domain
  2758. /// \pre <tt>COUNTOF(publicKey) == PublicEphemeralKeyLength()</tt>
  2759. virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
  2760. /// \brief Generate private/public key pair
  2761. /// \param rng a RandomNumberGenerator derived class
  2762. /// \param privateKey a byte buffer for the generated private key in this domain
  2763. /// \param publicKey a byte buffer for the generated public key in this domain
  2764. /// \details GenerateEphemeralKeyPair() is equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey()
  2765. virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
  2766. /// \brief Derive agreed value
  2767. /// \param agreedValue a byte buffer for the shared secret
  2768. /// \param staticPrivateKey a byte buffer with your static private key in this domain
  2769. /// \param ephemeralPrivateKey a byte buffer with your ephemeral private key in this domain
  2770. /// \param staticOtherPublicKey a byte buffer with the other party's static public key in this domain
  2771. /// \param ephemeralOtherPublicKey a byte buffer with the other party's ephemeral public key in this domain
  2772. /// \param validateStaticOtherPublicKey a flag indicating if the other party's public key should be validated
  2773. /// \return true upon success, false in case of failure
  2774. /// \details Agree() derives an agreed value from your private keys and couterparty's public keys.
  2775. /// \details The other party's ephemeral public key is validated by default. If you have previously validated
  2776. /// the static public key, use <tt>validateStaticOtherPublicKey=false</tt> to save time.
  2777. /// \pre <tt>COUNTOF(agreedValue) == AgreedValueLength()</tt>
  2778. /// \pre <tt>COUNTOF(staticPrivateKey) == StaticPrivateKeyLength()</tt>
  2779. /// \pre <tt>COUNTOF(ephemeralPrivateKey) == EphemeralPrivateKeyLength()</tt>
  2780. /// \pre <tt>COUNTOF(staticOtherPublicKey) == StaticPublicKeyLength()</tt>
  2781. /// \pre <tt>COUNTOF(ephemeralOtherPublicKey) == EphemeralPublicKeyLength()</tt>
  2782. virtual bool Agree(byte *agreedValue,
  2783. const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
  2784. const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
  2785. bool validateStaticOtherPublicKey=true) const =0;
  2786. };
  2787. // interface for password authenticated key agreement protocols, not implemented yet
  2788. #if 0
  2789. /// \brief Interface for protocol sessions
  2790. /*! The methods should be called in the following order:
  2791. InitializeSession(rng, parameters); // or call initialize method in derived class
  2792. while (true)
  2793. {
  2794. if (OutgoingMessageAvailable())
  2795. {
  2796. length = GetOutgoingMessageLength();
  2797. GetOutgoingMessage(message);
  2798. ; // send outgoing message
  2799. }
  2800. if (LastMessageProcessed())
  2801. break;
  2802. ; // receive incoming message
  2803. ProcessIncomingMessage(message);
  2804. }
  2805. ; // call methods in derived class to obtain result of protocol session
  2806. */
  2807. class ProtocolSession
  2808. {
  2809. public:
  2810. /// Exception thrown when an invalid protocol message is processed
  2811. class ProtocolError : public Exception
  2812. {
  2813. public:
  2814. ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
  2815. };
  2816. /// Exception thrown when a function is called unexpectedly
  2817. /*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
  2818. class UnexpectedMethodCall : public Exception
  2819. {
  2820. public:
  2821. UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
  2822. };
  2823. virtual ~ProtocolSession() {}
  2824. ProtocolSession() : m_rng(NULLPTR), m_throwOnProtocolError(true), m_validState(false) {}
  2825. virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs &parameters) =0;
  2826. bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
  2827. void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
  2828. bool HasValidState() const {return m_validState;}
  2829. virtual bool OutgoingMessageAvailable() const =0;
  2830. virtual unsigned int GetOutgoingMessageLength() const =0;
  2831. virtual void GetOutgoingMessage(byte *message) =0;
  2832. virtual bool LastMessageProcessed() const =0;
  2833. virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
  2834. protected:
  2835. void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
  2836. void CheckAndHandleInvalidState() const;
  2837. void SetValidState(bool valid) {m_validState = valid;}
  2838. RandomNumberGenerator *m_rng;
  2839. private:
  2840. bool m_throwOnProtocolError, m_validState;
  2841. };
  2842. class KeyAgreementSession : public ProtocolSession
  2843. {
  2844. public:
  2845. virtual ~KeyAgreementSession() {}
  2846. virtual unsigned int GetAgreedValueLength() const =0;
  2847. virtual void GetAgreedValue(byte *agreedValue) const =0;
  2848. };
  2849. class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
  2850. {
  2851. public:
  2852. virtual ~PasswordAuthenticatedKeyAgreementSession() {}
  2853. void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
  2854. const byte *myId, unsigned int myIdLength,
  2855. const byte *counterPartyId, unsigned int counterPartyIdLength,
  2856. const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
  2857. };
  2858. /// \brief Password based key agreement domain
  2859. /// \since Crypto++ 3.0
  2860. class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
  2861. {
  2862. public:
  2863. virtual ~PasswordAuthenticatedKeyAgreementDomain() {}
  2864. /// return whether the domain parameters stored in this object are valid
  2865. virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
  2866. {return GetCryptoParameters().Validate(rng, 2);}
  2867. virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
  2868. virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
  2869. enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
  2870. virtual bool IsValidRole(unsigned int role) =0;
  2871. virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
  2872. };
  2873. #endif
  2874. /// \brief Exception thrown when an ASN.1 BER decoing error is encountered
  2875. class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
  2876. {
  2877. public:
  2878. BERDecodeErr() : InvalidArgument("BER decode error") {}
  2879. BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
  2880. };
  2881. /// \brief Interface for encoding and decoding ASN1 objects
  2882. /// \details Each class that derives from ASN1Object should provide a serialization format
  2883. /// that controls subobject layout. Most of the time the serialization format is
  2884. /// taken from a standard, like P1363 or an RFC.
  2885. class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
  2886. {
  2887. public:
  2888. virtual ~ASN1Object() {}
  2889. /// \brief Decode this object from a BufferedTransformation
  2890. /// \param bt BufferedTransformation object
  2891. /// \details Uses Basic Encoding Rules (BER)
  2892. virtual void BERDecode(BufferedTransformation &bt) =0;
  2893. /// \brief Encode this object into a BufferedTransformation
  2894. /// \param bt BufferedTransformation object
  2895. /// \details Uses Distinguished Encoding Rules (DER)
  2896. virtual void DEREncode(BufferedTransformation &bt) const =0;
  2897. /// \brief Encode this object into a BufferedTransformation
  2898. /// \param bt BufferedTransformation object
  2899. /// \details Uses Basic Encoding Rules (BER).
  2900. /// \details This may be useful if DEREncode() would be too inefficient.
  2901. virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
  2902. };
  2903. /// \brief Specifies the build-time version of the library
  2904. /// \return integer representing the build-time version
  2905. /// \details LibraryVersion can help detect inadvertent mixing and matching of library
  2906. /// versions. When using Crypto++ distributed by a third party, LibraryVersion()
  2907. /// records the version of the shared object that was built by the third party.
  2908. /// The LibraryVersion() record resides in <tt>cryptlib.o</tt> on Unix compatibles
  2909. /// and <tt>cryptlib.obj</tt> on Windows. It does not change when an app links
  2910. /// to the library.
  2911. /// \details LibraryVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
  2912. /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
  2913. /// the library version is 5.7 or above. If it is missing, then the library version is
  2914. /// 5.6.5 or below.
  2915. /// \details The function could be used as shown below.
  2916. /// <pre> if (LibraryVersion() != HeaderVersion())
  2917. /// {
  2918. /// cout << "Potential version mismatch" << endl;
  2919. ///
  2920. /// const int lmaj = (LibraryVersion() / 100U) % 10;
  2921. /// const int lmin = (LibraryVersion() / 10U) % 10;
  2922. /// const int hmaj = (HeaderVersion() / 100U) % 10;
  2923. /// const int hmin = (HeaderVersion() / 10U) % 10;
  2924. ///
  2925. /// if(lmaj != hmaj)
  2926. /// cout << "Major version mismatch" << endl;
  2927. /// else if(lmin != hmin)
  2928. /// cout << "Minor version mismatch" << endl;
  2929. /// }
  2930. /// </pre>
  2931. /// \sa HeaderVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
  2932. /// \since Crypto++ 6.0
  2933. extern "C" {
  2934. int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT);
  2935. } // C linkage
  2936. /// \brief Specifies the runtime version of the library
  2937. /// \return integer representing the runtime version
  2938. /// \details HeaderVersion() can help detect inadvertent mixing and matching of library
  2939. /// versions. When using Crypto++ distributed by a third party, HeaderVersion()
  2940. /// records the version of the headers used by the app when the app is compiled.
  2941. /// \details HeaderVersion() is declared with C linkage (<tt>extern "C"</tt>) within the
  2942. /// CryptoPP namespace to help programs locate the symbol. If the symbol is present, then
  2943. /// the library version is 5.7 or above. If it is missing, then the library version is
  2944. /// 5.6.5 or below.
  2945. /// \details The function could be used as shown below.
  2946. /// <pre> if (LibraryVersion() != HeaderVersion())
  2947. /// {
  2948. /// cout << "Potential version mismatch" << endl;
  2949. ///
  2950. /// const int lmaj = (LibraryVersion() / 100U) % 10;
  2951. /// const int lmin = (LibraryVersion() / 10U) % 10;
  2952. /// const int hmaj = (HeaderVersion() / 100U) % 10;
  2953. /// const int hmin = (HeaderVersion() / 10U) % 10;
  2954. ///
  2955. /// if(lmaj != hmaj)
  2956. /// cout << "Major version mismatch" << endl;
  2957. /// else if(lmin != hmin)
  2958. /// cout << "Minor version mismatch" << endl;
  2959. /// }
  2960. /// </pre>
  2961. /// \sa LibraryVersion(), <A HREF="http://github.com/weidai11/cryptopp/issues/371">GitHub Issue 371</A>.
  2962. /// \since Crypto++ 6.0
  2963. extern "C" {
  2964. inline int HeaderVersion()
  2965. {
  2966. return CRYPTOPP_VERSION;
  2967. }
  2968. } // C linkage
  2969. NAMESPACE_END
  2970. #if CRYPTOPP_MSC_VERSION
  2971. # pragma warning(pop)
  2972. #endif
  2973. #endif