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) 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;
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;}
75 #if HAVE_GCC_INIT_PRIORITY 94 throw SelfTestFailure(
"Cryptographic algorithms are disabled before the power-up self tests are performed.");
97 throw SelfTestFailure(
"Cryptographic algorithms are disabled after a power-up self test failed.");
103 this->ThrowIfInvalidKeyLength(length);
104 this->UncheckedSetKey(key, (
unsigned int)length, params);
117 void SimpleKeyingInterface::ThrowIfInvalidKeyLength(
size_t length)
119 if (!IsValidKeyLength(length))
123 void SimpleKeyingInterface::ThrowIfResynchronizable()
125 if (IsResynchronizable())
126 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object requires an IV");
129 void SimpleKeyingInterface::ThrowIfInvalidIV(
const byte *iv)
131 if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
132 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object cannot use a null IV");
135 size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(
int size)
139 else if ((
size_t)size < MinIVLength())
141 else if ((
size_t)size > MaxIVLength())
147 const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(
const NameValuePairs ¶ms,
size_t &size)
158 iv = ivWithLength.
begin();
159 ThrowIfInvalidIV(iv);
160 size = ThrowIfInvalidIVLength((
int)ivWithLength.
size());
165 ThrowIfInvalidIV(iv);
171 ThrowIfResynchronizable();
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;
193 if (flags & BT_ReverseDirection)
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;
204 while (length >= blockSize)
206 if (flags & BT_XorInput)
210 #if defined(__COVERITY__) 213 xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
214 ProcessBlock(outBlocks);
219 ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
222 if (flags & BT_InBlockIsCounter)
223 const_cast<byte *
>(inBlocks)[blockSize-1]++;
224 inBlocks += inIncrement;
225 outBlocks += outIncrement;
226 xorBlocks += xorIncrement;
235 return GetAlignmentOf<word32>();
240 return GetAlignmentOf<word32>();
245 return GetAlignmentOf<word32>();
250 assert(MinLastBlockSize() == 0);
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");
260 if (headerLength > MaxHeaderLength())
263 if (messageLength > MaxMessageLength())
266 if (footerLength > MaxFooterLength())
269 UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
274 Resynchronize(iv, ivLength);
275 SpecifyDataLengths(headerLength, messageLength);
276 Update(header, headerLength);
277 ProcessString(ciphertext, message, messageLength);
278 TruncatedFinal(mac, macSize);
283 Resynchronize(iv, ivLength);
284 SpecifyDataLengths(headerLength, ciphertextLength);
285 Update(header, headerLength);
286 ProcessString(message, ciphertext, ciphertextLength);
287 return TruncatedVerify(mac, macLength);
292 return GenerateByte() & 1;
298 GenerateBlock(&b, 1);
304 const word32 range = max-min;
311 GenerateBlock((byte *)&value,
sizeof(value));
312 value =
Crop(value, maxBits);
313 }
while (value > range);
332 CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
336 throw NotImplemented(
"RandomNumberGenerator: GenerateBlock not implemented");
340 GenerateIntoBufferedTransformation(s, DEFAULT_CHANNEL, size);
345 GenerateIntoBufferedTransformation(
TheBitBucket(), DEFAULT_CHANNEL, n);
354 GenerateBlock(buffer, len);
355 size_t rem = target.
ChannelPut(channel, buffer, len);
356 CRYPTOPP_UNUSED(rem); assert(rem == 0);
373 #if defined(CRYPTOPP_DOXYGEN_PROCESSING) 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");
389 #if defined(CRYPTOPP_DOXYGEN_PROCESSING) 402 Clonable* Clone ()
const {
return NULL; }
414 ThrowIfInvalidTruncatedSize(digestLength);
416 TruncatedFinal(digest, digestLength);
420 void HashTransformation::ThrowIfInvalidTruncatedSize(
size_t size)
const 441 CRYPTOPP_UNUSED(propagation);
442 assert(!AttachedTransformation());
443 IsolatedInitialize(parameters);
448 CRYPTOPP_UNUSED(propagation);
449 assert(!AttachedTransformation());
450 return IsolatedFlush(hardFlush, blocking);
455 CRYPTOPP_UNUSED(propagation);
456 assert(!AttachedTransformation());
457 return IsolatedMessageSeriesEnd(blocking);
463 return CreatePutSpace(size);
471 return Put2(begin, length, messageEnd, blocking);
479 return PutModifiable2(begin, length, messageEnd, blocking);
481 return ChannelPut2(channel, begin, length, messageEnd, blocking);
487 return Flush(completeFlush, propagation, blocking);
495 return MessageSeriesEnd(propagation, blocking);
502 if (AttachedTransformation())
503 return AttachedTransformation()->MaxRetrievable();
510 if (AttachedTransformation())
511 return AttachedTransformation()->AnyRetrievable();
521 if (AttachedTransformation())
522 return AttachedTransformation()->Get(outByte);
524 return Get(&outByte, 1);
529 if (AttachedTransformation())
530 return AttachedTransformation()->Get(outString, getMax);
534 return (
size_t)TransferTo(arraySink, getMax);
540 if (AttachedTransformation())
541 return AttachedTransformation()->Peek(outByte);
543 return Peek(&outByte, 1);
548 if (AttachedTransformation())
549 return AttachedTransformation()->Peek(outString, peekMax);
553 return (
size_t)CopyTo(arraySink, peekMax);
559 if (AttachedTransformation())
560 return AttachedTransformation()->Skip(skipMax);
567 if (AttachedTransformation())
568 return AttachedTransformation()->TotalBytesRetrievable();
570 return MaxRetrievable();
575 if (AttachedTransformation())
576 return AttachedTransformation()->NumberOfMessages();
583 if (AttachedTransformation())
584 return AttachedTransformation()->AnyMessages();
586 return NumberOfMessages() != 0;
591 if (AttachedTransformation())
592 return AttachedTransformation()->GetNextMessage();
595 assert(!AnyMessages());
602 if (AttachedTransformation())
603 return AttachedTransformation()->SkipMessages(count);
610 if (AttachedTransformation())
611 return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
614 unsigned int maxMessages = messageCount;
615 for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
618 lword transferredBytes;
620 while (AnyRetrievable())
622 transferredBytes = LWORD_MAX;
623 blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
624 if (blockedBytes > 0)
631 bool result = GetNextMessage();
632 CRYPTOPP_UNUSED(result); assert(result);
640 if (AttachedTransformation())
641 return AttachedTransformation()->CopyMessagesTo(target, count, channel);
648 if (AttachedTransformation())
649 AttachedTransformation()->SkipAll();
652 while (SkipMessages()) {}
659 if (AttachedTransformation())
660 return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
663 assert(!NumberOfMessageSeries());
665 unsigned int messageCount;
668 messageCount = UINT_MAX;
669 size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
673 while (messageCount != 0);
678 byteCount = ULONG_MAX;
679 size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
683 while (byteCount != 0);
691 if (AttachedTransformation())
692 AttachedTransformation()->CopyAllTo(target, channel);
695 assert(!NumberOfMessageSeries());
696 while (CopyMessagesTo(target, UINT_MAX, channel)) {}
702 if (AttachedTransformation())
703 AttachedTransformation()->SetRetrievalChannel(channel);
708 PutWord(
false, order, m_buf, value);
709 return ChannelPut(channel, m_buf, 2, blocking);
714 PutWord(
false, order, m_buf, value);
715 return ChannelPut(channel, m_buf, 4, blocking);
720 return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
725 return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
730 byte buf[2] = {0, 0};
731 size_t len = Peek(buf, 2);
734 value = (buf[0] << 8) | buf[1];
736 value = (buf[1] << 8) | buf[0];
743 byte buf[4] = {0, 0, 0, 0};
744 size_t len = Peek(buf, 4);
747 value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
749 value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
756 return (
size_t)Skip(PeekWord16(value, order));
761 return (
size_t)Skip(PeekWord32(value, order));
766 if (AttachedTransformation() && AttachedTransformation()->Attachable())
767 AttachedTransformation()->Attach(newOut);
781 : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
786 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
789 m_plaintextQueue.Put(inString, length);
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);
800 m_plaintextQueue.Get(plaintext, plaintextLength);
801 m_ciphertext.resize(ciphertextLength);
802 m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
805 FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
807 FILTER_END_NO_MESSAGE_END;
826 : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
831 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
834 m_ciphertextQueue.Put(inString, length);
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);
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)
852 FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
854 FILTER_END_NO_MESSAGE_END;
873 return SignAndRestart(rng, *m, signature,
false);
879 m->
Update(message, messageLen);
880 return SignAndRestart(rng, *m, signature,
false);
884 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength, byte *signature)
const 887 InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
888 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
889 return SignAndRestart(rng, *m, signature,
false);
895 return VerifyAndRestart(*m);
901 InputSignature(*m, signature, signatureLength);
902 m->
Update(message, messageLen);
903 return VerifyAndRestart(*m);
909 return RecoverAndRestart(recoveredMessage, *m);
913 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength,
914 const byte *signature,
size_t signatureLength)
const 917 InputSignature(*m, signature, signatureLength);
918 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
919 return RecoverAndRestart(recoveredMessage, *m);
924 GeneratePrivateKey(rng, privateKey);
925 GeneratePublicKey(rng, privateKey, publicKey);
930 GenerateStaticPrivateKey(rng, privateKey);
931 GenerateStaticPublicKey(rng, privateKey, publicKey);
936 GenerateEphemeralPrivateKey(rng, privateKey);
937 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 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.
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.
size_t size() const
Length of the memory block.
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.
const byte * begin() const
Pointer to the first byte in the memory block.
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 a 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 a static 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 the messageAccumulator.
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.
Data structure used to store byte strings.
const char * BlockSize()
int, in bytes
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.
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.
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)
Encrypts and calculates a MAC in one call.
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)
Decrypts and verifies a MAC in one call.
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)
Prespecifies the data lengths.
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)
Retrieves 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.