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