cryptlib.h 174 KB

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