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 32 #if (defined(__CYGWIN__) || defined(__CYGWIN32__)) && defined(PREFER_WINDOWS_STYLE_SOCKETS) 33 # error Cygwin does not support Windows style sockets. See http://www.cygwin.com/faq.html#faq.api.winsock 42 #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE 57 throw SelfTestFailure(
"Cryptographic algorithms are disabled before the power-up self tests are performed.");
60 throw SelfTestFailure(
"Cryptographic algorithms are disabled after a power-up self test failed.");
66 this->ThrowIfInvalidKeyLength(length);
67 this->UncheckedSetKey(key, static_cast<unsigned int>(length), params);
80 void SimpleKeyingInterface::ThrowIfInvalidKeyLength(
size_t length)
82 if (!IsValidKeyLength(length))
86 void SimpleKeyingInterface::ThrowIfResynchronizable()
88 if (IsResynchronizable())
92 void SimpleKeyingInterface::ThrowIfInvalidIV(
const byte *iv)
94 if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
98 size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(
int length)
102 size =
static_cast<size_t>(IVSize());
103 else if ((
size_t)length < MinIVLength())
105 else if ((
size_t)length > MaxIVLength())
108 size =
static_cast<size_t>(length);
113 const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(
const NameValuePairs ¶ms,
size_t &size)
116 const byte *iv = NULLPTR;
124 iv = ivWithLength.
begin();
125 ThrowIfInvalidIV(iv);
126 size = ThrowIfInvalidIVLength(static_cast<int>(ivWithLength.
size()));
130 ThrowIfInvalidIV(iv);
131 size =
static_cast<size_t>(IVSize());
135 ThrowIfResynchronizable();
154 ptrdiff_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize;
155 ptrdiff_t xorIncrement = xorBlocks ? blockSize : 0;
156 ptrdiff_t outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : blockSize;
158 if (flags & BT_ReverseDirection)
160 inBlocks +=
static_cast<ptrdiff_t
>(length) - blockSize;
161 xorBlocks +=
static_cast<ptrdiff_t
>(length) - blockSize;
162 outBlocks +=
static_cast<ptrdiff_t
>(length) - blockSize;
163 inIncrement = 0-inIncrement;
164 xorIncrement = 0-xorIncrement;
165 outIncrement = 0-outIncrement;
169 const bool xorFlag = xorBlocks && (flags & BT_XorInput);
170 while (length >= blockSize)
175 xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
176 ProcessBlock(outBlocks);
181 ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
184 if (flags & BT_InBlockIsCounter)
185 const_cast<byte *
>(inBlocks)[blockSize-1]++;
187 inBlocks += inIncrement;
188 outBlocks += outIncrement;
189 xorBlocks += xorIncrement;
198 return GetAlignmentOf<word32>();
203 return GetAlignmentOf<word32>();
208 return GetAlignmentOf<word32>();
216 if (length == MandatoryBlockSize())
217 ProcessData(outString, inString, length);
218 else if (length != 0)
228 if (inLength == MandatoryBlockSize())
230 outLength = inLength;
231 ProcessData(outString, inString, inLength);
233 else if (inLength != 0)
241 if (headerLength > MaxHeaderLength())
244 if (messageLength > MaxMessageLength())
247 if (footerLength > MaxFooterLength())
250 UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
255 Resynchronize(iv, ivLength);
256 SpecifyDataLengths(headerLength, messageLength);
257 Update(header, headerLength);
258 ProcessString(ciphertext, message, messageLength);
259 TruncatedFinal(mac, macSize);
264 Resynchronize(iv, ivLength);
265 SpecifyDataLengths(headerLength, ciphertextLength);
266 Update(header, headerLength);
267 ProcessString(message, ciphertext, ciphertextLength);
268 return TruncatedVerify(mac, macLength);
279 return GenerateByte() & 1;
285 GenerateBlock(&b, 1);
291 const word32 range = max-min;
298 GenerateBlock((byte *)&value,
sizeof(value));
299 value =
Crop(value, maxBits);
300 }
while (value > range);
319 CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
336 GenerateBlock(buffer, len);
337 (void)target.
ChannelPut(channel, buffer, len);
349 return static_cast<size_t>(-1);
352 void KeyDerivationFunction::ThrowIfInvalidDerivedLength(
size_t length)
const 354 if (!IsValidDerivedLength(length))
359 CRYPTOPP_UNUSED(params);
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) 414 ThrowIfInvalidTruncatedSize(digestLength);
416 TruncatedFinal(calculated, digestLength);
420 void HashTransformation::ThrowIfInvalidTruncatedSize(
size_t size)
const 441 CRYPTOPP_UNUSED(propagation);
443 IsolatedInitialize(parameters);
448 CRYPTOPP_UNUSED(propagation);
450 return IsolatedFlush(hardFlush, blocking);
455 CRYPTOPP_UNUSED(propagation);
457 return IsolatedMessageSeriesEnd(blocking);
462 byte* space = NULLPTR;
464 space = CreatePutSpace(size);
474 size = Put2(inString, length, messageEnd, blocking);
484 size = PutModifiable2(inString, length, messageEnd, blocking);
486 size = ChannelPut2(channel, inString, length, messageEnd, blocking);
494 result = Flush(hardFlush, propagation, blocking);
504 result = MessageSeriesEnd(propagation, blocking);
513 if (AttachedTransformation())
514 size = AttachedTransformation()->MaxRetrievable();
523 if (AttachedTransformation())
524 result = AttachedTransformation()->AnyRetrievable();
528 result = Peek(b) != 0;
536 if (AttachedTransformation())
537 size = AttachedTransformation()->Get(outByte);
539 size = Get(&outByte, 1);
546 if (AttachedTransformation())
547 size = AttachedTransformation()->Get(outString, getMax);
551 size = (size_t)TransferTo(arraySink, getMax);
559 if (AttachedTransformation())
560 size = AttachedTransformation()->Peek(outByte);
562 size = Peek(&outByte, 1);
569 if (AttachedTransformation())
570 size = AttachedTransformation()->Peek(outString, peekMax);
574 size = (size_t)CopyTo(arraySink, peekMax);
582 if (AttachedTransformation())
583 size = AttachedTransformation()->Skip(skipMax);
592 if (AttachedTransformation())
593 size = AttachedTransformation()->TotalBytesRetrievable();
595 size = MaxRetrievable();
601 unsigned int size = 0;
602 if (AttachedTransformation())
603 size = AttachedTransformation()->NumberOfMessages();
612 if (AttachedTransformation())
613 result = AttachedTransformation()->AnyMessages();
615 result = NumberOfMessages() != 0;
622 if (AttachedTransformation())
623 result = AttachedTransformation()->GetNextMessage();
633 unsigned int size = 0;
634 if (AttachedTransformation())
635 size = AttachedTransformation()->SkipMessages(count);
643 if (AttachedTransformation())
644 return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
647 unsigned int maxMessages = messageCount;
648 for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
651 lword transferredBytes;
653 while (AnyRetrievable())
655 transferredBytes = LWORD_MAX;
656 blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
657 if (blockedBytes > 0)
664 bool result = GetNextMessage();
673 unsigned int size = 0;
674 if (AttachedTransformation())
675 size = AttachedTransformation()->CopyMessagesTo(target, count, channel);
681 if (AttachedTransformation())
682 AttachedTransformation()->SkipAll();
685 while (SkipMessages()) {}
692 if (AttachedTransformation())
693 return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
698 unsigned int messageCount;
701 messageCount = UINT_MAX;
702 size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
706 while (messageCount != 0);
711 byteCount = ULONG_MAX;
712 size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
716 while (byteCount != 0);
724 if (AttachedTransformation())
725 AttachedTransformation()->CopyAllTo(target, channel);
729 while (CopyMessagesTo(target, UINT_MAX, channel)) {}
735 if (AttachedTransformation())
736 AttachedTransformation()->SetRetrievalChannel(channel);
741 PutWord(
false, order, m_buf, value);
742 return ChannelPut(channel, m_buf, 2, blocking);
747 PutWord(
false, order, m_buf, value);
748 return ChannelPut(channel, m_buf, 4, blocking);
762 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 763 # pragma GCC diagnostic push 764 # pragma GCC diagnostic ignored "-Wconversion" 765 # pragma GCC diagnostic ignored "-Wsign-conversion" 770 byte buf[2] = {0, 0};
771 size_t len = Peek(buf, 2);
774 value = (buf[0] << 8) | buf[1];
776 value = (buf[1] << 8) | buf[0];
783 byte buf[4] = {0, 0, 0, 0};
784 size_t len = Peek(buf, 4);
787 value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
789 value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
795 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 796 # pragma GCC diagnostic pop 801 return (
size_t)Skip(PeekWord16(value, order));
806 return (
size_t)Skip(PeekWord32(value, order));
811 if (AttachedTransformation() && AttachedTransformation()->Attachable())
812 AttachedTransformation()->Attach(newAttachment);
814 Detach(newAttachment);
826 : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
831 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
834 m_plaintextQueue.Put(inString, length);
839 size_t plaintextLength;
840 if (!
SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
841 throw InvalidArgument(
"PK_DefaultEncryptionFilter: plaintext too long");
842 size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
845 m_plaintextQueue.Get(plaintext, plaintextLength);
846 m_ciphertext.resize(ciphertextLength);
847 m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
850 FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
852 FILTER_END_NO_MESSAGE_END;
871 : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
876 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
879 m_ciphertextQueue.Put(inString, length);
884 size_t ciphertextLength;
885 if (!
SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
886 throw InvalidArgument(
"PK_DefaultDecryptionFilter: ciphertext too long");
887 size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
890 m_ciphertextQueue.Get(ciphertext, ciphertextLength);
891 m_plaintext.resize(maxPlaintextLength);
892 m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
893 if (!m_result.isValidCoding)
897 FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
899 FILTER_END_NO_MESSAGE_END;
918 return SignAndRestart(rng, *m, signature,
false);
924 m->
Update(message, messageLen);
925 return SignAndRestart(rng, *m, signature,
false);
929 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength, byte *signature)
const 932 InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
933 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
934 return SignAndRestart(rng, *m, signature,
false);
940 return VerifyAndRestart(*m);
946 InputSignature(*m, signature, signatureLen);
947 m->
Update(message, messageLen);
948 return VerifyAndRestart(*m);
954 return RecoverAndRestart(recoveredMessage, *m);
958 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength,
959 const byte *signature,
size_t signatureLength)
const 962 InputSignature(*m, signature, signatureLength);
963 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
964 return RecoverAndRestart(recoveredMessage, *m);
969 GeneratePrivateKey(rng, privateKey);
970 GeneratePublicKey(rng, privateKey, publicKey);
975 GenerateStaticPrivateKey(rng, privateKey);
976 GenerateStaticPublicKey(rng, privateKey, publicKey);
981 GenerateEphemeralPrivateKey(rng, privateKey);
982 GenerateEphemeralPublicKey(rng, privateKey, publicKey);
987 #ifndef CRYPTOPP_BUILD_VERSION 988 # define CRYPTOPP_BUILD_VERSION CRYPTOPP_VERSION 992 return CRYPTOPP_BUILD_VERSION;
997 #endif // CRYPTOPP_IMPORTS 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 SetParameters(const NameValuePairs ¶ms)
Set or change parameters.
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
container of wait objects
Classes for working with NameValuePairs.
word32 GenerateWord32(word32 min, word32 max)
An implementation that throws NotImplemented.
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.
size_t size() const
Length of the memory block.
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const
Check whether messageAccumulator contains a valid signature and message.
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
Sign a message.
Exception thrown when an invalid key length is encountered.
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a static private/public key pair.
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.
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.
virtual Clonable * Clone() const
Copies this object.
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 void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate private/public key pair.
Interface for cloning objects.
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.
std::string AlgorithmName() const
The name of the generator.
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.
Interface for public-key decryptors.
void Shuffle(IT begin, IT end)
An implementation that does nothing.
A method was called which was not implemented.
const byte * begin() const
Pointer to the first byte in the memory block.
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.
Exception thrown when a crypto algorithm is used after a self test fails.
virtual DecodingResult RecoverMessage(byte *recoveredMessage, const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, const byte *signature, size_t signatureLength) const
Recover a message from its signature.
#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 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.
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
unsigned int GenerateBit()
An implementation that throws NotImplemented.
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters=g_nullNameValuePairs) const
Create a new decryption filter.
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
virtual size_t MinDerivedLength() const
Determine minimum number of bytes.
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
virtual byte GenerateByte()
Generate new random byte and return it.
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.
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.
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
Sign and delete the messageAccumulator.
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters=g_nullNameValuePairs) const
Create a new encryption filter.
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.
virtual size_t MaxDerivedLength() const
Determine maximum number of bytes.
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.
Exception thrown when an invalid derived key length is encountered.
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prespecifies the data lengths.
Acts as an input discarding Filter or Sink.
int LibraryVersion(...)
Specifies the build-time version of the library.
Crypto++ library namespace.
bool GetValue(const char *name, T &value) const
Get a named value.
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
Recover a message from its signature.
bool CanIncorporateEntropy() const
An implementation that returns false.
void IncorporateEntropy(const byte *input, size_t length)
An implementation that throws NotImplemented.
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.
size_type size() const
Provides the count of elements in the SecBlock.
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.
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.