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