Crypto++  7.0
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  // Squash C4505 on Visual Studio 2008 and friends
274  return "Unknown";
275 }
276 
278 {
279  return GenerateByte() & 1;
280 }
281 
283 {
284  byte b;
285  GenerateBlock(&b, 1);
286  return b;
287 }
288 
289 word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
290 {
291  const word32 range = max-min;
292  const unsigned int maxBits = BitPrecision(range);
293 
294  word32 value;
295 
296  do
297  {
298  GenerateBlock((byte *)&value, sizeof(value));
299  value = Crop(value, maxBits);
300  } while (value > range);
301 
302  return value+min;
303 }
304 
305 // Stack recursion below... GenerateIntoBufferedTransformation calls GenerateBlock,
306 // and GenerateBlock calls GenerateIntoBufferedTransformation. Ad infinitum. Also
307 // see http://github.com/weidai11/cryptopp/issues/38.
308 //
309 // According to Wei, RandomNumberGenerator is an interface, and it should not
310 // be instantiable. Its now spilt milk, and we are going to CRYPTOPP_ASSERT it in Debug
311 // builds to alert the programmer and throw in Release builds. Developers have
312 // a reference implementation in case its needed. If a programmer
313 // unintentionally lands here, then they should ensure use of a
314 // RandomNumberGenerator pointer or reference so polymorphism can provide the
315 // proper runtime dispatching.
316 
317 void RandomNumberGenerator::GenerateBlock(byte *output, size_t size)
318 {
319  CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
320 
321  ArraySink s(output, size);
323 }
324 
326 {
328 }
329 
330 void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
331 {
333  while (length)
334  {
335  size_t len = UnsignedMin(buffer.size(), length);
336  GenerateBlock(buffer, len);
337  (void)target.ChannelPut(channel, buffer, len);
338  length -= len;
339  }
340 }
341 
343 {
344  return 0;
345 }
346 
348 {
349  return static_cast<size_t>(-1);
350 }
351 
352 void KeyDerivationFunction::ThrowIfInvalidDerivedLength(size_t length) const
353 {
354  if (!IsValidDerivedLength(length))
355  throw InvalidDerivedLength(GetAlgorithm().AlgorithmName(), length);
356 }
357 
359  CRYPTOPP_UNUSED(params);
360 }
361 
362 /// \brief Random Number Generator that does not produce random numbers
363 /// \details ClassNullRNG can be used for functions that require a RandomNumberGenerator
364 /// but don't actually use it. The class throws NotImplemented when a generation function is called.
365 /// \sa NullRNG()
367 {
368 public:
369  /// \brief The name of the generator
370  /// \returns the string \a NullRNGs
371  std::string AlgorithmName() const {return "NullRNG";}
372 
373 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
374  /// \brief An implementation that throws NotImplemented
375  byte GenerateByte () {}
376  /// \brief An implementation that throws NotImplemented
377  unsigned int GenerateBit () {}
378  /// \brief An implementation that throws NotImplemented
379  word32 GenerateWord32 (word32 min, word32 max) {}
380 #endif
381 
382  /// \brief An implementation that throws NotImplemented
383  void GenerateBlock(byte *output, size_t size)
384  {
385  CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
386  throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
387  }
388 
389 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
390  /// \brief An implementation that throws NotImplemented
391  void GenerateIntoBufferedTransformation (BufferedTransformation &target, const std::string &channel, lword length) {}
392  /// \brief An implementation that throws NotImplemented
393  void IncorporateEntropy (const byte *input, size_t length) {}
394  /// \brief An implementation that returns \p false
395  bool CanIncorporateEntropy () const {}
396  /// \brief An implementation that does nothing
397  void DiscardBytes (size_t n) {}
398  /// \brief An implementation that does nothing
399  void Shuffle (IT begin, IT end) {}
400 
401 private:
402  Clonable* Clone () const { return NULLPTR; }
403 #endif
404 };
405 
407 {
408  static ClassNullRNG s_nullRNG;
409  return s_nullRNG;
410 }
411 
412 bool HashTransformation::TruncatedVerify(const byte *digest, size_t digestLength)
413 {
414  ThrowIfInvalidTruncatedSize(digestLength);
415  SecByteBlock calculated(digestLength);
416  TruncatedFinal(calculated, digestLength);
417  return VerifyBufsEqual(calculated, digest, digestLength);
418 }
419 
420 void HashTransformation::ThrowIfInvalidTruncatedSize(size_t size) const
421 {
422  if (size > DigestSize())
423  throw InvalidArgument("HashTransformation: can't truncate a " + IntToString(DigestSize()) + " byte digest to " + IntToString(size) + " bytes");
424 }
425 
427 {
429  return t ? t->GetMaxWaitObjectCount() : 0;
430 }
431 
433 {
435  if (t)
436  t->GetWaitObjects(container, callStack); // reduce clutter by not adding to stack here
437 }
438 
439 void BufferedTransformation::Initialize(const NameValuePairs &parameters, int propagation)
440 {
441  CRYPTOPP_UNUSED(propagation);
443  IsolatedInitialize(parameters);
444 }
445 
446 bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking)
447 {
448  CRYPTOPP_UNUSED(propagation);
450  return IsolatedFlush(hardFlush, blocking);
451 }
452 
453 bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking)
454 {
455  CRYPTOPP_UNUSED(propagation);
457  return IsolatedMessageSeriesEnd(blocking);
458 }
459 
460 byte * BufferedTransformation::ChannelCreatePutSpace(const std::string &channel, size_t &size)
461 {
462  byte* space = NULLPTR;
463  if (channel.empty())
464  space = CreatePutSpace(size);
465  else
467  return space;
468 }
469 
470 size_t BufferedTransformation::ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking)
471 {
472  size_t size = 0;
473  if (channel.empty())
474  size = Put2(inString, length, messageEnd, blocking);
475  else
477  return size;
478 }
479 
480 size_t BufferedTransformation::ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking)
481 {
482  size_t size = 0;
483  if (channel.empty())
484  size = PutModifiable2(inString, length, messageEnd, blocking);
485  else
486  size = ChannelPut2(channel, inString, length, messageEnd, blocking);
487  return size;
488 }
489 
490 bool BufferedTransformation::ChannelFlush(const std::string &channel, bool hardFlush, int propagation, bool blocking)
491 {
492  bool result = 0;
493  if (channel.empty())
494  result = Flush(hardFlush, propagation, blocking);
495  else
497  return result;
498 }
499 
500 bool BufferedTransformation::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
501 {
502  bool result = false;
503  if (channel.empty())
504  result = MessageSeriesEnd(propagation, blocking);
505  else
507  return result;
508 }
509 
511 {
512  lword size = 0;
515  else
516  size = CopyTo(TheBitBucket());
517  return size;
518 }
519 
521 {
522  bool result = false;
525  else
526  {
527  byte b;
528  result = Peek(b) != 0;
529  }
530  return result;
531 }
532 
533 size_t BufferedTransformation::Get(byte &outByte)
534 {
535  size_t size = 0;
537  size = AttachedTransformation()->Get(outByte);
538  else
539  size = Get(&outByte, 1);
540  return size;
541 }
542 
543 size_t BufferedTransformation::Get(byte *outString, size_t getMax)
544 {
545  size_t size = 0;
547  size = AttachedTransformation()->Get(outString, getMax);
548  else
549  {
550  ArraySink arraySink(outString, getMax);
551  size = (size_t)TransferTo(arraySink, getMax);
552  }
553  return size;
554 }
555 
556 size_t BufferedTransformation::Peek(byte &outByte) const
557 {
558  size_t size = 0;
560  size = AttachedTransformation()->Peek(outByte);
561  else
562  size = Peek(&outByte, 1);
563  return size;
564 }
565 
566 size_t BufferedTransformation::Peek(byte *outString, size_t peekMax) const
567 {
568  size_t size = 0;
570  size = AttachedTransformation()->Peek(outString, peekMax);
571  else
572  {
573  ArraySink arraySink(outString, peekMax);
574  size = (size_t)CopyTo(arraySink, peekMax);
575  }
576  return size;
577 }
578 
579 lword BufferedTransformation::Skip(lword skipMax)
580 {
581  lword size = 0;
583  size = AttachedTransformation()->Skip(skipMax);
584  else
585  size = TransferTo(TheBitBucket(), skipMax);
586  return size;
587 }
588 
590 {
591  lword size = 0;
594  else
595  size = MaxRetrievable();
596  return size;
597 }
598 
600 {
601  unsigned int size = 0;
604  else
605  size = CopyMessagesTo(TheBitBucket());
606  return size;
607 }
608 
610 {
611  bool result = false;
613  result = AttachedTransformation()->AnyMessages();
614  else
615  result = NumberOfMessages() != 0;
616  return result;
617 }
618 
620 {
621  bool result = false;
624  else
625  {
627  }
628  return result;
629 }
630 
631 unsigned int BufferedTransformation::SkipMessages(unsigned int count)
632 {
633  unsigned int size = 0;
635  size = AttachedTransformation()->SkipMessages(count);
636  else
637  size = TransferMessagesTo(TheBitBucket(), count);
638  return size;
639 }
640 
641 size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel, bool blocking)
642 {
644  return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
645  else
646  {
647  unsigned int maxMessages = messageCount;
648  for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
649  {
650  size_t blockedBytes;
651  lword transferredBytes;
652 
653  while (AnyRetrievable())
654  {
655  transferredBytes = LWORD_MAX;
656  blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
657  if (blockedBytes > 0)
658  return blockedBytes;
659  }
660 
661  if (target.ChannelMessageEnd(channel, GetAutoSignalPropagation(), blocking))
662  return 1;
663 
664  bool result = GetNextMessage();
665  CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result);
666  }
667  return 0;
668  }
669 }
670 
671 unsigned int BufferedTransformation::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
672 {
673  unsigned int size = 0;
675  size = AttachedTransformation()->CopyMessagesTo(target, count, channel);
676  return size;
677 }
678 
680 {
683  else
684  {
685  while (SkipMessages()) {}
686  while (Skip()) {}
687  }
688 }
689 
690 size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, const std::string &channel, bool blocking)
691 {
693  return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
694  else
695  {
697 
698  unsigned int messageCount;
699  do
700  {
701  messageCount = UINT_MAX;
702  size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
703  if (blockedBytes)
704  return blockedBytes;
705  }
706  while (messageCount != 0);
707 
708  lword byteCount;
709  do
710  {
711  byteCount = ULONG_MAX;
712  size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
713  if (blockedBytes)
714  return blockedBytes;
715  }
716  while (byteCount != 0);
717 
718  return 0;
719  }
720 }
721 
722 void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std::string &channel) const
723 {
725  AttachedTransformation()->CopyAllTo(target, channel);
726  else
727  {
729  while (CopyMessagesTo(target, UINT_MAX, channel)) {}
730  }
731 }
732 
733 void BufferedTransformation::SetRetrievalChannel(const std::string &channel)
734 {
737 }
738 
739 size_t BufferedTransformation::ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order, bool blocking)
740 {
741  PutWord(false, order, m_buf, value);
742  return ChannelPut(channel, m_buf, 2, blocking);
743 }
744 
745 size_t BufferedTransformation::ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order, bool blocking)
746 {
747  PutWord(false, order, m_buf, value);
748  return ChannelPut(channel, m_buf, 4, blocking);
749 }
750 
751 size_t BufferedTransformation::PutWord16(word16 value, ByteOrder order, bool blocking)
752 {
753  return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
754 }
755 
756 size_t BufferedTransformation::PutWord32(word32 value, ByteOrder order, bool blocking)
757 {
758  return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
759 }
760 
761 // Issue 340
762 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
763 # pragma GCC diagnostic push
764 # pragma GCC diagnostic ignored "-Wconversion"
765 # pragma GCC diagnostic ignored "-Wsign-conversion"
766 #endif
767 
768 size_t BufferedTransformation::PeekWord16(word16 &value, ByteOrder order) const
769 {
770  byte buf[2] = {0, 0};
771  size_t len = Peek(buf, 2);
772 
773  if (order)
774  value = (buf[0] << 8) | buf[1];
775  else
776  value = (buf[1] << 8) | buf[0];
777 
778  return len;
779 }
780 
781 size_t BufferedTransformation::PeekWord32(word32 &value, ByteOrder order) const
782 {
783  byte buf[4] = {0, 0, 0, 0};
784  size_t len = Peek(buf, 4);
785 
786  if (order)
787  value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
788  else
789  value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
790 
791  return len;
792 }
793 
794 // Issue 340
795 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
796 # pragma GCC diagnostic pop
797 #endif
798 
799 size_t BufferedTransformation::GetWord16(word16 &value, ByteOrder order)
800 {
801  return (size_t)Skip(PeekWord16(value, order));
802 }
803 
804 size_t BufferedTransformation::GetWord32(word32 &value, ByteOrder order)
805 {
806  return (size_t)Skip(PeekWord32(value, order));
807 }
808 
810 {
812  AttachedTransformation()->Attach(newAttachment);
813  else
814  Detach(newAttachment);
815 }
816 
818 {
819  GenerateRandom(rng, MakeParameters("KeySize", (int)keySize));
820 }
821 
823 {
824 public:
825  PK_DefaultEncryptionFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
826  : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
827  {
828  Detach(attachment);
829  }
830 
831  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
832  {
833  FILTER_BEGIN;
834  m_plaintextQueue.Put(inString, length);
835 
836  if (messageEnd)
837  {
838  {
839  size_t plaintextLength;
840  if (!SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
841  throw InvalidArgument("PK_DefaultEncryptionFilter: plaintext too long");
842  size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
843 
844  SecByteBlock plaintext(plaintextLength);
845  m_plaintextQueue.Get(plaintext, plaintextLength);
846  m_ciphertext.resize(ciphertextLength);
847  m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
848  }
849 
850  FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
851  }
852  FILTER_END_NO_MESSAGE_END;
853  }
854 
855  RandomNumberGenerator &m_rng;
856  const PK_Encryptor &m_encryptor;
857  const NameValuePairs &m_parameters;
858  ByteQueue m_plaintextQueue;
859  SecByteBlock m_ciphertext;
860 };
861 
863 {
864  return new PK_DefaultEncryptionFilter(rng, *this, attachment, parameters);
865 }
866 
868 {
869 public:
870  PK_DefaultDecryptionFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
871  : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
872  {
873  Detach(attachment);
874  }
875 
876  size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
877  {
878  FILTER_BEGIN;
879  m_ciphertextQueue.Put(inString, length);
880 
881  if (messageEnd)
882  {
883  {
884  size_t ciphertextLength;
885  if (!SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
886  throw InvalidArgument("PK_DefaultDecryptionFilter: ciphertext too long");
887  size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
888 
889  SecByteBlock ciphertext(ciphertextLength);
890  m_ciphertextQueue.Get(ciphertext, ciphertextLength);
891  m_plaintext.resize(maxPlaintextLength);
892  m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
893  if (!m_result.isValidCoding)
894  throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
895  }
896 
897  FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
898  }
899  FILTER_END_NO_MESSAGE_END;
900  }
901 
902  RandomNumberGenerator &m_rng;
903  const PK_Decryptor &m_decryptor;
904  const NameValuePairs &m_parameters;
905  ByteQueue m_ciphertextQueue;
906  SecByteBlock m_plaintext;
907  DecodingResult m_result;
908 };
909 
911 {
912  return new PK_DefaultDecryptionFilter(rng, *this, attachment, parameters);
913 }
914 
915 size_t PK_Signer::Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
916 {
917  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
918  return SignAndRestart(rng, *m, signature, false);
919 }
920 
921 size_t PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
922 {
924  m->Update(message, messageLen);
925  return SignAndRestart(rng, *m, signature, false);
926 }
927 
928 size_t PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
929  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const
930 {
932  InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
933  m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
934  return SignAndRestart(rng, *m, signature, false);
935 }
936 
937 bool PK_Verifier::Verify(PK_MessageAccumulator *messageAccumulator) const
938 {
939  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
940  return VerifyAndRestart(*m);
941 }
942 
943 bool PK_Verifier::VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLen) const
944 {
946  InputSignature(*m, signature, signatureLen);
947  m->Update(message, messageLen);
948  return VerifyAndRestart(*m);
949 }
950 
951 DecodingResult PK_Verifier::Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
952 {
953  member_ptr<PK_MessageAccumulator> m(messageAccumulator);
954  return RecoverAndRestart(recoveredMessage, *m);
955 }
956 
958  const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
959  const byte *signature, size_t signatureLength) const
960 {
962  InputSignature(*m, signature, signatureLength);
963  m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
964  return RecoverAndRestart(recoveredMessage, *m);
965 }
966 
967 void SimpleKeyAgreementDomain::GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
968 {
969  GeneratePrivateKey(rng, privateKey);
970  GeneratePublicKey(rng, privateKey, publicKey);
971 }
972 
973 void AuthenticatedKeyAgreementDomain::GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
974 {
975  GenerateStaticPrivateKey(rng, privateKey);
976  GenerateStaticPublicKey(rng, privateKey, publicKey);
977 }
978 
979 void AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
980 {
981  GenerateEphemeralPrivateKey(rng, privateKey);
982  GenerateEphemeralPublicKey(rng, privateKey, publicKey);
983 }
984 
985 // Allow a distro or packager to override the build-time version
986 // http://github.com/weidai11/cryptopp/issues/371
987 #ifndef CRYPTOPP_BUILD_VERSION
988 # define CRYPTOPP_BUILD_VERSION CRYPTOPP_VERSION
989 #endif
990 int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT)
991 {
992  return CRYPTOPP_BUILD_VERSION;
993 }
994 
995 NAMESPACE_END // CryptoPP
996 
997 #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:480
virtual void SetParameters(const NameValuePairs &params)
Set or change parameters.
Definition: cryptlib.cpp:358
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
Definition: cryptlib.cpp:967
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:745
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:1442
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:690
Classes for working with NameValuePairs.
word32 GenerateWord32(word32 min, word32 max)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:379
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition: cryptlib.h:724
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:641
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:556
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:317
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:2053
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const
Check whether messageAccumulator contains a valid signature and message.
Definition: cryptlib.cpp:937
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
Sign a message.
Definition: cryptlib.cpp:921
unsigned int GetMaxWaitObjectCount() const
Retrieves the maximum number of waitable objects.
Definition: cryptlib.cpp:426
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:1702
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:973
Interface for public-key encryptors.
Definition: cryptlib.h:2526
byte GenerateByte()
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:375
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:289
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:383
virtual void DiscardBytes(size_t n)
Generate and discard n bytes.
Definition: cryptlib.cpp:325
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:391
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:872
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:1013
virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true)
Marks the end of a series of messages, with signal propagation.
Definition: cryptlib.cpp:453
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:1765
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate private/public key pair.
Definition: cryptlib.cpp:979
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:490
virtual bool TruncatedVerify(const byte *digest, size_t digestLength)
Verifies the hash of the current message.
Definition: cryptlib.cpp:412
SecBlock<byte> typedef.
Definition: secblock.h:822
virtual unsigned int SkipMessages(unsigned int count=UINT_MAX)
Skip a number of meessages.
Definition: cryptlib.cpp:631
virtual void SetRetrievalChannel(const std::string &channel)
Sets the default retrieval channel.
Definition: cryptlib.cpp:733
Interface for buffered transformations.
Definition: cryptlib.h:1545
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:722
Interface for cloning objects.
Definition: cryptlib.h:559
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:928
std::string AlgorithmName() const
The name of the generator.
Definition: cryptlib.cpp:371
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Definition: cryptlib.cpp:876
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:2041
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.
virtual std::string AlgorithmName() const =0
Provides the name of this algorithm.
lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
move transferMax bytes of the buffered output to target as input
Definition: cryptlib.h:1848
size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 32-bit word.
Definition: cryptlib.cpp:781
virtual void Attach(BufferedTransformation *newAttachment)
Add newAttachment to the end of attachment chain.
Definition: cryptlib.cpp:809
Interface for public-key decryptors.
Definition: cryptlib.h:2561
void Shuffle(IT begin, IT end)
An implementation that does nothing.
Definition: cryptlib.cpp:399
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:1567
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:481
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:599
virtual lword TotalBytesRetrievable() const
Provides the number of bytes ready for retrieval.
Definition: cryptlib.cpp:589
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition: cryptlib.h:729
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:628
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:500
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:957
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition: cryptlib.h:736
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:918
#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:446
virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.cpp:460
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:832
virtual unsigned int NumberOfMessageSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:1970
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2190
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:943
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:470
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:714
unsigned int GenerateBit()
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:377
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new decryption filter.
Definition: cryptlib.cpp:910
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:579
virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a static public key from a private key in this domain.
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.cpp:271
virtual void Detach(BufferedTransformation *newAttachment=NULL)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:2205
virtual size_t MinDerivedLength() const
Determine minimum number of bytes.
Definition: cryptlib.cpp:342
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:594
RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:406
#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:282
virtual bool AnyMessages() const
Determines if any messages are available for retrieval.
Definition: cryptlib.cpp:609
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:1716
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:520
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:799
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:432
Random Number Generator that does not produce random numbers.
Definition: cryptlib.cpp:366
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:2689
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:671
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:756
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:510
size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER)
Retrieve a 32-bit word.
Definition: cryptlib.cpp:804
virtual unsigned int GenerateBit()
Generate new random bit and return it.
Definition: cryptlib.cpp:277
Base class for unflushable filters.
Definition: simple.h:108
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
Sign and delete the messageAccumulator.
Definition: cryptlib.cpp:915
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new encryption filter.
Definition: cryptlib.cpp:862
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:1873
Xor inputs before transformation.
Definition: cryptlib.h:874
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1606
virtual size_t MaxDerivedLength() const
Determine maximum number of bytes.
Definition: cryptlib.cpp:347
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2354
virtual void SkipAll()
Skip all messages in the series.
Definition: cryptlib.cpp:679
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
Generate a random key or crypto parameters.
Definition: cryptlib.cpp:817
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:751
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:619
Exception thrown when an invalid derived key length is encountered.
Definition: simple.h:73
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:768
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:349
perform the transformation in reverse
Definition: cryptlib.h:876
virtual size_t Get(byte &outByte)
Retrieve a 8-bit byte.
Definition: cryptlib.cpp:533
int LibraryVersion(...)
Specifies the build-time version of the library.
Definition: cryptlib.cpp:990
Crypto++ library namespace.
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate ephemeral private key.
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:347
The IV must be random and unpredictable.
Definition: cryptlib.h:678
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition: cryptlib.h:693
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
Recover a message from its signature.
Definition: cryptlib.cpp:951
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:1930
bool CanIncorporateEntropy() const
An implementation that returns false.
Definition: cryptlib.cpp:395
void IncorporateEntropy(const byte *input, size_t length)
An implementation that throws NotImplemented.
Definition: cryptlib.cpp:393
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:1664
virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1)
Initialize or reinitialize this object, with signal propagation.
Definition: cryptlib.cpp:439
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:739
virtual lword MaxFooterLength() const
Provides the the maximum length of AAD.
Definition: cryptlib.h:1290
void DiscardBytes(size_t n)
An implementation that does nothing.
Definition: cryptlib.cpp:397
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:2184
virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
Generate random bytes into a BufferedTransformation.
Definition: cryptlib.cpp:330
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:2102
virtual unsigned int MinLastBlockSize() const
Provides the size of the last block.
Definition: cryptlib.h:974
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:831