Crypto++  8.2
Free C++ class library of cryptographic schemes
cryptlib.cpp
1 // cryptlib.cpp - originally written and placed in the public domain by Wei Dai
2 
3 #include "pch.h"
4 #include "config.h"
5 
6 #if CRYPTOPP_MSC_VERSION
7 # pragma warning(disable: 4127 4189 4459)
8 #endif
9 
10 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
11 # pragma GCC diagnostic ignored "-Wunused-value"
12 # pragma GCC diagnostic ignored "-Wunused-variable"
13 # pragma GCC diagnostic ignored "-Wunused-parameter"
14 #endif
15 
16 #ifndef CRYPTOPP_IMPORTS
17 
18 #include "cryptlib.h"
19 #include "misc.h"
20 #include "filters.h"
21 #include "algparam.h"
22 #include "fips140.h"
23 #include "argnames.h"
24 #include "fltrimpl.h"
25 #include "osrng.h"
26 #include "secblock.h"
27 #include "smartptr.h"
28 #include "stdcpp.h"
29 
30 NAMESPACE_BEGIN(CryptoPP)
31 
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 
41 {
42  static BitBucket bitBucket;
43  return bitBucket;
44 }
45 
46 Algorithm::Algorithm(bool checkSelfTestStatus)
47 {
48  if (checkSelfTestStatus && FIPS_140_2_ComplianceEnabled())
49  {
50  if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_NOT_DONE && !PowerUpSelfTestInProgressOnThisThread())
51  throw SelfTestFailure("Cryptographic algorithms are disabled before the power-up self tests are performed.");
52 
54  throw SelfTestFailure("Cryptographic algorithms are disabled after a power-up self test failed.");
55  }
56 }
57 
58 void SimpleKeyingInterface::SetKey(const byte *key, size_t length, const NameValuePairs &params)
59 {
60  this->ThrowIfInvalidKeyLength(length);
61  this->UncheckedSetKey(key, static_cast<unsigned int>(length), params);
62 }
63 
64 void SimpleKeyingInterface::SetKeyWithRounds(const byte *key, size_t length, int rounds)
65 {
66  SetKey(key, length, MakeParameters(Name::Rounds(), rounds));
67 }
68 
69 void SimpleKeyingInterface::SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
70 {
71  SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, ivLength)));
72 }
73 
74 void SimpleKeyingInterface::ThrowIfInvalidKeyLength(size_t length)
75 {
76  if (!IsValidKeyLength(length))
77  throw InvalidKeyLength(GetAlgorithm().AlgorithmName(), length);
78 }
79 
80 void SimpleKeyingInterface::ThrowIfResynchronizable()
81 {
82  if (IsResynchronizable())
83  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object requires an IV");
84 }
85 
86 void SimpleKeyingInterface::ThrowIfInvalidIV(const byte *iv)
87 {
88  if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
89  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object cannot use a null IV");
90 }
91 
92 size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(int length)
93 {
94  size_t size = 0;
95  if (length < 0)
96  size = static_cast<size_t>(IVSize());
97  else if ((size_t)length < MinIVLength())
98  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(length) + " is less than the minimum of " + IntToString(MinIVLength()));
99  else if ((size_t)length > MaxIVLength())
100  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(length) + " exceeds the maximum of " + IntToString(MaxIVLength()));
101  else
102  size = static_cast<size_t>(length);
103 
104  return size;
105 }
106 
107 const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size)
108 {
109  ConstByteArrayParameter ivWithLength;
110  const byte *iv = NULLPTR;
111  bool found = false;
112 
113  try {found = params.GetValue(Name::IV(), ivWithLength);}
114  catch (const NameValuePairs::ValueTypeMismatch &) {}
115 
116  if (found)
117  {
118  iv = ivWithLength.begin();
119  ThrowIfInvalidIV(iv);
120  size = ThrowIfInvalidIVLength(static_cast<int>(ivWithLength.size()));
121  }
122  else if (params.GetValue(Name::IV(), iv))
123  {
124  ThrowIfInvalidIV(iv);
125  size = static_cast<size_t>(IVSize());
126  }
127  else
128  {
129  ThrowIfResynchronizable();
130  size = 0;
131  }
132 
133  return iv;
134 }
135 
137 {
138  rng.GenerateBlock(iv, IVSize());
139 }
140 
141 size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const
142 {
143  CRYPTOPP_ASSERT(inBlocks);
144  CRYPTOPP_ASSERT(outBlocks);
145  CRYPTOPP_ASSERT(length);
146 
147  const unsigned int blockSize = BlockSize();
148  size_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize;
149  size_t xorIncrement = xorBlocks ? blockSize : 0;
150  size_t outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : blockSize;
151 
152  if (flags & BT_ReverseDirection)
153  {
154  inBlocks = PtrAdd(inBlocks, length - blockSize);
155  xorBlocks = PtrAdd(xorBlocks, length - blockSize);
156  outBlocks = PtrAdd(outBlocks, length - blockSize);
157  inIncrement = 0-inIncrement;
158  xorIncrement = 0-xorIncrement;
159  outIncrement = 0-outIncrement;
160  }
161 
162  // Coverity finding.
163  const bool xorFlag = xorBlocks && (flags & BT_XorInput);
164  while (length >= blockSize)
165  {
166  if (xorFlag)
167  {
168  // xorBlocks non-NULL and with BT_XorInput.
169  xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
170  ProcessBlock(outBlocks);
171  }
172  else
173  {
174  // xorBlocks may be non-NULL and without BT_XorInput.
175  ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
176  }
177 
178  if (flags & BT_InBlockIsCounter)
179  const_cast<byte *>(inBlocks)[blockSize-1]++;
180 
181  inBlocks = PtrAdd(inBlocks, inIncrement);
182  outBlocks = PtrAdd(outBlocks, outIncrement);
183  xorBlocks = PtrAdd(xorBlocks, xorIncrement);
184  length -= blockSize;
185  }
186 
187  return length;
188 }
189 
191 {
192  return GetAlignmentOf<word32>();
193 }
194 
196 {
197  return GetAlignmentOf<word32>();
198 }
199 
201 {
202  return GetAlignmentOf<word32>();
203 }
204 
205 #if 0
206 void StreamTransformation::ProcessLastBlock(byte *outString, const byte *inString, size_t length)
207 {
208  CRYPTOPP_ASSERT(MinLastBlockSize() == 0); // this function should be overridden otherwise
209 
210  if (length == MandatoryBlockSize())
211  ProcessData(outString, inString, length);
212  else if (length != 0)
213  throw NotImplemented(AlgorithmName() + ": this object doesn't support a special last block");
214 }
215 #endif
216 
217 size_t StreamTransformation::ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength)
218 {
219  // this function should be overridden otherwise
221 
222  if (inLength == MandatoryBlockSize())
223  {
224  outLength = inLength; // squash unused warning
225  ProcessData(outString, inString, inLength);
226  }
227  else if (inLength != 0)
228  throw NotImplemented(AlgorithmName() + ": this object doesn't support a special last block");
229 
230  return outLength;
231 }
232 
233 void AuthenticatedSymmetricCipher::SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
234 {
235  if (headerLength > MaxHeaderLength())
236  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": header length " + IntToString(headerLength) + " exceeds the maximum of " + IntToString(MaxHeaderLength()));
237 
238  if (messageLength > MaxMessageLength())
239  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": message length " + IntToString(messageLength) + " exceeds the maximum of " + IntToString(MaxMessageLength()));
240 
241  if (footerLength > MaxFooterLength())
242  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": footer length " + IntToString(footerLength) + " exceeds the maximum of " + IntToString(MaxFooterLength()));
243 
244  UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
245 }
246 
247 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)
248 {
249  Resynchronize(iv, ivLength);
250  SpecifyDataLengths(headerLength, messageLength);
251  Update(header, headerLength);
252  ProcessString(ciphertext, message, messageLength);
253  TruncatedFinal(mac, macSize);
254 }
255 
256 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)
257 {
258  Resynchronize(iv, ivLength);
259  SpecifyDataLengths(headerLength, ciphertextLength);
260  Update(header, headerLength);
261  ProcessString(message, ciphertext, ciphertextLength);
262  return TruncatedVerify(mac, macLength);
263 }
264 
266 {
267  // Squash C4505 on Visual Studio 2008 and friends
268  return "Unknown";
269 }
270 
272 {
273  return GenerateByte() & 1;
274 }
275 
277 {
278  byte b;
279  GenerateBlock(&b, 1);
280  return b;
281 }
282 
283 word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
284 {
285  const word32 range = max-min;
286  const unsigned int maxBits = BitPrecision(range);
287 
288  word32 value;
289 
290  do
291  {
292  GenerateBlock((byte *)&value, sizeof(value));
293  value = Crop(value, maxBits);
294  } while (value > range);
295 
296  return value+min;
297 }
298 
299 // Stack recursion below... GenerateIntoBufferedTransformation calls GenerateBlock,
300 // and GenerateBlock calls GenerateIntoBufferedTransformation. Ad infinitum. Also
301 // see http://github.com/weidai11/cryptopp/issues/38.
302 //
303 // According to Wei, RandomNumberGenerator is an interface, and it should not
304 // be instantiable. Its now spilt milk, and we are going to CRYPTOPP_ASSERT it in Debug
305 // builds to alert the programmer and throw in Release builds. Developers have
306 // a reference implementation in case its needed. If a programmer
307 // unintentionally lands here, then they should ensure use of a
308 // RandomNumberGenerator pointer or reference so polymorphism can provide the
309 // proper runtime dispatching.
310 
311 void RandomNumberGenerator::GenerateBlock(byte *output, size_t size)
312 {
313  CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
314 
315  ArraySink s(output, size);
317 }
318 
320 {
322 }
323 
324 void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
325 {
327  while (length)
328  {
329  size_t len = UnsignedMin(buffer.size(), length);
330  GenerateBlock(buffer, len);
331  (void)target.ChannelPut(channel, buffer, len);
332  length -= len;
333  }
334 }
335 
337 {
338  return 0;
339 }
340 
342 {
343  return static_cast<size_t>(-1);
344 }
345 
346 void KeyDerivationFunction::ThrowIfInvalidDerivedLength(size_t length) const
347 {
348  if (!IsValidDerivedLength(length))
349  throw InvalidDerivedLength(GetAlgorithm().AlgorithmName(), length);
350 }
351 
353  CRYPTOPP_UNUSED(params);
354 }
355 
356 /// \brief Random Number Generator that does not produce random numbers
357 /// \details ClassNullRNG can be used for functions that require a RandomNumberGenerator
358 /// but don't actually use it. The class throws NotImplemented when a generation function is called.
359 /// \sa NullRNG()
361 {
362 public:
363  /// \brief The name of the generator
364  /// \returns the string \a NullRNGs
365  std::string AlgorithmName() const {return "NullRNG";}
366 
367 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
368  /// \brief An implementation that throws NotImplemented
369  byte GenerateByte () {}
370  /// \brief An implementation that throws NotImplemented
371  unsigned int GenerateBit () {}
372  /// \brief An implementation that throws NotImplemented
373  word32 GenerateWord32 (word32 min, word32 max) {}
374 #endif
375 
376  /// \brief An implementation that throws NotImplemented
377  void GenerateBlock(byte *output, size_t size)
378  {
379  CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
380  throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
381  }
382 
383 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
384  /// \brief An implementation that throws NotImplemented
385  void GenerateIntoBufferedTransformation (BufferedTransformation &target, const std::string &channel, lword length) {}
386  /// \brief An implementation that throws NotImplemented
387  void IncorporateEntropy (const byte *input, size_t length) {}
388  /// \brief An implementation that returns \p false
389  bool CanIncorporateEntropy () const {}
390  /// \brief An implementation that does nothing
391  void DiscardBytes (size_t n) {}
392  /// \brief An implementation that does nothing
393  void Shuffle (IT begin, IT end) {}
394 
395 private:
396  Clonable* Clone () const { return NULLPTR; }
397 #endif
398 };
399 
401 {
402  static ClassNullRNG s_nullRNG;
403  return s_nullRNG;
404 }
405 
406 bool HashTransformation::TruncatedVerify(const byte *digest, size_t digestLength)
407 {
408  ThrowIfInvalidTruncatedSize(digestLength);
409  SecByteBlock calculated(digestLength);
410  TruncatedFinal(calculated, digestLength);
411  return VerifyBufsEqual(calculated, digest, digestLength);
412 }
413 
414 void HashTransformation::ThrowIfInvalidTruncatedSize(size_t size) const
415 {
416  if (size > DigestSize())
417  throw InvalidArgument("HashTransformation: can't truncate a " + IntToString(DigestSize()) + " byte digest to " + IntToString(size) + " bytes");
418 }
419 
421 {
423  return t ? t->GetMaxWaitObjectCount() : 0;
424 }
425 
426 void BufferedTransformation::GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack)
427 {
429  if (t)
430  t->GetWaitObjects(container, callStack); // reduce clutter by not adding to stack here
431 }
432 
433 void BufferedTransformation::Initialize(const NameValuePairs &parameters, int propagation)
434 {
435  CRYPTOPP_UNUSED(propagation);
437  IsolatedInitialize(parameters);
438 }
439 
440 bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking)
441 {
442  CRYPTOPP_UNUSED(propagation);
444  return IsolatedFlush(hardFlush, blocking);
445 }
446 
447 bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking)
448 {
449  CRYPTOPP_UNUSED(propagation);
451  return IsolatedMessageSeriesEnd(blocking);
452 }
453 
454 byte * BufferedTransformation::ChannelCreatePutSpace(const std::string &channel, size_t &size)
455 {
456  byte* space = NULLPTR;
457  if (channel.empty())
458  space = CreatePutSpace(size);
459  else
461  return space;
462 }
463 
464 size_t BufferedTransformation::ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking)
465 {
466  size_t size = 0;
467  if (channel.empty())
468  size = Put2(inString, length, messageEnd, blocking);
469  else
471  return size;
472 }
473 
474 size_t BufferedTransformation::ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking)
475 {
476  size_t size = 0;
477  if (channel.empty())
478  size = PutModifiable2(inString, length, messageEnd, blocking);
479  else
480  size = ChannelPut2(channel, inString, length, messageEnd, blocking);
481  return size;
482 }
483 
484 bool BufferedTransformation::ChannelFlush(const std::string &channel, bool hardFlush, int propagation, bool blocking)
485 {
486  bool result = 0;
487  if (channel.empty())
488  result = Flush(hardFlush, propagation, blocking);
489  else
491  return result;
492 }
493 
494 bool BufferedTransformation::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
495 {
496  bool result = false;
497  if (channel.empty())
498  result = MessageSeriesEnd(propagation, blocking);
499  else
501  return result;
502 }
503 
505 {
506  lword size = 0;
509  else
510  size = CopyTo(TheBitBucket());
511  return size;
512 }
513 
515 {
516  bool result = false;
519  else
520  {
521  byte b;
522  result = Peek(b) != 0;
523  }
524  return result;
525 }
526 
527 size_t BufferedTransformation::Get(byte &outByte)
528 {
529  size_t size = 0;
531  size = AttachedTransformation()->Get(outByte);
532  else
533  size = Get(&outByte, 1);
534  return size;
535 }
536 
537 size_t BufferedTransformation::Get(byte *outString, size_t getMax)
538 {
539  size_t size = 0;
541  size = AttachedTransformation()->Get(outString, getMax);
542  else
543  {
544  ArraySink arraySink(outString, getMax);
545  size = (size_t)TransferTo(arraySink, getMax);
546  }
547  return size;
548 }
549 
550 size_t BufferedTransformation::Peek(byte &outByte) const
551 {
552  size_t size = 0;
554  size = AttachedTransformation()->Peek(outByte);
555  else
556  size = Peek(&outByte, 1);
557  return size;
558 }
559 
560 size_t BufferedTransformation::Peek(byte *outString, size_t peekMax) const
561 {
562  size_t size = 0;
564  size = AttachedTransformation()->Peek(outString, peekMax);
565  else
566  {
567  ArraySink arraySink(outString, peekMax);
568  size = (size_t)CopyTo(arraySink, peekMax);
569  }
570  return size;
571 }
572 
573 lword BufferedTransformation::Skip(lword skipMax)
574 {
575  lword size = 0;
577  size = AttachedTransformation()->Skip(skipMax);
578  else
579  size = TransferTo(TheBitBucket(), skipMax);
580  return size;
581 }
582 
584 {
585  lword size = 0;
588  else
589  size = MaxRetrievable();
590  return size;
591 }
592 
594 {
595  unsigned int size = 0;
598  else
599  size = CopyMessagesTo(TheBitBucket());
600  return size;
601 }
602 
604 {
605  bool result = false;
607  result = AttachedTransformation()->AnyMessages();
608  else
609  result = NumberOfMessages() != 0;
610  return result;
611 }
612 
614 {
615  bool result = false;
618  else
619  {
621  }
622  return result;
623 }
624 
625 unsigned int BufferedTransformation::SkipMessages(unsigned int count)
626 {
627  unsigned int size = 0;
629  size = AttachedTransformation()->SkipMessages(count);
630  else
631  size = TransferMessagesTo(TheBitBucket(), count);
632  return size;
633 }
634 
635 size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel, bool blocking)
636 {
638  return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
639  else
640  {
641  unsigned int maxMessages = messageCount;
642  for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
643  {
644  size_t blockedBytes;
645  lword transferredBytes;
646 
647  while (AnyRetrievable())
648  {
649  transferredBytes = LWORD_MAX;
650  blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
651  if (blockedBytes > 0)
652  return blockedBytes;
653  }
654 
655  if (target.ChannelMessageEnd(channel, GetAutoSignalPropagation(), blocking))
656  return 1;
657 
658  bool result = GetNextMessage();
659  CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result);
660  }
661  return 0;
662  }
663 }
664 
665 unsigned int BufferedTransformation::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
666 {
667  unsigned int size = 0;
669  size = AttachedTransformation()->CopyMessagesTo(target, count, channel);
670  return size;
671 }
672 
674 {
677  else
678  {
679  while (SkipMessages()) {}
680  while (Skip()) {}
681  }
682 }
683 
684 size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, const std::string &channel, bool blocking)
685 {
687  return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
688  else
689  {
691 
692  unsigned int messageCount;
693  do
694  {
695  messageCount = UINT_MAX;
696  size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
697  if (blockedBytes)
698  return blockedBytes;
699  }
700  while (messageCount != 0);
701 
702  lword byteCount;
703  do
704  {
705  byteCount = ULONG_MAX;
706  size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
707  if (blockedBytes)
708  return blockedBytes;
709  }
710  while (byteCount != 0);
711 
712  return 0;
713  }
714 }
715 
716 void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std::string &channel) const
717 {
719  AttachedTransformation()->CopyAllTo(target, channel);
720  else
721  {
723  while (CopyMessagesTo(target, UINT_MAX, channel)) {}
724  }
725 }
726 
727 void BufferedTransformation::SetRetrievalChannel(const std::string &channel)
728 {
731 }
732 
733 size_t BufferedTransformation::ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order, bool blocking)
734 {
735  PutWord(false, order, m_buf, value);
736  return ChannelPut(channel, m_buf, 2, blocking);
737 }
738 
739 size_t BufferedTransformation::ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order, bool blocking)
740 {
741  PutWord(false, order, m_buf, value);
742  return ChannelPut(channel, m_buf, 4, blocking);
743 }
744 
745 size_t BufferedTransformation::PutWord16(word16 value, ByteOrder order, bool blocking)
746 {
747  return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
748 }
749 
750 size_t BufferedTransformation::PutWord32(word32 value, ByteOrder order, bool blocking)
751 {
752  return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
753 }
754 
755 // Issue 340
756 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
757 # pragma GCC diagnostic push
758 # pragma GCC diagnostic ignored "-Wconversion"
759 # pragma GCC diagnostic ignored "-Wsign-conversion"
760 #endif
761 
762 size_t BufferedTransformation::PeekWord16(word16 &value, ByteOrder order) const
763 {
764  byte buf[2] = {0, 0};
765  size_t len = Peek(buf, 2);
766 
767  if (order)
768  value = (buf[0] << 8) | buf[1];
769  else
770  value = (buf[1] << 8) | buf[0];
771 
772  return len;
773 }
774 
775 size_t BufferedTransformation::PeekWord32(word32 &value, ByteOrder order) const
776 {
777  byte buf[4] = {0, 0, 0, 0};
778  size_t len = Peek(buf, 4);
779 
780  if (order)
781  value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
782  else
783  value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
784 
785  return len;
786 }
787 
788 // Issue 340
789 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
790 # pragma GCC diagnostic pop
791 #endif
792 
793 size_t BufferedTransformation::GetWord16(word16 &value, ByteOrder order)
794 {
795  return (size_t)Skip(PeekWord16(value, order));
796 }
797 
798 size_t BufferedTransformation::GetWord32(word32 &value, ByteOrder order)
799 {
800  return (size_t)Skip(PeekWord32(value, order));
801 }
802 
804 {
806  AttachedTransformation()->Attach(newAttachment);
807  else
808  Detach(newAttachment);
809 }
810 
812 {
813  GenerateRandom(rng, MakeParameters("KeySize", (int)keySize));
814 }
815 
817 {
818 public:
819  PK_DefaultEncryptionFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
820  : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
821  {
822  Detach(attachment);
823  }
824 
825  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
826  {
827  FILTER_BEGIN;
828  m_plaintextQueue.Put(inString, length);
829 
830  if (messageEnd)
831  {
832  {
833  size_t plaintextLength;
834  if (!SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
835  throw InvalidArgument("PK_DefaultEncryptionFilter: plaintext too long");
836  size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
837 
838  SecByteBlock plaintext(plaintextLength);
839  m_plaintextQueue.Get(plaintext, plaintextLength);
840  m_ciphertext.resize(ciphertextLength);
841  m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
842  }
843 
844  FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
845  }
846  FILTER_END_NO_MESSAGE_END;
847  }
848 
849  RandomNumberGenerator &m_rng;
850  const PK_Encryptor &m_encryptor;
851  const NameValuePairs &m_parameters;
852  ByteQueue m_plaintextQueue;
853  SecByteBlock m_ciphertext;
854 };
855 
857 {
858  return new PK_DefaultEncryptionFilter(rng, *this, attachment, parameters);
859 }
860 
862 {
863 public:
864  PK_DefaultDecryptionFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
865  : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
866  {
867  Detach(attachment);
868  }
869 
870  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
871  {
872  FILTER_BEGIN;
873  m_ciphertextQueue.Put(inString, length);
874 
875  if (messageEnd)
876  {
877  {
878  size_t ciphertextLength;
879  if (!SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
880  throw InvalidArgument("PK_DefaultDecryptionFilter: ciphertext too long");
881  size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
882 
883  SecByteBlock ciphertext(ciphertextLength);
884  m_ciphertextQueue.Get(ciphertext, ciphertextLength);
885  m_plaintext.resize(maxPlaintextLength);
886  m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
887  if (!m_result.isValidCoding)
888  throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
889  }
890 
891  FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
892  }
893  FILTER_END_NO_MESSAGE_END;
894  }
895 
896  RandomNumberGenerator &m_rng;
897  const PK_Decryptor &m_decryptor;
898  const NameValuePairs &m_parameters;
899  ByteQueue m_ciphertextQueue;
900  SecByteBlock m_plaintext;
901  DecodingResult m_result;
902 };
903 
905 {
906  return new PK_DefaultDecryptionFilter(rng, *this, attachment, parameters);
907 }
908 
909 size_t PK_Signer::Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
910 {
911  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
912  return SignAndRestart(rng, *m, signature, false);
913 }
914 
915 size_t PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
916 {
918  m->Update(message, messageLen);
919  return SignAndRestart(rng, *m, signature, false);
920 }
921 
922 size_t PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
923  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const
924 {
926  InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
927  m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
928  return SignAndRestart(rng, *m, signature, false);
929 }
930 
931 bool PK_Verifier::Verify(PK_MessageAccumulator *messageAccumulator) const
932 {
933  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
934  return VerifyAndRestart(*m);
935 }
936 
937 bool PK_Verifier::VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLen) const
938 {
940  InputSignature(*m, signature, signatureLen);
941  m->Update(message, messageLen);
942  return VerifyAndRestart(*m);
943 }
944 
945 DecodingResult PK_Verifier::Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
946 {
947  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
948  return RecoverAndRestart(recoveredMessage, *m);
949 }
950 
952  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
953  const byte *signature, size_t signatureLength) const
954 {
956  InputSignature(*m, signature, signatureLength);
957  m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
958  return RecoverAndRestart(recoveredMessage, *m);
959 }
960 
961 void SimpleKeyAgreementDomain::GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
962 {
963  GeneratePrivateKey(rng, privateKey);
964  GeneratePublicKey(rng, privateKey, publicKey);
965 }
966 
967 void AuthenticatedKeyAgreementDomain::GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
968 {
969  GenerateStaticPrivateKey(rng, privateKey);
970  GenerateStaticPublicKey(rng, privateKey, publicKey);
971 }
972 
973 void AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
974 {
975  GenerateEphemeralPrivateKey(rng, privateKey);
976  GenerateEphemeralPublicKey(rng, privateKey, publicKey);
977 }
978 
979 // Allow a distro or packager to override the build-time version
980 // http://github.com/weidai11/cryptopp/issues/371
981 #ifndef CRYPTOPP_BUILD_VERSION
982 # define CRYPTOPP_BUILD_VERSION CRYPTOPP_VERSION
983 #endif
984 int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT)
985 {
986  return CRYPTOPP_BUILD_VERSION;
987 }
988 
990 {
991 public:
992  NullNameValuePairs() {} // Clang complains a default ctor must be avilable
993  bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
994  {CRYPTOPP_UNUSED(name); CRYPTOPP_UNUSED(valueType); CRYPTOPP_UNUSED(pValue); return false;}
995 };
996 
997 #if HAVE_GCC_INIT_PRIORITY
998  const std::string DEFAULT_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 25))) = "";
999  const std::string AAD_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 26))) = "AAD";
1000  const NullNameValuePairs s_nullNameValuePairs __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 27)));
1001  const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
1002 #elif HAVE_MSC_INIT_PRIORITY
1003  #pragma warning(disable: 4073)
1004  #pragma init_seg(lib)
1005  const std::string DEFAULT_CHANNEL = "";
1006  const std::string AAD_CHANNEL = "AAD";
1007  const NullNameValuePairs s_nullNameValuePairs;
1008  const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
1009  #pragma warning(default: 4073)
1010 #elif HAVE_XLC_INIT_PRIORITY
1011  #pragma priority(260)
1012  const std::string DEFAULT_CHANNEL = "";
1013  const std::string AAD_CHANNEL = "AAD";
1014  const NullNameValuePairs s_nullNameValuePairs;
1015  const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
1016 #else
1017  const std::string DEFAULT_CHANNEL = "";
1018  const std::string AAD_CHANNEL = "AAD";
1019  const simple_ptr<NullNameValuePairs> s_pNullNameValuePairs(new NullNameValuePairs);
1020  const NameValuePairs &g_nullNameValuePairs = *s_pNullNameValuePairs.m_p;
1021 #endif
1022 
1023 NAMESPACE_END // CryptoPP
1024 
1025 #endif // CRYPTOPP_IMPORTS
Used to pass byte array input as part of a NameValuePairs object.
Definition: algparam.h:20
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Definition: cryptlib.cpp:993
Standard names for retrieving values by name when working with NameValuePairs.
An invalid argument was detected.
Definition: cryptlib.h:202
virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes that may be modified by callee on a channel.
Definition: cryptlib.cpp:474
virtual void SetParameters(const NameValuePairs &params)
Set or change parameters.
Definition: cryptlib.cpp:352
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
Definition: cryptlib.cpp:961
size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 32-bit word for processing on a channel.
Definition: cryptlib.cpp:739
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:1495
size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)
Transfer all bytes from this object to another BufferedTransformation.
Definition: cryptlib.cpp:684
Classes for working with NameValuePairs.
word32 GenerateWord32(word32 min, word32 max)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:373
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition: cryptlib.h:743
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
Definition: misc.h:622
virtual void ProcessData(byte *outString, const byte *inString, size_t length)=0
Encrypt or decrypt an array of bytes.
size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)
Transfer messages from this object to another BufferedTransformation.
Definition: cryptlib.cpp:635
Utility functions for the Crypto++ library.
virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params=g_nullNameValuePairs)
Sets or reset the key of this object.
Definition: cryptlib.cpp:58
const char * Rounds()
int
Definition: argnames.h:24
virtual size_t Peek(byte &outByte) const
Peek a 8-bit byte.
Definition: cryptlib.cpp:550
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:143
virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0
Encrypt or decrypt a block.
virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)=0
Input multiple bytes for processing.
virtual void GenerateBlock(byte *output, size_t size)
Generate random array of bytes.
Definition: cryptlib.cpp:311
size_t size() const
Length of the memory block.
Definition: algparam.h:84
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition: cryptlib.h:2106
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const
Check whether messageAccumulator contains a valid signature and message.
Definition: cryptlib.cpp:931
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
Sign a message.
Definition: cryptlib.cpp:915
unsigned int GetMaxWaitObjectCount() const
Retrieves the maximum number of waitable objects.
Definition: cryptlib.cpp:420
Exception thrown when an invalid key length is encountered.
Definition: simple.h:52
virtual void TruncatedFinal(byte *digest, size_t digestSize)=0
Computes the hash of the current message.
virtual void IsolatedInitialize(const NameValuePairs &parameters)
Initialize or reinitialize this object, without signal propagation.
Definition: cryptlib.h:1755
virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength)
Encrypt or decrypt the last block of data.
Definition: cryptlib.cpp:217
void resize(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:1031
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
Definition: misc.h:2428
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)
Decrypts and verifies a MAC in one call.
Definition: cryptlib.cpp:256
virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a static private/public key pair.
Definition: cryptlib.cpp:967
Interface for public-key encryptors.
Definition: cryptlib.h:2582
byte GenerateByte()
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:369
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL)
Generate a random 32 bit word in the range min to max, inclusive.
Definition: cryptlib.cpp:283
Abstract base classes that provide a uniform interface to this library.
virtual void Encrypt(RandomNumberGenerator &rng, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs &parameters=g_nullNameValuePairs) const =0
Encrypt a byte string.
virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0
Provides the maximum length of plaintext for a given ciphertext length.
Thrown when an unexpected type is encountered.
Definition: cryptlib.h:300
void GenerateBlock(byte *output, size_t size)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:377
virtual void DiscardBytes(size_t n)
Generate and discard n bytes.
Definition: cryptlib.cpp:319
The self tests were executed via DoPowerUpSelfTest() or DoDllPowerUpSelfTest(), but the result was fa...
Definition: fips140.h:43
Classes for automatic resource management.
void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:385
virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)=0
Transfer bytes from this object to another BufferedTransformation.
Library configuration file.
should not modify block pointers
Definition: cryptlib.h:891
Interface for random number generators.
Definition: cryptlib.h:1383
virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0
Input a recoverable message to an accumulator.
Common C++ header files.
void ProcessString(byte *inoutString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1032
virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true)
Marks the end of a series of messages, with signal propagation.
Definition: cryptlib.cpp:447
size_t messageLength
Recovered message length if isValidCoding is true, undefined otherwise.
Definition: cryptlib.h:278
void SetKeyWithRounds(const byte *key, size_t length, int rounds)
Sets or reset the key of this object.
Definition: cryptlib.cpp:64
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1818
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate private/public key pair.
Definition: cryptlib.cpp:973
virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0
Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulat...
virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output on a channel.
Definition: cryptlib.cpp:484
virtual bool TruncatedVerify(const byte *digest, size_t digestLength)
Verifies the hash of the current message.
Definition: cryptlib.cpp:406
SecBlock<byte> typedef.
Definition: secblock.h:1058
virtual unsigned int SkipMessages(unsigned int count=UINT_MAX)
Skip a number of meessages.
Definition: cryptlib.cpp:625
virtual void SetRetrievalChannel(const std::string &channel)
Sets the default retrieval channel.
Definition: cryptlib.cpp:727
Interface for buffered transformations.
Definition: cryptlib.h:1598
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
Definition: cryptlib.cpp:190
void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const
Copy messages from this object to another BufferedTransformation.
Definition: cryptlib.cpp:716
Interface for cloning objects.
Definition: cryptlib.h:556
virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength, const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const
Sign a recoverable message.
Definition: cryptlib.cpp:922
std::string AlgorithmName() const
The name of the generator.
Definition: cryptlib.cpp:365
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Definition: cryptlib.cpp:870
CRYPTOPP_DLL RandomNumberGenerator &CRYPTOPP_API NullRNG()
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:400
virtual lword MaxHeaderLength() const =0
Provides the maximum length of AAD that can be input.
Classes and functions for secure memory allocations.
virtual unsigned int BlockSize() const =0
Provides the block size of the cipher.
Copy input to a memory buffer.
Definition: filters.h:1136
Exception thrown when a filter does not support named channels.
Definition: cryptlib.h:2094
Returns a decoding results.
Definition: cryptlib.h:255
Algorithm(bool checkSelfTestStatus=true)
Interface for all crypto algorithms.
Definition: cryptlib.cpp:46
virtual IV_Requirement IVRequirement() const =0
Minimal requirement for secure IVs.
virtual std::string AlgorithmName() const =0
Provides the name of this algorithm.
lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
move transferMax bytes of the buffered output to target as input
Definition: cryptlib.h:1901
size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 32-bit word.
Definition: cryptlib.cpp:775
virtual void Attach(BufferedTransformation *newAttachment)
Add newAttachment to the end of attachment chain.
Definition: cryptlib.cpp:803
Interface for public-key decryptors.
Definition: cryptlib.h:2617
void Shuffle(IT begin, IT end)
An implementation that does nothing.
Definition: cryptlib.cpp:393
virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate static private key in this domain.
A method was called which was not implemented.
Definition: cryptlib.h:223
CRYPTOPP_DLL bool CRYPTOPP_API VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
Definition: misc.cpp:100
virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0
Recover a message from its signature.
const byte * begin() const
Pointer to the first byte in the memory block.
Definition: algparam.h:80
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1620
void Detach(BufferedTransformation *newAttachment=NULL)
Replace an attached transformation.
Definition: filters.cpp:50
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.h:482
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:504
virtual unsigned int NumberOfMessages() const
Provides the number of meesages processed by this object.
Definition: cryptlib.cpp:593
Manages resources for a single object.
Definition: smartptr.h:18
virtual lword TotalBytesRetrievable() const
Provides the number of bytes ready for retrieval.
Definition: cryptlib.cpp:583
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition: cryptlib.h:748
Exception thrown when a crypto algorithm is used after a self test fails.
Definition: fips140.h:22
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:644
virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Marks the end of a series of messages on a channel.
Definition: cryptlib.cpp:494
virtual DecodingResult RecoverMessage(byte *recoveredMessage, const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, const byte *signature, size_t signatureLength) const
Recover a message from its signature.
Definition: cryptlib.cpp:951
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition: cryptlib.h:755
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:937
#define CRYPTOPP_COMPILE_ASSERT(expr)
Compile time assertion.
Definition: misc.h:116
virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output, with signal propagation.
Definition: cryptlib.cpp:440
virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.cpp:454
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
Definition: misc.h:838
virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const
Encrypt and xor multiple blocks using additional flags.
Definition: cryptlib.cpp:141
Precompiled header file.
void ProcessBlock(const byte *inBlock, byte *outBlock) const
Encrypt or decrypt a block.
Definition: cryptlib.h:851
virtual unsigned int NumberOfMessageSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:2023
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2243
virtual bool VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLen) const
Check whether input signature is a valid signature for input message.
Definition: cryptlib.cpp:937
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
Definition: misc.h:606
virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing on a channel.
Definition: cryptlib.cpp:464
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:733
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:500
unsigned int GenerateBit()
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:371
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new decryption filter.
Definition: cryptlib.cpp:904
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
Definition: cryptlib.cpp:195
virtual lword Skip(lword skipMax=LWORD_MAX)
Discard skipMax bytes from the output buffer.
Definition: cryptlib.cpp:573
virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a static public key from a private key in this domain.
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.cpp:265
virtual void Detach(BufferedTransformation *newAttachment=NULL)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:2258
virtual size_t MinDerivedLength() const
Determine minimum number of bytes.
Definition: cryptlib.cpp:336
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:591
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:69
virtual byte GenerateByte()
Generate new random byte and return it.
Definition: cryptlib.cpp:276
virtual bool AnyMessages() const
Determines if any messages are available for retrieval.
Definition: cryptlib.cpp:603
CRYPTOPP_DLL bool CRYPTOPP_API FIPS_140_2_ComplianceEnabled()
Determines whether the library provides FIPS validated cryptography.
Definition: fips140.cpp:24
Data structure used to store byte strings.
Definition: queue.h:18
virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a public key from a private key in this domain.
virtual bool IsolatedMessageSeriesEnd(bool blocking)
Marks the end of a series of messages, without signal propagation.
Definition: cryptlib.h:1769
virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate ephemeral public key.
virtual bool AnyRetrievable() const
Determines whether bytes are ready for retrieval.
Definition: cryptlib.cpp:514
virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0
Create a new HashTransformation to accumulate the message to be verified.
size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER)
Retrieve a 16-bit word.
Definition: cryptlib.cpp:793
virtual bool IsolatedFlush(bool hardFlush, bool blocking)=0
Flushes data buffered by this object, without signal propagation.
void GetWaitObjects(WaitObjectContainer &container, CallStack const &callStack)
Retrieves waitable objects.
Definition: cryptlib.cpp:426
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:360
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
Definition: cryptlib.cpp:200
Implementation of BufferedTransformation&#39;s attachment interface.
const char * IV()
ConstByteArrayParameter, also accepts const byte * for backwards compatibility.
Definition: argnames.h:21
The self tests have not been performed.
Definition: fips140.h:40
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2745
unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const
Copy messages from this object to another BufferedTransformation.
Definition: cryptlib.cpp:665
virtual lword MaxMessageLength() const =0
Provides the maximum length of encrypted data.
virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate private key in this domain.
A decryption filter encountered invalid ciphertext.
Definition: cryptlib.h:216
size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 32-bit word for processing.
Definition: cryptlib.cpp:750
void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
Sets or reset the key of this object.
Definition: cryptlib.cpp:69
PTR PtrAdd(PTR pointer, OFF offset)
Create a pointer with an offset.
Definition: misc.h:343
virtual lword MaxRetrievable() const
Provides the number of bytes ready for retrieval.
Definition: cryptlib.cpp:504
size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER)
Retrieve a 32-bit word.
Definition: cryptlib.cpp:798
virtual unsigned int GenerateBit()
Generate new random bit and return it.
Definition: cryptlib.cpp:271
Base class for unflushable filters.
Definition: simple.h:108
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
Sign and delete the messageAccumulator.
Definition: cryptlib.cpp:909
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new encryption filter.
Definition: cryptlib.cpp:856
Classes and functions for the FIPS 140-2 validated library.
virtual unsigned int DigestSize() const =0
Provides the digest size of the hash.
virtual size_t CiphertextLength(size_t plaintextLength) const =0
Calculate the length of ciphertext given length of plaintext.
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)
Encrypts and calculates a MAC in one call.
Definition: cryptlib.cpp:247
lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
copy copyMax bytes of the buffered output to target as input
Definition: cryptlib.h:1926
CRYPTOPP_DLL PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus()
Provides the current power-up self test status.
Definition: fips140.cpp:34
Xor inputs before transformation.
Definition: cryptlib.h:893
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1659
virtual size_t MaxDerivedLength() const
Determine maximum number of bytes.
Definition: cryptlib.cpp:341
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2410
virtual void SkipAll()
Skip all messages in the series.
Definition: cryptlib.cpp:673
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
Generate a random key or crypto parameters.
Definition: cryptlib.cpp:811
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:636
CRYPTOPP_DLL void CRYPTOPP_API xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
Definition: misc.cpp:32
size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 16-bit word for processing.
Definition: cryptlib.cpp:745
virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0
Create a new HashTransformation to accumulate the message to be signed.
virtual bool GetNextMessage()
Start retrieving the next message.
Definition: cryptlib.cpp:613
Exception thrown when an invalid derived key length is encountered.
Definition: simple.h:73
CRYPTOPP_DLL BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
Definition: cryptlib.cpp:40
virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0
Sign and restart messageAccumulator.
bool isValidCoding
Flag to indicate the decoding is valid.
Definition: cryptlib.h:276
size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 16-bit word.
Definition: cryptlib.cpp:762
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prescribes the data lengths.
Definition: cryptlib.cpp:233
Acts as an input discarding Filter or Sink.
Definition: simple.h:349
perform the transformation in reverse
Definition: cryptlib.h:895
virtual size_t Get(byte &outByte)
Retrieve a 8-bit byte.
Definition: cryptlib.cpp:527
int LibraryVersion(...)
Specifies the build-time version of the library.
Definition: cryptlib.cpp:984
Crypto++ library namespace.
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate ephemeral private key.
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:350
The IV must be random and unpredictable.
Definition: cryptlib.h:697
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition: cryptlib.h:712
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
Recover a message from its signature.
Definition: cryptlib.cpp:945
virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0
Input signature into a message accumulator.
unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
Transfer messages from this object to another BufferedTransformation.
Definition: cryptlib.h:1983
bool CanIncorporateEntropy() const
An implementation that returns false.
Definition: cryptlib.cpp:389
void IncorporateEntropy(const byte *input, size_t length)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:387
const std::string AAD_CHANNEL
Channel for additional authenticated data.
Definition: cryptlib.h:491
virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes that may be modified by callee.
Definition: cryptlib.h:1717
virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1)
Initialize or reinitialize this object, with signal propagation.
Definition: cryptlib.cpp:433
size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 16-bit word for processing on a channel.
Definition: cryptlib.cpp:733
virtual lword MaxFooterLength() const
Provides the the maximum length of AAD.
Definition: cryptlib.h:1313
void DiscardBytes(size_t n)
An implementation that does nothing.
Definition: cryptlib.cpp:391
virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv)
Retrieves a secure IV for the next message.
Definition: cryptlib.cpp:136
size_t Get(byte &outByte)
Retrieve a 8-bit byte.
Definition: queue.cpp:301
virtual void Update(const byte *input, size_t length)=0
Updates a hash with additional input.
unsigned int BitPrecision(const T &value)
Returns the number of bits required for a value.
Definition: misc.h:754
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:797
virtual bool Attachable()
Determines whether the object allows attachment.
Definition: cryptlib.h:2237
virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
Generate random bytes into a BufferedTransformation.
Definition: cryptlib.cpp:324
Classes for access to the operating system&#39;s random number generators.
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition: cryptlib.h:2155
virtual unsigned int MinLastBlockSize() const
Provides the size of the last block.
Definition: cryptlib.h:993
Interface for retrieving values given their names.
Definition: cryptlib.h:293
virtual DecodingResult Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs &parameters=g_nullNameValuePairs) const =0
Decrypt a byte string.
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Definition: cryptlib.cpp:825