6 #if CRYPTOPP_MSC_VERSION 7 # pragma warning(disable: 4127 4189 4459) 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" 16 #ifndef CRYPTOPP_IMPORTS 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 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)) 45 #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE 49 #if HAVE_GCC_INIT_PRIORITY 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) 59 const std::string &BufferedTransformation::NULL_CHANNEL =
DEFAULT_CHANNEL;
60 #pragma warning(default: 4073) 63 const std::string AAD_CHANNEL =
"AAD";
64 const std::string &BufferedTransformation::NULL_CHANNEL =
DEFAULT_CHANNEL;
70 bool GetVoidValue(
const char *name,
const std::type_info &valueType,
void *pValue)
const 71 {CRYPTOPP_UNUSED(name); CRYPTOPP_UNUSED(valueType); CRYPTOPP_UNUSED(pValue);
return false;}
74 #if HAVE_GCC_INIT_PRIORITY 93 throw SelfTestFailure(
"Cryptographic algorithms are disabled before the power-up self tests are performed.");
96 throw SelfTestFailure(
"Cryptographic algorithms are disabled after a power-up self test failed.");
102 this->ThrowIfInvalidKeyLength(length);
103 this->UncheckedSetKey(key, (
unsigned int)length, params);
116 void SimpleKeyingInterface::ThrowIfInvalidKeyLength(
size_t length)
118 if (!IsValidKeyLength(length))
122 void SimpleKeyingInterface::ThrowIfResynchronizable()
124 if (IsResynchronizable())
125 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object requires an IV");
128 void SimpleKeyingInterface::ThrowIfInvalidIV(
const byte *iv)
130 if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
131 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object cannot use a null IV");
134 size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(
int size)
138 else if ((
size_t)size < MinIVLength())
140 else if ((
size_t)size > MaxIVLength())
146 const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(
const NameValuePairs ¶ms,
size_t &size)
157 iv = ivWithLength.begin();
158 ThrowIfInvalidIV(iv);
159 size = ThrowIfInvalidIVLength((
int)ivWithLength.size());
164 ThrowIfInvalidIV(iv);
170 ThrowIfResynchronizable();
188 size_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize;
189 size_t xorIncrement = xorBlocks ? blockSize : 0;
190 size_t outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : blockSize;
192 if (flags & BT_ReverseDirection)
194 assert(length % blockSize == 0);
195 inBlocks += length - blockSize;
196 xorBlocks += length - blockSize;
197 outBlocks += length - blockSize;
198 inIncrement = 0-inIncrement;
199 xorIncrement = 0-xorIncrement;
200 outIncrement = 0-outIncrement;
203 while (length >= blockSize)
205 if (flags & BT_XorInput)
209 #if defined(__COVERITY__) 212 xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
213 ProcessBlock(outBlocks);
218 ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
221 if (flags & BT_InBlockIsCounter)
222 const_cast<byte *
>(inBlocks)[blockSize-1]++;
223 inBlocks += inIncrement;
224 outBlocks += outIncrement;
225 xorBlocks += xorIncrement;
234 return GetAlignmentOf<word32>();
239 return GetAlignmentOf<word32>();
244 return GetAlignmentOf<word32>();
249 assert(MinLastBlockSize() == 0);
251 if (length == MandatoryBlockSize())
252 ProcessData(outString, inString, length);
253 else if (length != 0)
254 throw NotImplemented(AlgorithmName() +
": this object does't support a special last block");
259 if (headerLength > MaxHeaderLength())
262 if (messageLength > MaxMessageLength())
265 if (footerLength > MaxFooterLength())
268 UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
273 Resynchronize(iv, ivLength);
274 SpecifyDataLengths(headerLength, messageLength);
275 Update(header, headerLength);
276 ProcessString(ciphertext, message, messageLength);
277 TruncatedFinal(mac, macSize);
282 Resynchronize(iv, ivLength);
283 SpecifyDataLengths(headerLength, ciphertextLength);
284 Update(header, headerLength);
285 ProcessString(message, ciphertext, ciphertextLength);
286 return TruncatedVerify(mac, macLength);
291 return GenerateByte() & 1;
297 GenerateBlock(&b, 1);
303 const word32 range = max-min;
310 GenerateBlock((byte *)&value,
sizeof(value));
311 value =
Crop(value, maxBits);
312 }
while (value > range);
331 CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
335 throw NotImplemented(
"RandomNumberGenerator: GenerateBlock not implemented");
339 GenerateIntoBufferedTransformation(s, DEFAULT_CHANNEL, size);
344 GenerateIntoBufferedTransformation(
TheBitBucket(), DEFAULT_CHANNEL, n);
353 GenerateBlock(buffer, len);
354 size_t rem = target.
ChannelPut(channel, buffer, len);
355 CRYPTOPP_UNUSED(rem); assert(rem == 0);
372 #if defined(CRYPTOPP_DOXYGEN_PROCESSING) 384 CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
385 throw NotImplemented(
"NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
388 #if defined(CRYPTOPP_DOXYGEN_PROCESSING) 401 Clonable* Clone ()
const {
return NULL; }
413 ThrowIfInvalidTruncatedSize(digestLength);
415 TruncatedFinal(digest, digestLength);
419 void HashTransformation::ThrowIfInvalidTruncatedSize(
size_t size)
const 440 CRYPTOPP_UNUSED(propagation);
441 assert(!AttachedTransformation());
442 IsolatedInitialize(parameters);
447 CRYPTOPP_UNUSED(propagation);
448 assert(!AttachedTransformation());
449 return IsolatedFlush(hardFlush, blocking);
454 CRYPTOPP_UNUSED(propagation);
455 assert(!AttachedTransformation());
456 return IsolatedMessageSeriesEnd(blocking);
462 return CreatePutSpace(size);
470 return Put2(begin, length, messageEnd, blocking);
478 return PutModifiable2(begin, length, messageEnd, blocking);
480 return ChannelPut2(channel, begin, length, messageEnd, blocking);
486 return Flush(completeFlush, propagation, blocking);
494 return MessageSeriesEnd(propagation, blocking);
501 if (AttachedTransformation())
502 return AttachedTransformation()->MaxRetrievable();
509 if (AttachedTransformation())
510 return AttachedTransformation()->AnyRetrievable();
520 if (AttachedTransformation())
521 return AttachedTransformation()->Get(outByte);
523 return Get(&outByte, 1);
528 if (AttachedTransformation())
529 return AttachedTransformation()->Get(outString, getMax);
533 return (
size_t)TransferTo(arraySink, getMax);
539 if (AttachedTransformation())
540 return AttachedTransformation()->Peek(outByte);
542 return Peek(&outByte, 1);
547 if (AttachedTransformation())
548 return AttachedTransformation()->Peek(outString, peekMax);
552 return (
size_t)CopyTo(arraySink, peekMax);
558 if (AttachedTransformation())
559 return AttachedTransformation()->Skip(skipMax);
566 if (AttachedTransformation())
567 return AttachedTransformation()->TotalBytesRetrievable();
569 return MaxRetrievable();
574 if (AttachedTransformation())
575 return AttachedTransformation()->NumberOfMessages();
582 if (AttachedTransformation())
583 return AttachedTransformation()->AnyMessages();
585 return NumberOfMessages() != 0;
590 if (AttachedTransformation())
591 return AttachedTransformation()->GetNextMessage();
594 assert(!AnyMessages());
601 if (AttachedTransformation())
602 return AttachedTransformation()->SkipMessages(count);
609 if (AttachedTransformation())
610 return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
613 unsigned int maxMessages = messageCount;
614 for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
617 lword transferredBytes;
619 while (AnyRetrievable())
621 transferredBytes = LWORD_MAX;
622 blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
623 if (blockedBytes > 0)
630 bool result = GetNextMessage();
631 CRYPTOPP_UNUSED(result); assert(result);
639 if (AttachedTransformation())
640 return AttachedTransformation()->CopyMessagesTo(target, count, channel);
645 void BufferedTransformation::SkipAll()
647 if (AttachedTransformation())
648 AttachedTransformation()->SkipAll();
651 while (SkipMessages()) {}
658 if (AttachedTransformation())
659 return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
662 assert(!NumberOfMessageSeries());
664 unsigned int messageCount;
667 messageCount = UINT_MAX;
668 size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
672 while (messageCount != 0);
677 byteCount = ULONG_MAX;
678 size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
682 while (byteCount != 0);
690 if (AttachedTransformation())
691 AttachedTransformation()->CopyAllTo(target, channel);
694 assert(!NumberOfMessageSeries());
695 while (CopyMessagesTo(target, UINT_MAX, channel)) {}
701 if (AttachedTransformation())
702 AttachedTransformation()->SetRetrievalChannel(channel);
707 PutWord(
false, order, m_buf, value);
708 return ChannelPut(channel, m_buf, 2, blocking);
713 PutWord(
false, order, m_buf, value);
714 return ChannelPut(channel, m_buf, 4, blocking);
719 return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
724 return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
729 byte buf[2] = {0, 0};
730 size_t len = Peek(buf, 2);
733 value = (buf[0] << 8) | buf[1];
735 value = (buf[1] << 8) | buf[0];
742 byte buf[4] = {0, 0, 0, 0};
743 size_t len = Peek(buf, 4);
746 value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
748 value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
755 return (
size_t)Skip(PeekWord16(value, order));
760 return (
size_t)Skip(PeekWord32(value, order));
765 if (AttachedTransformation() && AttachedTransformation()->Attachable())
766 AttachedTransformation()->Attach(newOut);
780 : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
785 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
788 m_plaintextQueue.Put(inString, length);
793 size_t plaintextLength;
794 if (!
SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
795 throw InvalidArgument(
"PK_DefaultEncryptionFilter: plaintext too long");
796 size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
799 m_plaintextQueue.Get(plaintext, plaintextLength);
800 m_ciphertext.resize(ciphertextLength);
801 m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
804 FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
806 FILTER_END_NO_MESSAGE_END;
825 : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
830 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
833 m_ciphertextQueue.Put(inString, length);
838 size_t ciphertextLength;
839 if (!
SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
840 throw InvalidArgument(
"PK_DefaultDecryptionFilter: ciphertext too long");
841 size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
844 m_ciphertextQueue.Get(ciphertext, ciphertextLength);
845 m_plaintext.resize(maxPlaintextLength);
846 m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
847 if (!m_result.isValidCoding)
851 FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
853 FILTER_END_NO_MESSAGE_END;
872 return SignAndRestart(rng, *m, signature,
false);
878 m->
Update(message, messageLen);
879 return SignAndRestart(rng, *m, signature,
false);
883 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength, byte *signature)
const 886 InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
887 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
888 return SignAndRestart(rng, *m, signature,
false);
894 return VerifyAndRestart(*m);
900 InputSignature(*m, signature, signatureLength);
901 m->
Update(message, messageLen);
902 return VerifyAndRestart(*m);
908 return RecoverAndRestart(recoveredMessage, *m);
912 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength,
913 const byte *signature,
size_t signatureLength)
const 916 InputSignature(*m, signature, signatureLength);
917 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
918 return RecoverAndRestart(recoveredMessage, *m);
923 GeneratePrivateKey(rng, privateKey);
924 GeneratePublicKey(rng, privateKey, publicKey);
929 GenerateStaticPrivateKey(rng, privateKey);
930 GenerateStaticPublicKey(rng, privateKey, publicKey);
935 GenerateEphemeralPrivateKey(rng, privateKey);
936 GenerateEphemeralPublicKey(rng, privateKey, publicKey);
used to pass byte array input as part of a NameValuePairs object
Standard names for retrieving values by name when working with NameValuePairs.
const char * DigestSize()
int, in bytes
An invalid argument was detected.
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
generate private/public key pair
container of wait objects
Classes for working with NameValuePairs.
word32 GenerateWord32(word32 min, word32 max)
An implementation that throws NotImplemented.
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
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters=g_nullNameValuePairs) const
create a new decryption filter
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from → to is safe to perform.
Utility functions for the Crypto++ library.
virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms=g_nullNameValuePairs)
Sets or reset the key of this object.
ByteOrder
Provides the byte ordering.
virtual void GenerateBlock(byte *output, size_t size)
Generate random array of bytes.
Exception thrown when an invalid key length is encountered.
Interface for public-key encryptors.
byte GenerateByte()
An implementation that throws NotImplemented.
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL)
Generate a random 32 bit word in the range min to max, inclusive.
Abstract base classes that provide a uniform interface to this library.
Thrown when an unexpected type is encountered.
BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
size_type size() const
Provides the count of elements in the SecBlock.
void GenerateBlock(byte *output, size_t size)
An implementation that throws NotImplemented.
virtual void DiscardBytes(size_t n)
Generate and discard n bytes.
The self tests were executed via DoPowerUpSelfTest() or DoDllPowerUpSelfTest(), but the result was fa...
Classes for automatic resource management.
void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
An implementation that throws NotImplemented.
Library configuration file.
Interface for random number generators.
void SetKeyWithRounds(const byte *key, size_t length, int rounds)
Sets or reset the key of this object.
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
recover a message from its signature
SecByteBlock is a SecBlock<byte> typedef.
Interface for cloning objects.
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Classes and functions for secure memory allocations.
bool FIPS_140_2_ComplianceEnabled()
Determines whether the library provides FIPS validated cryptography.
Copy input to a memory buffer.
Returns a decoding results.
Algorithm(bool checkSelfTestStatus=true)
Interface for all crypto algorithms.
bool GetValue(const char *name, T &value) const
Get a named value.
Interface for public-key decryptors.
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters=g_nullNameValuePairs) const
Create a new encryption filter.
void Shuffle(IT begin, IT end)
An implementation that does nothing.
A method was called which was not implemented.
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
generate private/public key pair
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Manages resources for a single object.
Exception thrown when a crypto algorithm is used after a self test fails.
virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
generate private/public key pair
#define CRYPTOPP_COMPILE_ASSERT(expr)
Compile time assertion.
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
virtual DecodingResult RecoverMessage(byte *recoveredMessage, const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, const byte *signature, size_t signatureLength) const
recover a message from its signature
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
unsigned int GenerateBit()
An implementation that throws NotImplemented.
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
sign and delete messageAccumulator (even in case of exception thrown)
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
sign a message
RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
virtual byte GenerateByte()
Generate new random byte and return it.
std::string AlgorithmName() const
The name of the generator.
const char * BlockSize()
int, in bytes
virtual bool VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLength) const
check whether input signature is a valid signature for input message
PowerUpSelfTestStatus GetPowerUpSelfTestStatus()
Provides the current power-up self test status.
Random Number Generator that does not produce random numbers.
Implementation of BufferedTransformation's attachment interface in cryptlib.h.
const char * IV()
ConstByteArrayParameter, also accepts const byte * for backwards compatibility.
The self tests have not been performed.
Interface for accumulating messages to be signed or verified.
A decryption filter encountered invalid ciphertext.
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const
check whether messageAccumulator contains a valid signature and message, and delete messageAccumulato...
void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
Sets or reset the key of this object.
virtual unsigned int GenerateBit()
Generate new random bit and return it.
Base class for unflushable filters.
Classes and functions for the FIPS 140-2 validated library.
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)
encrypt and generate MAC in one call. will truncate MAC if macSize < TagSize()
void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
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)
decrypt and verify MAC in one call, returning true iff MAC is valid. will assume MAC is truncated if ...
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
Generate a random key or crypto parameters.
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
bool VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
this function only needs to be called if NeedsPrespecifiedDataLengths() returns true ...
Acts as an input discarding Filter or Sink.
Crypto++ library namespace.
void IncorporateEntropy(const byte *input, size_t length)
An implementation that throws NotImplemented.
const std::string AAD_CHANNEL
Channel for additional authenticated data.
void DiscardBytes(size_t n)
An implementation that does nothing.
virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv)
Gets a secure IV for the next message.
unsigned int BitPrecision(const T &value)
Returns the number of bits required for a value.
virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
Generate random bytes into a BufferedTransformation.
Classes for access to the operating system's random number generators.
bool CanIncorporateEntropy() const
An implementation that returns false.
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Interface for retrieving values given their names.
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.