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