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