Crypto++  6.1
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 #include "stdcpp.h"
30 
31 // http://www.cygwin.com/faq.html#faq.api.winsock
32 #if (defined(__CYGWIN__) || defined(__CYGWIN32__)) && defined(PREFER_WINDOWS_STYLE_SOCKETS)
33 # error Cygwin does not support Windows style sockets. See http://www.cygwin.com/faq.html#faq.api.winsock
34 #endif
35 
36 NAMESPACE_BEGIN(CryptoPP)
37 
38 CRYPTOPP_COMPILE_ASSERT(sizeof(byte) == 1);
39 CRYPTOPP_COMPILE_ASSERT(sizeof(word16) == 2);
40 CRYPTOPP_COMPILE_ASSERT(sizeof(word32) == 4);
41 CRYPTOPP_COMPILE_ASSERT(sizeof(word64) == 8);
42 #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
43 CRYPTOPP_COMPILE_ASSERT(sizeof(dword) == 2*sizeof(word));
44 #endif
45 
47 {
48  static BitBucket bitBucket;
49  return bitBucket;
50 }
51 
52 Algorithm::Algorithm(bool checkSelfTestStatus)
53 {
54  if (checkSelfTestStatus && FIPS_140_2_ComplianceEnabled())
55  {
56  if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_NOT_DONE && !PowerUpSelfTestInProgressOnThisThread())
57  throw SelfTestFailure("Cryptographic algorithms are disabled before the power-up self tests are performed.");
58 
60  throw SelfTestFailure("Cryptographic algorithms are disabled after a power-up self test failed.");
61  }
62 }
63 
64 void SimpleKeyingInterface::SetKey(const byte *key, size_t length, const NameValuePairs &params)
65 {
66  this->ThrowIfInvalidKeyLength(length);
67  this->UncheckedSetKey(key, static_cast<unsigned int>(length), params);
68 }
69 
70 void SimpleKeyingInterface::SetKeyWithRounds(const byte *key, size_t length, int rounds)
71 {
72  SetKey(key, length, MakeParameters(Name::Rounds(), rounds));
73 }
74 
75 void SimpleKeyingInterface::SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
76 {
77  SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, ivLength)));
78 }
79 
80 void SimpleKeyingInterface::ThrowIfInvalidKeyLength(size_t length)
81 {
82  if (!IsValidKeyLength(length))
83  throw InvalidKeyLength(GetAlgorithm().AlgorithmName(), length);
84 }
85 
86 void SimpleKeyingInterface::ThrowIfResynchronizable()
87 {
88  if (IsResynchronizable())
89  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object requires an IV");
90 }
91 
92 void SimpleKeyingInterface::ThrowIfInvalidIV(const byte *iv)
93 {
94  if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
95  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object cannot use a null IV");
96 }
97 
98 size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(int length)
99 {
100  size_t size = 0;
101  if (length < 0)
102  size = static_cast<size_t>(IVSize());
103  else if ((size_t)length < MinIVLength())
104  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(length) + " is less than the minimum of " + IntToString(MinIVLength()));
105  else if ((size_t)length > MaxIVLength())
106  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(length) + " exceeds the maximum of " + IntToString(MaxIVLength()));
107  else
108  size = static_cast<size_t>(length);
109 
110  return size;
111 }
112 
113 const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size)
114 {
115  ConstByteArrayParameter ivWithLength;
116  const byte *iv = NULLPTR;
117  bool found = false;
118 
119  try {found = params.GetValue(Name::IV(), ivWithLength);}
120  catch (const NameValuePairs::ValueTypeMismatch &) {}
121 
122  if (found)
123  {
124  iv = ivWithLength.begin();
125  ThrowIfInvalidIV(iv);
126  size = ThrowIfInvalidIVLength(static_cast<int>(ivWithLength.size()));
127  }
128  else if (params.GetValue(Name::IV(), iv))
129  {
130  ThrowIfInvalidIV(iv);
131  size = static_cast<size_t>(IVSize());
132  }
133  else
134  {
135  ThrowIfResynchronizable();
136  size = 0;
137  }
138 
139  return iv;
140 }
141 
143 {
144  rng.GenerateBlock(iv, IVSize());
145 }
146 
147 size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const
148 {
149  CRYPTOPP_ASSERT(inBlocks);
150  CRYPTOPP_ASSERT(outBlocks);
151  CRYPTOPP_ASSERT(length);
152 
153  const size_t blockSize = BlockSize();
154  ptrdiff_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize;
155  ptrdiff_t xorIncrement = xorBlocks ? blockSize : 0;
156  ptrdiff_t outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : blockSize;
157 
158  if (flags & BT_ReverseDirection)
159  {
160  inBlocks += static_cast<ptrdiff_t>(length) - blockSize;
161  xorBlocks += static_cast<ptrdiff_t>(length) - blockSize;
162  outBlocks += static_cast<ptrdiff_t>(length) - blockSize;
163  inIncrement = 0-inIncrement;
164  xorIncrement = 0-xorIncrement;
165  outIncrement = 0-outIncrement;
166  }
167 
168  // Coverity finding.
169  const bool xorFlag = xorBlocks && (flags & BT_XorInput);
170  while (length >= blockSize)
171  {
172  if (xorFlag)
173  {
174  // xorBlocks non-NULL and with BT_XorInput.
175  xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
176  ProcessBlock(outBlocks);
177  }
178  else
179  {
180  // xorBlocks may be non-NULL and without BT_XorInput.
181  ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
182  }
183 
184  if (flags & BT_InBlockIsCounter)
185  const_cast<byte *>(inBlocks)[blockSize-1]++;
186 
187  inBlocks += inIncrement;
188  outBlocks += outIncrement;
189  xorBlocks += xorIncrement;
190  length -= blockSize;
191  }
192 
193  return length;
194 }
195 
197 {
198  return GetAlignmentOf<word32>();
199 }
200 
202 {
203  return GetAlignmentOf<word32>();
204 }
205 
207 {
208  return GetAlignmentOf<word32>();
209 }
210 
211 #if 0
212 void StreamTransformation::ProcessLastBlock(byte *outString, const byte *inString, size_t length)
213 {
214  CRYPTOPP_ASSERT(MinLastBlockSize() == 0); // this function should be overridden otherwise
215 
216  if (length == MandatoryBlockSize())
217  ProcessData(outString, inString, length);
218  else if (length != 0)
219  throw NotImplemented(AlgorithmName() + ": this object doesn't support a special last block");
220 }
221 #endif
222 
223 size_t StreamTransformation::ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength)
224 {
225  // this function should be overridden otherwise
227 
228  if (inLength == MandatoryBlockSize())
229  {
230  outLength = inLength; // squash unused warning
231  ProcessData(outString, inString, inLength);
232  }
233  else if (inLength != 0)
234  throw NotImplemented(AlgorithmName() + ": this object doesn't support a special last block");
235 
236  return outLength;
237 }
238 
239 void AuthenticatedSymmetricCipher::SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
240 {
241  if (headerLength > MaxHeaderLength())
242  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": header length " + IntToString(headerLength) + " exceeds the maximum of " + IntToString(MaxHeaderLength()));
243 
244  if (messageLength > MaxMessageLength())
245  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": message length " + IntToString(messageLength) + " exceeds the maximum of " + IntToString(MaxMessageLength()));
246 
247  if (footerLength > MaxFooterLength())
248  throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": footer length " + IntToString(footerLength) + " exceeds the maximum of " + IntToString(MaxFooterLength()));
249 
250  UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
251 }
252 
253 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)
254 {
255  Resynchronize(iv, ivLength);
256  SpecifyDataLengths(headerLength, messageLength);
257  Update(header, headerLength);
258  ProcessString(ciphertext, message, messageLength);
259  TruncatedFinal(mac, macSize);
260 }
261 
262 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)
263 {
264  Resynchronize(iv, ivLength);
265  SpecifyDataLengths(headerLength, ciphertextLength);
266  Update(header, headerLength);
267  ProcessString(message, ciphertext, ciphertextLength);
268  return TruncatedVerify(mac, macLength);
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 
336 /// \brief Random Number Generator that does not produce random numbers
337 /// \details ClassNullRNG can be used for functions that require a RandomNumberGenerator
338 /// but don't actually use it. The class throws NotImplemented when a generation function is called.
339 /// \sa NullRNG()
341 {
342 public:
343  /// \brief The name of the generator
344  /// \returns the string \a NullRNGs
345  std::string AlgorithmName() const {return "NullRNG";}
346 
347 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
348  /// \brief An implementation that throws NotImplemented
349  byte GenerateByte () {}
350  /// \brief An implementation that throws NotImplemented
351  unsigned int GenerateBit () {}
352  /// \brief An implementation that throws NotImplemented
353  word32 GenerateWord32 (word32 min, word32 max) {}
354 #endif
355 
356  /// \brief An implementation that throws NotImplemented
357  void GenerateBlock(byte *output, size_t size)
358  {
359  CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
360  throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
361  }
362 
363 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
364  /// \brief An implementation that throws NotImplemented
365  void GenerateIntoBufferedTransformation (BufferedTransformation &target, const std::string &channel, lword length) {}
366  /// \brief An implementation that throws NotImplemented
367  void IncorporateEntropy (const byte *input, size_t length) {}
368  /// \brief An implementation that returns \p false
369  bool CanIncorporateEntropy () const {}
370  /// \brief An implementation that does nothing
371  void DiscardBytes (size_t n) {}
372  /// \brief An implementation that does nothing
373  void Shuffle (IT begin, IT end) {}
374 
375 private:
376  Clonable* Clone () const { return NULLPTR; }
377 #endif
378 };
379 
381 {
382  static ClassNullRNG s_nullRNG;
383  return s_nullRNG;
384 }
385 
386 bool HashTransformation::TruncatedVerify(const byte *digest, size_t digestLength)
387 {
388  ThrowIfInvalidTruncatedSize(digestLength);
389  SecByteBlock calculated(digestLength);
390  TruncatedFinal(calculated, digestLength);
391  return VerifyBufsEqual(calculated, digest, digestLength);
392 }
393 
394 void HashTransformation::ThrowIfInvalidTruncatedSize(size_t size) const
395 {
396  if (size > DigestSize())
397  throw InvalidArgument("HashTransformation: can't truncate a " + IntToString(DigestSize()) + " byte digest to " + IntToString(size) + " bytes");
398 }
399 
401 {
403  return t ? t->GetMaxWaitObjectCount() : 0;
404 }
405 
407 {
409  if (t)
410  t->GetWaitObjects(container, callStack); // reduce clutter by not adding to stack here
411 }
412 
413 void BufferedTransformation::Initialize(const NameValuePairs &parameters, int propagation)
414 {
415  CRYPTOPP_UNUSED(propagation);
417  IsolatedInitialize(parameters);
418 }
419 
420 bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking)
421 {
422  CRYPTOPP_UNUSED(propagation);
424  return IsolatedFlush(hardFlush, blocking);
425 }
426 
427 bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking)
428 {
429  CRYPTOPP_UNUSED(propagation);
431  return IsolatedMessageSeriesEnd(blocking);
432 }
433 
434 byte * BufferedTransformation::ChannelCreatePutSpace(const std::string &channel, size_t &size)
435 {
436  byte* space = NULLPTR;
437  if (channel.empty())
438  space = CreatePutSpace(size);
439  else
441  return space;
442 }
443 
444 size_t BufferedTransformation::ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking)
445 {
446  size_t size = 0;
447  if (channel.empty())
448  size = Put2(inString, length, messageEnd, blocking);
449  else
451  return size;
452 }
453 
454 size_t BufferedTransformation::ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking)
455 {
456  size_t size = 0;
457  if (channel.empty())
458  size = PutModifiable2(inString, length, messageEnd, blocking);
459  else
460  size = ChannelPut2(channel, inString, length, messageEnd, blocking);
461  return size;
462 }
463 
464 bool BufferedTransformation::ChannelFlush(const std::string &channel, bool hardFlush, int propagation, bool blocking)
465 {
466  bool result = 0;
467  if (channel.empty())
468  result = Flush(hardFlush, propagation, blocking);
469  else
471  return result;
472 }
473 
474 bool BufferedTransformation::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
475 {
476  bool result = false;
477  if (channel.empty())
478  result = MessageSeriesEnd(propagation, blocking);
479  else
481  return result;
482 }
483 
485 {
486  lword size = 0;
489  else
490  size = CopyTo(TheBitBucket());
491  return size;
492 }
493 
495 {
496  bool result = false;
499  else
500  {
501  byte b;
502  result = Peek(b) != 0;
503  }
504  return result;
505 }
506 
507 size_t BufferedTransformation::Get(byte &outByte)
508 {
509  size_t size = 0;
511  size = AttachedTransformation()->Get(outByte);
512  else
513  size = Get(&outByte, 1);
514  return size;
515 }
516 
517 size_t BufferedTransformation::Get(byte *outString, size_t getMax)
518 {
519  size_t size = 0;
521  size = AttachedTransformation()->Get(outString, getMax);
522  else
523  {
524  ArraySink arraySink(outString, getMax);
525  size = (size_t)TransferTo(arraySink, getMax);
526  }
527  return size;
528 }
529 
530 size_t BufferedTransformation::Peek(byte &outByte) const
531 {
532  size_t size = 0;
534  size = AttachedTransformation()->Peek(outByte);
535  else
536  size = Peek(&outByte, 1);
537  return size;
538 }
539 
540 size_t BufferedTransformation::Peek(byte *outString, size_t peekMax) const
541 {
542  size_t size = 0;
544  size = AttachedTransformation()->Peek(outString, peekMax);
545  else
546  {
547  ArraySink arraySink(outString, peekMax);
548  size = (size_t)CopyTo(arraySink, peekMax);
549  }
550  return size;
551 }
552 
553 lword BufferedTransformation::Skip(lword skipMax)
554 {
555  lword size = 0;
557  size = AttachedTransformation()->Skip(skipMax);
558  else
559  size = TransferTo(TheBitBucket(), skipMax);
560  return size;
561 }
562 
564 {
565  lword size = 0;
568  else
569  size = MaxRetrievable();
570  return size;
571 }
572 
574 {
575  unsigned int size = 0;
578  else
579  size = CopyMessagesTo(TheBitBucket());
580  return size;
581 }
582 
584 {
585  bool result = false;
587  result = AttachedTransformation()->AnyMessages();
588  else
589  result = NumberOfMessages() != 0;
590  return result;
591 }
592 
594 {
595  bool result = false;
598  else
599  {
601  }
602  return result;
603 }
604 
605 unsigned int BufferedTransformation::SkipMessages(unsigned int count)
606 {
607  unsigned int size = 0;
609  size = AttachedTransformation()->SkipMessages(count);
610  else
611  size = TransferMessagesTo(TheBitBucket(), count);
612  return size;
613 }
614 
615 size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel, bool blocking)
616 {
618  return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
619  else
620  {
621  unsigned int maxMessages = messageCount;
622  for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
623  {
624  size_t blockedBytes;
625  lword transferredBytes;
626 
627  while (AnyRetrievable())
628  {
629  transferredBytes = LWORD_MAX;
630  blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
631  if (blockedBytes > 0)
632  return blockedBytes;
633  }
634 
635  if (target.ChannelMessageEnd(channel, GetAutoSignalPropagation(), blocking))
636  return 1;
637 
638  bool result = GetNextMessage();
639  CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result);
640  }
641  return 0;
642  }
643 }
644 
645 unsigned int BufferedTransformation::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
646 {
647  unsigned int size = 0;
649  size = AttachedTransformation()->CopyMessagesTo(target, count, channel);
650  return size;
651 }
652 
654 {
657  else
658  {
659  while (SkipMessages()) {}
660  while (Skip()) {}
661  }
662 }
663 
664 size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, const std::string &channel, bool blocking)
665 {
667  return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
668  else
669  {
671 
672  unsigned int messageCount;
673  do
674  {
675  messageCount = UINT_MAX;
676  size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
677  if (blockedBytes)
678  return blockedBytes;
679  }
680  while (messageCount != 0);
681 
682  lword byteCount;
683  do
684  {
685  byteCount = ULONG_MAX;
686  size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
687  if (blockedBytes)
688  return blockedBytes;
689  }
690  while (byteCount != 0);
691 
692  return 0;
693  }
694 }
695 
696 void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std::string &channel) const
697 {
699  AttachedTransformation()->CopyAllTo(target, channel);
700  else
701  {
703  while (CopyMessagesTo(target, UINT_MAX, channel)) {}
704  }
705 }
706 
707 void BufferedTransformation::SetRetrievalChannel(const std::string &channel)
708 {
711 }
712 
713 size_t BufferedTransformation::ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order, bool blocking)
714 {
715  PutWord(false, order, m_buf, value);
716  return ChannelPut(channel, m_buf, 2, blocking);
717 }
718 
719 size_t BufferedTransformation::ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order, bool blocking)
720 {
721  PutWord(false, order, m_buf, value);
722  return ChannelPut(channel, m_buf, 4, blocking);
723 }
724 
725 size_t BufferedTransformation::PutWord16(word16 value, ByteOrder order, bool blocking)
726 {
727  return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
728 }
729 
730 size_t BufferedTransformation::PutWord32(word32 value, ByteOrder order, bool blocking)
731 {
732  return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
733 }
734 
735 // Issue 340
736 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
737 # pragma GCC diagnostic push
738 # pragma GCC diagnostic ignored "-Wconversion"
739 # pragma GCC diagnostic ignored "-Wsign-conversion"
740 #endif
741 
742 size_t BufferedTransformation::PeekWord16(word16 &value, ByteOrder order) const
743 {
744  byte buf[2] = {0, 0};
745  size_t len = Peek(buf, 2);
746 
747  if (order)
748  value = (buf[0] << 8) | buf[1];
749  else
750  value = (buf[1] << 8) | buf[0];
751 
752  return len;
753 }
754 
755 size_t BufferedTransformation::PeekWord32(word32 &value, ByteOrder order) const
756 {
757  byte buf[4] = {0, 0, 0, 0};
758  size_t len = Peek(buf, 4);
759 
760  if (order)
761  value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
762  else
763  value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
764 
765  return len;
766 }
767 
768 // Issue 340
769 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
770 # pragma GCC diagnostic pop
771 #endif
772 
773 size_t BufferedTransformation::GetWord16(word16 &value, ByteOrder order)
774 {
775  return (size_t)Skip(PeekWord16(value, order));
776 }
777 
778 size_t BufferedTransformation::GetWord32(word32 &value, ByteOrder order)
779 {
780  return (size_t)Skip(PeekWord32(value, order));
781 }
782 
784 {
786  AttachedTransformation()->Attach(newAttachment);
787  else
788  Detach(newAttachment);
789 }
790 
792 {
793  GenerateRandom(rng, MakeParameters("KeySize", (int)keySize));
794 }
795 
797 {
798 public:
799  PK_DefaultEncryptionFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
800  : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
801  {
802  Detach(attachment);
803  }
804 
805  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
806  {
807  FILTER_BEGIN;
808  m_plaintextQueue.Put(inString, length);
809 
810  if (messageEnd)
811  {
812  {
813  size_t plaintextLength;
814  if (!SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
815  throw InvalidArgument("PK_DefaultEncryptionFilter: plaintext too long");
816  size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
817 
818  SecByteBlock plaintext(plaintextLength);
819  m_plaintextQueue.Get(plaintext, plaintextLength);
820  m_ciphertext.resize(ciphertextLength);
821  m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
822  }
823 
824  FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
825  }
826  FILTER_END_NO_MESSAGE_END;
827  }
828 
829  RandomNumberGenerator &m_rng;
830  const PK_Encryptor &m_encryptor;
831  const NameValuePairs &m_parameters;
832  ByteQueue m_plaintextQueue;
833  SecByteBlock m_ciphertext;
834 };
835 
837 {
838  return new PK_DefaultEncryptionFilter(rng, *this, attachment, parameters);
839 }
840 
842 {
843 public:
844  PK_DefaultDecryptionFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
845  : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
846  {
847  Detach(attachment);
848  }
849 
850  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
851  {
852  FILTER_BEGIN;
853  m_ciphertextQueue.Put(inString, length);
854 
855  if (messageEnd)
856  {
857  {
858  size_t ciphertextLength;
859  if (!SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
860  throw InvalidArgument("PK_DefaultDecryptionFilter: ciphertext too long");
861  size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
862 
863  SecByteBlock ciphertext(ciphertextLength);
864  m_ciphertextQueue.Get(ciphertext, ciphertextLength);
865  m_plaintext.resize(maxPlaintextLength);
866  m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
867  if (!m_result.isValidCoding)
868  throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
869  }
870 
871  FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
872  }
873  FILTER_END_NO_MESSAGE_END;
874  }
875 
876  RandomNumberGenerator &m_rng;
877  const PK_Decryptor &m_decryptor;
878  const NameValuePairs &m_parameters;
879  ByteQueue m_ciphertextQueue;
880  SecByteBlock m_plaintext;
881  DecodingResult m_result;
882 };
883 
885 {
886  return new PK_DefaultDecryptionFilter(rng, *this, attachment, parameters);
887 }
888 
889 size_t PK_Signer::Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
890 {
891  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
892  return SignAndRestart(rng, *m, signature, false);
893 }
894 
895 size_t PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
896 {
898  m->Update(message, messageLen);
899  return SignAndRestart(rng, *m, signature, false);
900 }
901 
902 size_t PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
903  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const
904 {
906  InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
907  m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
908  return SignAndRestart(rng, *m, signature, false);
909 }
910 
911 bool PK_Verifier::Verify(PK_MessageAccumulator *messageAccumulator) const
912 {
913  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
914  return VerifyAndRestart(*m);
915 }
916 
917 bool PK_Verifier::VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLen) const
918 {
920  InputSignature(*m, signature, signatureLen);
921  m->Update(message, messageLen);
922  return VerifyAndRestart(*m);
923 }
924 
925 DecodingResult PK_Verifier::Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
926 {
927  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
928  return RecoverAndRestart(recoveredMessage, *m);
929 }
930 
932  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
933  const byte *signature, size_t signatureLength) const
934 {
936  InputSignature(*m, signature, signatureLength);
937  m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
938  return RecoverAndRestart(recoveredMessage, *m);
939 }
940 
941 void SimpleKeyAgreementDomain::GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
942 {
943  GeneratePrivateKey(rng, privateKey);
944  GeneratePublicKey(rng, privateKey, publicKey);
945 }
946 
947 void AuthenticatedKeyAgreementDomain::GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
948 {
949  GenerateStaticPrivateKey(rng, privateKey);
950  GenerateStaticPublicKey(rng, privateKey, publicKey);
951 }
952 
953 void AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
954 {
955  GenerateEphemeralPrivateKey(rng, privateKey);
956  GenerateEphemeralPublicKey(rng, privateKey, publicKey);
957 }
958 
959 // Allow a distro or packager to override the build-time version
960 // http://github.com/weidai11/cryptopp/issues/371
961 #ifndef CRYPTOPP_BUILD_VERSION
962 # define CRYPTOPP_BUILD_VERSION CRYPTOPP_VERSION
963 #endif
964 int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT)
965 {
966  return CRYPTOPP_BUILD_VERSION;
967 }
968 
969 NAMESPACE_END // CryptoPP
970 
971 #endif // CRYPTOPP_IMPORTS
Used to pass byte array input as part of a NameValuePairs object.
Definition: algparam.h:20
Standard names for retrieving values by name when working with NameValuePairs.
An invalid argument was detected.
Definition: cryptlib.h:199
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:454
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
Definition: cryptlib.cpp:941
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:719
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:664
Classes for working with NameValuePairs.
word32 GenerateWord32(word32 min, word32 max)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:353
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition: cryptlib.h:726
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
Definition: misc.h:562
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:615
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:64
const char * Rounds()
int
Definition: argnames.h:24
virtual size_t Peek(byte &outByte) const
Peek a 8-bit byte.
Definition: cryptlib.cpp:530
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:140
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:1983
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const
Check whether messageAccumulator contains a valid signature and message.
Definition: cryptlib.cpp:911
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
Sign a message.
Definition: cryptlib.cpp:895
unsigned int GetMaxWaitObjectCount() const
Retrieves the maximum number of waitable objects.
Definition: cryptlib.cpp:400
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:1632
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:223
void resize(size_type newSize)
Change size and preserve contents.
Definition: secblock.h:795
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
Definition: misc.h:2295
virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a static private/public key pair.
Definition: cryptlib.cpp:947
Interface for public-key encryptors.
Definition: cryptlib.h:2456
byte GenerateByte()
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:349
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:297
BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
Definition: cryptlib.cpp:46
void GenerateBlock(byte *output, size_t size)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:357
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:365
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:874
Interface for random number generators.
Definition: cryptlib.h:1330
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:1015
virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true)
Marks the end of a series of messages, with signal propagation.
Definition: cryptlib.cpp:427
size_t messageLength
Recovered message length if isValidCoding is true, undefined otherwise.
Definition: cryptlib.h:275
void SetKeyWithRounds(const byte *key, size_t length, int rounds)
Sets or reset the key of this object.
Definition: cryptlib.cpp:70
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1695
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate private/public key pair.
Definition: cryptlib.cpp:953
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:464
virtual bool TruncatedVerify(const byte *digest, size_t digestLength)
Verifies the hash of the current message.
Definition: cryptlib.cpp:386
SecBlock<byte> typedef.
Definition: secblock.h:822
virtual unsigned int SkipMessages(unsigned int count=UINT_MAX)
Skip a number of meessages.
Definition: cryptlib.cpp:605
virtual void SetRetrievalChannel(const std::string &channel)
Sets the default retrieval channel.
Definition: cryptlib.cpp:707
Interface for buffered transformations.
Definition: cryptlib.h:1475
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
Definition: cryptlib.cpp:196
void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const
Copy messages from this object to another BufferedTransformation.
Definition: cryptlib.cpp:696
Interface for cloning objects.
Definition: cryptlib.h:560
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:902
std::string AlgorithmName() const
The name of the generator.
Definition: cryptlib.cpp:345
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Definition: cryptlib.cpp:850
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.
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:1132
Exception thrown when a filter does not support named channels.
Definition: cryptlib.h:1971
Returns a decoding results.
Definition: cryptlib.h:252
Algorithm(bool checkSelfTestStatus=true)
Interface for all crypto algorithms.
Definition: cryptlib.cpp:52
virtual IV_Requirement IVRequirement() const =0
Minimal requirement for secure IVs.
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:1778
size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 32-bit word.
Definition: cryptlib.cpp:755
virtual void Attach(BufferedTransformation *newAttachment)
Add newAttachment to the end of attachment chain.
Definition: cryptlib.cpp:783
Interface for public-key decryptors.
Definition: cryptlib.h:2491
void Shuffle(IT begin, IT end)
An implementation that does nothing.
Definition: cryptlib.cpp:373
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:220
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:1497
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:502
virtual unsigned int NumberOfMessages() const
Provides the number of meesages processed by this object.
Definition: cryptlib.cpp:573
virtual lword TotalBytesRetrievable() const
Provides the number of bytes ready for retrieval.
Definition: cryptlib.cpp:563
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition: cryptlib.h:731
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:629
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:474
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:931
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition: cryptlib.h:738
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:920
#define CRYPTOPP_COMPILE_ASSERT(expr)
Compile time assertion.
Definition: misc.h:144
virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output, with signal propagation.
Definition: cryptlib.cpp:420
virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.cpp:434
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
Definition: misc.h:778
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:147
Precompiled header file.
void ProcessBlock(const byte *inBlock, byte *outBlock) const
Encrypt or decrypt a block.
Definition: cryptlib.h:834
virtual unsigned int NumberOfMessageSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:1900
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2120
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:917
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
Definition: misc.h:546
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:444
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:716
unsigned int GenerateBit()
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:351
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new decryption filter.
Definition: cryptlib.cpp:884
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
Definition: cryptlib.cpp:201
virtual lword Skip(lword skipMax=LWORD_MAX)
Discard skipMax bytes from the output buffer.
Definition: cryptlib.cpp:553
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 void Detach(BufferedTransformation *newAttachment=NULL)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:2135
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:595
RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:380
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:60
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:583
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:1646
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:494
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:773
virtual bool IsolatedFlush(bool hardFlush, bool blocking)=0
Flushes data buffered by this object, without signal propagation.
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:406
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:340
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
Definition: cryptlib.cpp:206
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:2619
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:645
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:213
size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 32-bit word for processing.
Definition: cryptlib.cpp:730
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:75
virtual lword MaxRetrievable() const
Provides the number of bytes ready for retrieval.
Definition: cryptlib.cpp:484
size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER)
Retrieve a 32-bit word.
Definition: cryptlib.cpp:778
virtual unsigned int GenerateBit()
Generate new random bit and return it.
Definition: cryptlib.cpp:271
Base class for unflushable filters.
Definition: simple.h:101
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
Sign and delete the messageAccumulator.
Definition: cryptlib.cpp:889
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new encryption filter.
Definition: cryptlib.cpp:836
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:253
void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
Definition: misc.cpp:32
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:262
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:1803
Xor inputs before transformation.
Definition: cryptlib.h:876
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1536
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2284
virtual void SkipAll()
Skip all messages in the series.
Definition: cryptlib.cpp:653
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
Generate a random key or crypto parameters.
Definition: cryptlib.cpp:791
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:576
size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 16-bit word for processing.
Definition: cryptlib.cpp:725
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:100
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:593
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:273
size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 16-bit word.
Definition: cryptlib.cpp:742
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prespecifies the data lengths.
Definition: cryptlib.cpp:239
Acts as an input discarding Filter or Sink.
Definition: simple.h:342
perform the transformation in reverse
Definition: cryptlib.h:878
virtual size_t Get(byte &outByte)
Retrieve a 8-bit byte.
Definition: cryptlib.cpp:507
int LibraryVersion(...)
Specifies the build-time version of the library.
Definition: cryptlib.cpp:964
Crypto++ library namespace.
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate ephemeral private key.
virtual std::string AlgorithmName() const =0
Provides the name of this algorithm.
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:347
The IV must be random and unpredictable.
Definition: cryptlib.h:680
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition: cryptlib.h:695
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
Recover a message from its signature.
Definition: cryptlib.cpp:925
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:1860
bool CanIncorporateEntropy() const
An implementation that returns false.
Definition: cryptlib.cpp:369
void IncorporateEntropy(const byte *input, size_t length)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:367
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:1594
virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1)
Initialize or reinitialize this object, with signal propagation.
Definition: cryptlib.cpp:413
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:713
virtual lword MaxFooterLength() const
Provides the the maximum length of AAD.
Definition: cryptlib.h:1292
void DiscardBytes(size_t n)
An implementation that does nothing.
Definition: cryptlib.cpp:371
virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv)
Retrieves a secure IV for the next message.
Definition: cryptlib.cpp:142
size_t Get(byte &outByte)
Retrieve a 8-bit byte.
Definition: queue.cpp:300
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:694
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:561
virtual bool Attachable()
Determines whether the object allows attachment.
Definition: cryptlib.h:2114
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:2032
virtual unsigned int MinLastBlockSize() const
Provides the size of the last block.
Definition: cryptlib.h:976
Interface for retrieving values given their names.
Definition: cryptlib.h:290
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:805