Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

949 lines
29 KiB

  1. // cryptlib.cpp - written and placed in the public domain by Wei Dai
  2. #include "pch.h"
  3. #include "config.h"
  4. #if CRYPTOPP_MSC_VERSION
  5. # pragma warning(disable: 4127 4189 4459)
  6. #endif
  7. #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
  8. # pragma GCC diagnostic ignored "-Wunused-value"
  9. # pragma GCC diagnostic ignored "-Wunused-variable"
  10. # pragma GCC diagnostic ignored "-Wunused-parameter"
  11. #endif
  12. #ifndef CRYPTOPP_IMPORTS
  13. #include "cryptlib.h"
  14. #include "misc.h"
  15. #include "filters.h"
  16. #include "algparam.h"
  17. #include "fips140.h"
  18. #include "argnames.h"
  19. #include "fltrimpl.h"
  20. #include "trdlocal.h"
  21. #include "osrng.h"
  22. #include "secblock.h"
  23. #include "smartptr.h"
  24. // http://www.cygwin.com/faq.html#faq.api.winsock
  25. #if (defined(__CYGWIN__) || defined(__CYGWIN32__)) && defined(PREFER_WINDOWS_STYLE_SOCKETS)
  26. # error Cygwin does not support Windows style sockets. See http://www.cygwin.com/faq.html#faq.api.winsock
  27. #endif
  28. // MacPorts/GCC does not provide init_priority(priority). Apple/GCC and Fink/GCC do provide it.
  29. #define HAVE_GCC_INIT_PRIORITY (__GNUC__ && (CRYPTOPP_INIT_PRIORITY > 0) && !(MACPORTS_GCC_COMPILER > 0))
  30. #define HAVE_MSC_INIT_PRIORITY (_MSC_VER && (CRYPTOPP_INIT_PRIORITY > 0))
  31. NAMESPACE_BEGIN(CryptoPP)
  32. CRYPTOPP_COMPILE_ASSERT(sizeof(byte) == 1);
  33. CRYPTOPP_COMPILE_ASSERT(sizeof(word16) == 2);
  34. CRYPTOPP_COMPILE_ASSERT(sizeof(word32) == 4);
  35. CRYPTOPP_COMPILE_ASSERT(sizeof(word64) == 8);
  36. #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
  37. CRYPTOPP_COMPILE_ASSERT(sizeof(dword) == 2*sizeof(word));
  38. #endif
  39. #if HAVE_GCC_INIT_PRIORITY
  40. CRYPTOPP_COMPILE_ASSERT(CRYPTOPP_INIT_PRIORITY >= 101);
  41. const std::string DEFAULT_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 25)));
  42. const std::string AAD_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 26))) = "AAD";
  43. const std::string &BufferedTransformation::NULL_CHANNEL = DEFAULT_CHANNEL;
  44. #elif HAVE_MSC_INIT_PRIORITY
  45. #pragma warning(disable: 4073)
  46. #pragma init_seg(lib)
  47. const std::string DEFAULT_CHANNEL;
  48. const std::string AAD_CHANNEL = "AAD";
  49. const std::string &BufferedTransformation::NULL_CHANNEL = DEFAULT_CHANNEL;
  50. #pragma warning(default: 4073)
  51. #else
  52. // VALVE, changed DEFAULT_CHANNEL to a basic type from std::string
  53. //const std::string DEFAULT_CHANNEL;
  54. const char * DEFAULT_CHANNEL = "";
  55. const std::string AAD_CHANNEL = "AAD";
  56. const std::string &BufferedTransformation::NULL_CHANNEL = DEFAULT_CHANNEL;
  57. #endif
  58. class NullNameValuePairs : public NameValuePairs
  59. {
  60. public:
  61. NullNameValuePairs() {}
  62. bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
  63. {CRYPTOPP_UNUSED(name); CRYPTOPP_UNUSED(valueType); CRYPTOPP_UNUSED(pValue); return false;}
  64. };
  65. // VALVE: Our debug allocator doesn't much care for global objects like this, it registers them
  66. // as a memory leak during validation. So make them const.
  67. //#if HAVE_GCC_INIT_PRIORITY
  68. //const simple_ptr<NullNameValuePairs> s_pNullNameValuePairs __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 30))) = new NullNameValuePairs;
  69. //const NameValuePairs &g_nullNameValuePairs = *s_pNullNameValuePairs.m_p;
  70. //#else
  71. //const simple_ptr<NullNameValuePairs> s_pNullNameValuePairs(new NullNameValuePairs);
  72. //const NameValuePairs &g_nullNameValuePairs = *s_pNullNameValuePairs.m_p;
  73. //#endif
  74. const NullNameValuePairs s_NullNameValuePairs;
  75. const NameValuePairs &g_nullNameValuePairs = s_NullNameValuePairs;
  76. BufferedTransformation & TheBitBucket()
  77. {
  78. static BitBucket bitBucket;
  79. return bitBucket;
  80. }
  81. Algorithm::Algorithm(bool checkSelfTestStatus)
  82. {
  83. if (checkSelfTestStatus && FIPS_140_2_ComplianceEnabled())
  84. {
  85. if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_NOT_DONE && !PowerUpSelfTestInProgressOnThisThread())
  86. throw SelfTestFailure("Cryptographic algorithms are disabled before the power-up self tests are performed.");
  87. if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_FAILED)
  88. throw SelfTestFailure("Cryptographic algorithms are disabled after a power-up self test failed.");
  89. }
  90. }
  91. void SimpleKeyingInterface::SetKey(const byte *key, size_t length, const NameValuePairs &params)
  92. {
  93. this->ThrowIfInvalidKeyLength(length);
  94. this->UncheckedSetKey(key, (unsigned int)length, params);
  95. }
  96. void SimpleKeyingInterface::SetKeyWithRounds(const byte *key, size_t length, int rounds)
  97. {
  98. SetKey(key, length, MakeParameters(Name::Rounds(), rounds));
  99. }
  100. void SimpleKeyingInterface::SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
  101. {
  102. SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, ivLength)));
  103. }
  104. void SimpleKeyingInterface::ThrowIfInvalidKeyLength(size_t length)
  105. {
  106. if (!IsValidKeyLength(length))
  107. throw InvalidKeyLength(GetAlgorithm().AlgorithmName(), length);
  108. }
  109. void SimpleKeyingInterface::ThrowIfResynchronizable()
  110. {
  111. if (IsResynchronizable())
  112. throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object requires an IV");
  113. }
  114. void SimpleKeyingInterface::ThrowIfInvalidIV(const byte *iv)
  115. {
  116. if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
  117. throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object cannot use a null IV");
  118. }
  119. size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(int size)
  120. {
  121. if (size < 0)
  122. return IVSize();
  123. else if ((size_t)size < MinIVLength())
  124. throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(size) + " is less than the minimum of " + IntToString(MinIVLength()));
  125. else if ((size_t)size > MaxIVLength())
  126. throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(size) + " exceeds the maximum of " + IntToString(MaxIVLength()));
  127. else
  128. return size;
  129. }
  130. const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size)
  131. {
  132. ConstByteArrayParameter ivWithLength;
  133. const byte *iv;
  134. bool found = false;
  135. try {found = params.GetValue(Name::IV(), ivWithLength);}
  136. catch (const NameValuePairs::ValueTypeMismatch &) {}
  137. if (found)
  138. {
  139. iv = ivWithLength.begin();
  140. ThrowIfInvalidIV(iv);
  141. size = ThrowIfInvalidIVLength((int)ivWithLength.size());
  142. return iv;
  143. }
  144. else if (params.GetValue(Name::IV(), iv))
  145. {
  146. ThrowIfInvalidIV(iv);
  147. size = IVSize();
  148. return iv;
  149. }
  150. else
  151. {
  152. ThrowIfResynchronizable();
  153. size = 0;
  154. return NULL;
  155. }
  156. }
  157. void SimpleKeyingInterface::GetNextIV(RandomNumberGenerator &rng, byte *IV)
  158. {
  159. rng.GenerateBlock(IV, IVSize());
  160. }
  161. size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const
  162. {
  163. assert(inBlocks);
  164. assert(outBlocks);
  165. assert(length);
  166. size_t blockSize = BlockSize();
  167. size_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize;
  168. size_t xorIncrement = xorBlocks ? blockSize : 0;
  169. size_t outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : blockSize;
  170. if (flags & BT_ReverseDirection)
  171. {
  172. assert(length % blockSize == 0);
  173. inBlocks += length - blockSize;
  174. xorBlocks += length - blockSize;
  175. outBlocks += length - blockSize;
  176. inIncrement = 0-inIncrement;
  177. xorIncrement = 0-xorIncrement;
  178. outIncrement = 0-outIncrement;
  179. }
  180. while (length >= blockSize)
  181. {
  182. if (flags & BT_XorInput)
  183. {
  184. // Coverity finding. However, xorBlocks is never NULL if BT_XorInput.
  185. assert(xorBlocks);
  186. #if defined(__COVERITY__)
  187. if (xorBlocks)
  188. #endif
  189. xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
  190. ProcessBlock(outBlocks);
  191. }
  192. else
  193. {
  194. // xorBlocks can be NULL. See, for example, ECB_OneWay::ProcessData.
  195. ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
  196. }
  197. if (flags & BT_InBlockIsCounter)
  198. const_cast<byte *>(inBlocks)[blockSize-1]++;
  199. inBlocks += inIncrement;
  200. outBlocks += outIncrement;
  201. xorBlocks += xorIncrement;
  202. length -= blockSize;
  203. }
  204. return length;
  205. }
  206. unsigned int BlockTransformation::OptimalDataAlignment() const
  207. {
  208. return GetAlignmentOf<word32>();
  209. }
  210. unsigned int StreamTransformation::OptimalDataAlignment() const
  211. {
  212. return GetAlignmentOf<word32>();
  213. }
  214. unsigned int HashTransformation::OptimalDataAlignment() const
  215. {
  216. return GetAlignmentOf<word32>();
  217. }
  218. void StreamTransformation::ProcessLastBlock(byte *outString, const byte *inString, size_t length)
  219. {
  220. assert(MinLastBlockSize() == 0); // this function should be overriden otherwise
  221. if (length == MandatoryBlockSize())
  222. ProcessData(outString, inString, length);
  223. else if (length != 0)
  224. throw NotImplemented(AlgorithmName() + ": this object does't support a special last block");
  225. }
  226. void AuthenticatedSymmetricCipher::SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
  227. {
  228. if (headerLength > MaxHeaderLength())
  229. throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": header length " + IntToString(headerLength) + " exceeds the maximum of " + IntToString(MaxHeaderLength()));
  230. if (messageLength > MaxMessageLength())
  231. throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": message length " + IntToString(messageLength) + " exceeds the maximum of " + IntToString(MaxMessageLength()));
  232. if (footerLength > MaxFooterLength())
  233. throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": footer length " + IntToString(footerLength) + " exceeds the maximum of " + IntToString(MaxFooterLength()));
  234. UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
  235. }
  236. void AuthenticatedSymmetricCipher::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)
  237. {
  238. Resynchronize(iv, ivLength);
  239. SpecifyDataLengths(headerLength, messageLength);
  240. Update(header, headerLength);
  241. ProcessString(ciphertext, message, messageLength);
  242. TruncatedFinal(mac, macSize);
  243. }
  244. bool AuthenticatedSymmetricCipher::DecryptAndVerify(byte *message, const byte *mac, size_t macLength, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength)
  245. {
  246. Resynchronize(iv, ivLength);
  247. SpecifyDataLengths(headerLength, ciphertextLength);
  248. Update(header, headerLength);
  249. ProcessString(message, ciphertext, ciphertextLength);
  250. return TruncatedVerify(mac, macLength);
  251. }
  252. unsigned int RandomNumberGenerator::GenerateBit()
  253. {
  254. return GenerateByte() & 1;
  255. }
  256. byte RandomNumberGenerator::GenerateByte()
  257. {
  258. byte b;
  259. GenerateBlock(&b, 1);
  260. return b;
  261. }
  262. word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
  263. {
  264. const word32 range = max-min;
  265. const int maxBits = BitPrecision(range);
  266. word32 value;
  267. do
  268. {
  269. GenerateBlock((byte *)&value, sizeof(value));
  270. value = Crop(value, maxBits);
  271. } while (value > range);
  272. return value+min;
  273. }
  274. // Stack recursion below... GenerateIntoBufferedTransformation calls GenerateBlock,
  275. // and GenerateBlock calls GenerateIntoBufferedTransformation. Ad infinitum. Also
  276. // see https://github.com/weidai11/cryptopp/issues/38.
  277. //
  278. // According to Wei, RandomNumberGenerator is an interface, and it should not
  279. // be instantiable. Its now spilt milk, and we are going to assert it in Debug
  280. // builds to alert the programmer and throw in Release builds. Developers have
  281. // a reference implementation in case its needed. If a programmer
  282. // unintentionally lands here, then they should ensure use of a
  283. // RandomNumberGenerator pointer or reference so polymorphism can provide the
  284. // proper runtime dispatching.
  285. void RandomNumberGenerator::GenerateBlock(byte *output, size_t size)
  286. {
  287. CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
  288. #if 0
  289. // This breaks AutoSeededX917RNG<T> generators.
  290. throw NotImplemented("RandomNumberGenerator: GenerateBlock not implemented");
  291. #endif
  292. ArraySink s(output, size);
  293. GenerateIntoBufferedTransformation(s, DEFAULT_CHANNEL, size);
  294. }
  295. void RandomNumberGenerator::DiscardBytes(size_t n)
  296. {
  297. GenerateIntoBufferedTransformation(TheBitBucket(), DEFAULT_CHANNEL, n);
  298. }
  299. void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
  300. {
  301. FixedSizeSecBlock<byte, 256> buffer;
  302. while (length)
  303. {
  304. size_t len = UnsignedMin(buffer.size(), length);
  305. GenerateBlock(buffer, len);
  306. size_t rem = target.ChannelPut(channel, buffer, len);
  307. CRYPTOPP_UNUSED(rem); assert(rem == 0);
  308. length -= len;
  309. }
  310. }
  311. //! \class ClassNullRNG
  312. //! \brief Random Number Generator that does not produce random numbers
  313. //! \details ClassNullRNG can be used for functions that require a RandomNumberGenerator
  314. //! but don't actually use it. The class throws NotImplemented when a generation function is called.
  315. //! \sa NullRNG()
  316. class ClassNullRNG : public RandomNumberGenerator
  317. {
  318. public:
  319. //! \brief The name of the generator
  320. //! \returns the string \a NullRNGs
  321. std::string AlgorithmName() const {return "NullRNG";}
  322. #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
  323. //! \brief An implementation that throws NotImplemented
  324. byte GenerateByte () {}
  325. //! \brief An implementation that throws NotImplemented
  326. unsigned int GenerateBit () {}
  327. //! \brief An implementation that throws NotImplemented
  328. word32 GenerateWord32 (word32 min, word32 max) {}
  329. #endif
  330. //! \brief An implementation that throws NotImplemented
  331. void GenerateBlock(byte *output, size_t size)
  332. {
  333. CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
  334. throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
  335. }
  336. #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
  337. //! \brief An implementation that throws NotImplemented
  338. void GenerateIntoBufferedTransformation (BufferedTransformation &target, const std::string &channel, lword length) {}
  339. //! \brief An implementation that throws NotImplemented
  340. void IncorporateEntropy (const byte *input, size_t length) {}
  341. //! \brief An implementation that returns \p false
  342. bool CanIncorporateEntropy () const {}
  343. //! \brief An implementation that does nothing
  344. void DiscardBytes (size_t n) {}
  345. //! \brief An implementation that does nothing
  346. void Shuffle (IT begin, IT end) {}
  347. private:
  348. Clonable* Clone () const { return NULL; }
  349. #endif
  350. };
  351. RandomNumberGenerator & NullRNG()
  352. {
  353. static ClassNullRNG s_nullRNG;
  354. return s_nullRNG;
  355. }
  356. bool HashTransformation::TruncatedVerify(const byte *digestIn, size_t digestLength)
  357. {
  358. ThrowIfInvalidTruncatedSize(digestLength);
  359. SecByteBlock digest(digestLength);
  360. TruncatedFinal(digest, digestLength);
  361. return VerifyBufsEqual(digest, digestIn, digestLength);
  362. }
  363. void HashTransformation::ThrowIfInvalidTruncatedSize(size_t size) const
  364. {
  365. if (size > DigestSize())
  366. throw InvalidArgument("HashTransformation: can't truncate a " + IntToString(DigestSize()) + " byte digest to " + IntToString(size) + " bytes");
  367. }
  368. unsigned int BufferedTransformation::GetMaxWaitObjectCount() const
  369. {
  370. const BufferedTransformation *t = AttachedTransformation();
  371. return t ? t->GetMaxWaitObjectCount() : 0;
  372. }
  373. void BufferedTransformation::GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack)
  374. {
  375. BufferedTransformation *t = AttachedTransformation();
  376. if (t)
  377. t->GetWaitObjects(container, callStack); // reduce clutter by not adding to stack here
  378. }
  379. void BufferedTransformation::Initialize(const NameValuePairs &parameters, int propagation)
  380. {
  381. CRYPTOPP_UNUSED(propagation);
  382. assert(!AttachedTransformation());
  383. IsolatedInitialize(parameters);
  384. }
  385. bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking)
  386. {
  387. CRYPTOPP_UNUSED(propagation);
  388. assert(!AttachedTransformation());
  389. return IsolatedFlush(hardFlush, blocking);
  390. }
  391. bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking)
  392. {
  393. CRYPTOPP_UNUSED(propagation);
  394. assert(!AttachedTransformation());
  395. return IsolatedMessageSeriesEnd(blocking);
  396. }
  397. byte * BufferedTransformation::ChannelCreatePutSpace(const std::string &channel, size_t &size)
  398. {
  399. if (channel.empty())
  400. return CreatePutSpace(size);
  401. else
  402. throw NoChannelSupport(AlgorithmName());
  403. }
  404. size_t BufferedTransformation::ChannelPut2(const std::string &channel, const byte *begin, size_t length, int messageEnd, bool blocking)
  405. {
  406. if (channel.empty())
  407. return Put2(begin, length, messageEnd, blocking);
  408. else
  409. throw NoChannelSupport(AlgorithmName());
  410. }
  411. size_t BufferedTransformation::ChannelPutModifiable2(const std::string &channel, byte *begin, size_t length, int messageEnd, bool blocking)
  412. {
  413. if (channel.empty())
  414. return PutModifiable2(begin, length, messageEnd, blocking);
  415. else
  416. return ChannelPut2(channel, begin, length, messageEnd, blocking);
  417. }
  418. bool BufferedTransformation::ChannelFlush(const std::string &channel, bool completeFlush, int propagation, bool blocking)
  419. {
  420. if (channel.empty())
  421. return Flush(completeFlush, propagation, blocking);
  422. else
  423. throw NoChannelSupport(AlgorithmName());
  424. }
  425. bool BufferedTransformation::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
  426. {
  427. if (channel.empty())
  428. return MessageSeriesEnd(propagation, blocking);
  429. else
  430. throw NoChannelSupport(AlgorithmName());
  431. }
  432. lword BufferedTransformation::MaxRetrievable() const
  433. {
  434. if (AttachedTransformation())
  435. return AttachedTransformation()->MaxRetrievable();
  436. else
  437. return CopyTo(TheBitBucket());
  438. }
  439. bool BufferedTransformation::AnyRetrievable() const
  440. {
  441. if (AttachedTransformation())
  442. return AttachedTransformation()->AnyRetrievable();
  443. else
  444. {
  445. byte b;
  446. return Peek(b) != 0;
  447. }
  448. }
  449. size_t BufferedTransformation::Get(byte &outByte)
  450. {
  451. if (AttachedTransformation())
  452. return AttachedTransformation()->Get(outByte);
  453. else
  454. return Get(&outByte, 1);
  455. }
  456. size_t BufferedTransformation::Get(byte *outString, size_t getMax)
  457. {
  458. if (AttachedTransformation())
  459. return AttachedTransformation()->Get(outString, getMax);
  460. else
  461. {
  462. ArraySink arraySink(outString, getMax);
  463. return (size_t)TransferTo(arraySink, getMax);
  464. }
  465. }
  466. size_t BufferedTransformation::Peek(byte &outByte) const
  467. {
  468. if (AttachedTransformation())
  469. return AttachedTransformation()->Peek(outByte);
  470. else
  471. return Peek(&outByte, 1);
  472. }
  473. size_t BufferedTransformation::Peek(byte *outString, size_t peekMax) const
  474. {
  475. if (AttachedTransformation())
  476. return AttachedTransformation()->Peek(outString, peekMax);
  477. else
  478. {
  479. ArraySink arraySink(outString, peekMax);
  480. return (size_t)CopyTo(arraySink, peekMax);
  481. }
  482. }
  483. lword BufferedTransformation::Skip(lword skipMax)
  484. {
  485. if (AttachedTransformation())
  486. return AttachedTransformation()->Skip(skipMax);
  487. else
  488. return TransferTo(TheBitBucket(), skipMax);
  489. }
  490. lword BufferedTransformation::TotalBytesRetrievable() const
  491. {
  492. if (AttachedTransformation())
  493. return AttachedTransformation()->TotalBytesRetrievable();
  494. else
  495. return MaxRetrievable();
  496. }
  497. unsigned int BufferedTransformation::NumberOfMessages() const
  498. {
  499. if (AttachedTransformation())
  500. return AttachedTransformation()->NumberOfMessages();
  501. else
  502. return CopyMessagesTo(TheBitBucket());
  503. }
  504. bool BufferedTransformation::AnyMessages() const
  505. {
  506. if (AttachedTransformation())
  507. return AttachedTransformation()->AnyMessages();
  508. else
  509. return NumberOfMessages() != 0;
  510. }
  511. bool BufferedTransformation::GetNextMessage()
  512. {
  513. if (AttachedTransformation())
  514. return AttachedTransformation()->GetNextMessage();
  515. else
  516. {
  517. assert(!AnyMessages());
  518. return false;
  519. }
  520. }
  521. unsigned int BufferedTransformation::SkipMessages(unsigned int count)
  522. {
  523. if (AttachedTransformation())
  524. return AttachedTransformation()->SkipMessages(count);
  525. else
  526. return TransferMessagesTo(TheBitBucket(), count);
  527. }
  528. size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel, bool blocking)
  529. {
  530. if (AttachedTransformation())
  531. return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
  532. else
  533. {
  534. unsigned int maxMessages = messageCount;
  535. for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
  536. {
  537. size_t blockedBytes;
  538. lword transferredBytes;
  539. while (AnyRetrievable())
  540. {
  541. transferredBytes = LWORD_MAX;
  542. blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
  543. if (blockedBytes > 0)
  544. return blockedBytes;
  545. }
  546. if (target.ChannelMessageEnd(channel, GetAutoSignalPropagation(), blocking))
  547. return 1;
  548. bool result = GetNextMessage();
  549. CRYPTOPP_UNUSED(result); assert(result);
  550. }
  551. return 0;
  552. }
  553. }
  554. unsigned int BufferedTransformation::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
  555. {
  556. if (AttachedTransformation())
  557. return AttachedTransformation()->CopyMessagesTo(target, count, channel);
  558. else
  559. return 0;
  560. }
  561. void BufferedTransformation::SkipAll()
  562. {
  563. if (AttachedTransformation())
  564. AttachedTransformation()->SkipAll();
  565. else
  566. {
  567. while (SkipMessages()) {}
  568. while (Skip()) {}
  569. }
  570. }
  571. size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, const std::string &channel, bool blocking)
  572. {
  573. if (AttachedTransformation())
  574. return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
  575. else
  576. {
  577. assert(!NumberOfMessageSeries());
  578. unsigned int messageCount;
  579. do
  580. {
  581. messageCount = UINT_MAX;
  582. size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
  583. if (blockedBytes)
  584. return blockedBytes;
  585. }
  586. while (messageCount != 0);
  587. lword byteCount;
  588. do
  589. {
  590. byteCount = ULONG_MAX;
  591. size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
  592. if (blockedBytes)
  593. return blockedBytes;
  594. }
  595. while (byteCount != 0);
  596. return 0;
  597. }
  598. }
  599. void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std::string &channel) const
  600. {
  601. if (AttachedTransformation())
  602. AttachedTransformation()->CopyAllTo(target, channel);
  603. else
  604. {
  605. assert(!NumberOfMessageSeries());
  606. while (CopyMessagesTo(target, UINT_MAX, channel)) {}
  607. }
  608. }
  609. void BufferedTransformation::SetRetrievalChannel(const std::string &channel)
  610. {
  611. if (AttachedTransformation())
  612. AttachedTransformation()->SetRetrievalChannel(channel);
  613. }
  614. size_t BufferedTransformation::ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order, bool blocking)
  615. {
  616. PutWord(false, order, m_buf, value);
  617. return ChannelPut(channel, m_buf, 2, blocking);
  618. }
  619. size_t BufferedTransformation::ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order, bool blocking)
  620. {
  621. PutWord(false, order, m_buf, value);
  622. return ChannelPut(channel, m_buf, 4, blocking);
  623. }
  624. size_t BufferedTransformation::PutWord16(word16 value, ByteOrder order, bool blocking)
  625. {
  626. return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
  627. }
  628. size_t BufferedTransformation::PutWord32(word32 value, ByteOrder order, bool blocking)
  629. {
  630. return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
  631. }
  632. size_t BufferedTransformation::PeekWord16(word16 &value, ByteOrder order) const
  633. {
  634. byte buf[2] = {0, 0};
  635. size_t len = Peek(buf, 2);
  636. if (order)
  637. value = (buf[0] << 8) | buf[1];
  638. else
  639. value = (buf[1] << 8) | buf[0];
  640. return len;
  641. }
  642. size_t BufferedTransformation::PeekWord32(word32 &value, ByteOrder order) const
  643. {
  644. byte buf[4] = {0, 0, 0, 0};
  645. size_t len = Peek(buf, 4);
  646. if (order)
  647. value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
  648. else
  649. value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
  650. return len;
  651. }
  652. size_t BufferedTransformation::GetWord16(word16 &value, ByteOrder order)
  653. {
  654. return (size_t)Skip(PeekWord16(value, order));
  655. }
  656. size_t BufferedTransformation::GetWord32(word32 &value, ByteOrder order)
  657. {
  658. return (size_t)Skip(PeekWord32(value, order));
  659. }
  660. void BufferedTransformation::Attach(BufferedTransformation *newOut)
  661. {
  662. if (AttachedTransformation() && AttachedTransformation()->Attachable())
  663. AttachedTransformation()->Attach(newOut);
  664. else
  665. Detach(newOut);
  666. }
  667. void GeneratableCryptoMaterial::GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
  668. {
  669. GenerateRandom(rng, MakeParameters("KeySize", (int)keySize));
  670. }
  671. class PK_DefaultEncryptionFilter : public Unflushable<Filter>
  672. {
  673. public:
  674. PK_DefaultEncryptionFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
  675. : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
  676. {
  677. Detach(attachment);
  678. }
  679. size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
  680. {
  681. FILTER_BEGIN;
  682. m_plaintextQueue.Put(inString, length);
  683. if (messageEnd)
  684. {
  685. {
  686. size_t plaintextLength;
  687. if (!SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
  688. throw InvalidArgument("PK_DefaultEncryptionFilter: plaintext too long");
  689. size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
  690. SecByteBlock plaintext(plaintextLength);
  691. m_plaintextQueue.Get(plaintext, plaintextLength);
  692. m_ciphertext.resize(ciphertextLength);
  693. m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
  694. }
  695. FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
  696. }
  697. FILTER_END_NO_MESSAGE_END;
  698. }
  699. RandomNumberGenerator &m_rng;
  700. const PK_Encryptor &m_encryptor;
  701. const NameValuePairs &m_parameters;
  702. ByteQueue m_plaintextQueue;
  703. SecByteBlock m_ciphertext;
  704. };
  705. BufferedTransformation * PK_Encryptor::CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment, const NameValuePairs &parameters) const
  706. {
  707. return new PK_DefaultEncryptionFilter(rng, *this, attachment, parameters);
  708. }
  709. class PK_DefaultDecryptionFilter : public Unflushable<Filter>
  710. {
  711. public:
  712. PK_DefaultDecryptionFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
  713. : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
  714. {
  715. Detach(attachment);
  716. }
  717. size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
  718. {
  719. FILTER_BEGIN;
  720. m_ciphertextQueue.Put(inString, length);
  721. if (messageEnd)
  722. {
  723. {
  724. size_t ciphertextLength;
  725. if (!SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
  726. throw InvalidArgument("PK_DefaultDecryptionFilter: ciphertext too long");
  727. size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
  728. SecByteBlock ciphertext(ciphertextLength);
  729. m_ciphertextQueue.Get(ciphertext, ciphertextLength);
  730. m_plaintext.resize(maxPlaintextLength);
  731. m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
  732. if (!m_result.isValidCoding)
  733. throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
  734. }
  735. FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
  736. }
  737. FILTER_END_NO_MESSAGE_END;
  738. }
  739. RandomNumberGenerator &m_rng;
  740. const PK_Decryptor &m_decryptor;
  741. const NameValuePairs &m_parameters;
  742. ByteQueue m_ciphertextQueue;
  743. SecByteBlock m_plaintext;
  744. DecodingResult m_result;
  745. };
  746. BufferedTransformation * PK_Decryptor::CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment, const NameValuePairs &parameters) const
  747. {
  748. return new PK_DefaultDecryptionFilter(rng, *this, attachment, parameters);
  749. }
  750. size_t PK_Signer::Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
  751. {
  752. member_ptr<PK_MessageAccumulator> m(messageAccumulator);
  753. return SignAndRestart(rng, *m, signature, false);
  754. }
  755. size_t PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
  756. {
  757. member_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
  758. m->Update(message, messageLen);
  759. return SignAndRestart(rng, *m, signature, false);
  760. }
  761. size_t PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
  762. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const
  763. {
  764. member_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
  765. InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
  766. m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
  767. return SignAndRestart(rng, *m, signature, false);
  768. }
  769. bool PK_Verifier::Verify(PK_MessageAccumulator *messageAccumulator) const
  770. {
  771. member_ptr<PK_MessageAccumulator> m(messageAccumulator);
  772. return VerifyAndRestart(*m);
  773. }
  774. bool PK_Verifier::VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLength) const
  775. {
  776. member_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
  777. InputSignature(*m, signature, signatureLength);
  778. m->Update(message, messageLen);
  779. return VerifyAndRestart(*m);
  780. }
  781. DecodingResult PK_Verifier::Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
  782. {
  783. member_ptr<PK_MessageAccumulator> m(messageAccumulator);
  784. return RecoverAndRestart(recoveredMessage, *m);
  785. }
  786. DecodingResult PK_Verifier::RecoverMessage(byte *recoveredMessage,
  787. const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
  788. const byte *signature, size_t signatureLength) const
  789. {
  790. member_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
  791. InputSignature(*m, signature, signatureLength);
  792. m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
  793. return RecoverAndRestart(recoveredMessage, *m);
  794. }
  795. void SimpleKeyAgreementDomain::GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
  796. {
  797. GeneratePrivateKey(rng, privateKey);
  798. GeneratePublicKey(rng, privateKey, publicKey);
  799. }
  800. void AuthenticatedKeyAgreementDomain::GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
  801. {
  802. GenerateStaticPrivateKey(rng, privateKey);
  803. GenerateStaticPublicKey(rng, privateKey, publicKey);
  804. }
  805. void AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
  806. {
  807. GenerateEphemeralPrivateKey(rng, privateKey);
  808. GenerateEphemeralPublicKey(rng, privateKey, publicKey);
  809. }
  810. NAMESPACE_END
  811. #endif