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