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 41 #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE 45 #if HAVE_GCC_INIT_PRIORITY 50 #elif HAVE_MSC_INIT_PRIORITY 51 #pragma warning(disable: 4073) 55 const std::string &BufferedTransformation::NULL_CHANNEL =
DEFAULT_CHANNEL;
56 #pragma warning(default: 4073) 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;
67 bool GetVoidValue(
const char *
name,
const std::type_info &valueType,
void *pValue)
const 71 #if HAVE_GCC_INIT_PRIORITY 90 throw SelfTestFailure(
"Cryptographic algorithms are disabled before the power-up self tests are performed.");
93 throw SelfTestFailure(
"Cryptographic algorithms are disabled after a power-up self test failed.");
99 this->ThrowIfInvalidKeyLength(length);
100 this->UncheckedSetKey(key, (
unsigned int)length, params);
115 if (!IsValidKeyLength(length))
121 if (IsResynchronizable())
122 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object requires an IV");
127 if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
128 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object cannot use a null IV");
134 return (
size_t)IVSize();
135 else if ((
size_t)size < MinIVLength())
137 else if ((
size_t)size > MaxIVLength())
149 try {found = params.
GetValue(Name::IV(), ivWithLength);}
154 iv = ivWithLength.
begin();
155 ThrowIfInvalidIV(iv);
156 size = ThrowIfInvalidIVLength((
int)ivWithLength.
size());
159 else if (params.
GetValue(Name::IV(), iv))
161 ThrowIfInvalidIV(iv);
167 ThrowIfResynchronizable();
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;
189 if (flags & BT_ReverseDirection)
192 inBlocks += length - blockSize;
193 xorBlocks += length - blockSize;
194 outBlocks += length - blockSize;
195 inIncrement = 0-inIncrement;
196 xorIncrement = 0-xorIncrement;
197 outIncrement = 0-outIncrement;
200 while (length >= blockSize)
202 if (flags & BT_XorInput)
206 #if defined(__COVERITY__) 209 xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
210 ProcessBlock(outBlocks);
215 ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
218 if (flags & BT_InBlockIsCounter)
219 const_cast<byte *
>(inBlocks)[blockSize-1]++;
220 inBlocks += inIncrement;
221 outBlocks += outIncrement;
222 xorBlocks += xorIncrement;
231 return GetAlignmentOf<word32>();
236 return GetAlignmentOf<word32>();
241 return GetAlignmentOf<word32>();
248 if (length == MandatoryBlockSize())
249 ProcessData(outString, inString, length);
250 else if (length != 0)
251 throw NotImplemented(AlgorithmName() +
": this object doesn't support a special last block");
256 if (headerLength > MaxHeaderLength())
259 if (messageLength > MaxMessageLength())
262 if (footerLength > MaxFooterLength())
265 UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
270 Resynchronize(iv, ivLength);
271 SpecifyDataLengths(headerLength, messageLength);
272 Update(header, headerLength);
273 ProcessString(ciphertext, message, messageLength);
274 TruncatedFinal(mac, macSize);
279 Resynchronize(iv, ivLength);
280 SpecifyDataLengths(headerLength, ciphertextLength);
281 Update(header, headerLength);
282 ProcessString(message, ciphertext, ciphertextLength);
283 return TruncatedVerify(mac, macLength);
288 return GenerateByte() & 1;
294 GenerateBlock(&b, 1);
300 const word32 range = max-
min;
307 GenerateBlock((byte *)&value,
sizeof(value));
308 value =
Crop(value, maxBits);
309 }
while (value > range);
332 throw NotImplemented(
"RandomNumberGenerator: GenerateBlock not implemented");
336 GenerateIntoBufferedTransformation(s, DEFAULT_CHANNEL, size);
341 GenerateIntoBufferedTransformation(
TheBitBucket(), DEFAULT_CHANNEL, n);
350 GenerateBlock(buffer, len);
351 size_t rem = target.
ChannelPut(channel, buffer, len);
369 #if defined(CRYPTOPP_DOXYGEN_PROCESSING) 370 byte GenerateByte () {}
373 unsigned int GenerateBit () {}
375 word32 GenerateWord32 (word32
min, word32
max) {}
382 throw NotImplemented(
"NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
385 #if defined(CRYPTOPP_DOXYGEN_PROCESSING) 389 void IncorporateEntropy (
const byte *input,
size_t length) {}
391 bool CanIncorporateEntropy ()
const {}
393 void DiscardBytes (
size_t n) {}
395 void Shuffle (IT begin, IT end) {}
398 Clonable* Clone ()
const {
return NULL; }
410 ThrowIfInvalidTruncatedSize(digestLength);
412 TruncatedFinal(digest, digestLength);
418 if (size > DigestSize())
439 IsolatedInitialize(parameters);
446 return IsolatedFlush(hardFlush, blocking);
453 return IsolatedMessageSeriesEnd(blocking);
459 return CreatePutSpace(size);
467 return Put2(begin, length, messageEnd, blocking);
475 return PutModifiable2(begin, length, messageEnd, blocking);
477 return ChannelPut2(channel, begin, length, messageEnd, blocking);
483 return Flush(completeFlush, propagation, blocking);
491 return MessageSeriesEnd(propagation, blocking);
498 if (AttachedTransformation())
499 return AttachedTransformation()->MaxRetrievable();
506 if (AttachedTransformation())
507 return AttachedTransformation()->AnyRetrievable();
517 if (AttachedTransformation())
518 return AttachedTransformation()->Get(outByte);
520 return Get(&outByte, 1);
525 if (AttachedTransformation())
526 return AttachedTransformation()->Get(outString, getMax);
530 return (
size_t)TransferTo(arraySink, getMax);
536 if (AttachedTransformation())
537 return AttachedTransformation()->Peek(outByte);
539 return Peek(&outByte, 1);
544 if (AttachedTransformation())
545 return AttachedTransformation()->Peek(outString, peekMax);
549 return (
size_t)CopyTo(arraySink, peekMax);
555 if (AttachedTransformation())
556 return AttachedTransformation()->Skip(skipMax);
563 if (AttachedTransformation())
564 return AttachedTransformation()->TotalBytesRetrievable();
566 return MaxRetrievable();
571 if (AttachedTransformation())
572 return AttachedTransformation()->NumberOfMessages();
579 if (AttachedTransformation())
580 return AttachedTransformation()->AnyMessages();
582 return NumberOfMessages() != 0;
587 if (AttachedTransformation())
588 return AttachedTransformation()->GetNextMessage();
598 if (AttachedTransformation())
599 return AttachedTransformation()->SkipMessages(count);
606 if (AttachedTransformation())
607 return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
610 unsigned int maxMessages = messageCount;
611 for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
614 lword transferredBytes;
616 while (AnyRetrievable())
619 blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
620 if (blockedBytes > 0)
627 bool result = GetNextMessage();
636 if (AttachedTransformation())
637 return AttachedTransformation()->CopyMessagesTo(target, count, channel);
644 if (AttachedTransformation())
645 AttachedTransformation()->SkipAll();
648 while (SkipMessages()) {}
655 if (AttachedTransformation())
656 return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
661 unsigned int messageCount;
664 messageCount = UINT_MAX;
665 size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
669 while (messageCount != 0);
674 byteCount = ULONG_MAX;
675 size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
679 while (byteCount != 0);
687 if (AttachedTransformation())
688 AttachedTransformation()->CopyAllTo(target, channel);
692 while (CopyMessagesTo(target, UINT_MAX, channel)) {}
698 if (AttachedTransformation())
699 AttachedTransformation()->SetRetrievalChannel(channel);
704 PutWord(
false, order, m_buf, value);
705 return ChannelPut(channel, m_buf, 2, blocking);
710 PutWord(
false, order, m_buf, value);
711 return ChannelPut(channel, m_buf, 4, blocking);
716 return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
721 return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
725 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 726 # pragma GCC diagnostic push 727 # pragma GCC diagnostic ignored "-Wconversion" 728 # pragma GCC diagnostic ignored "-Wsign-conversion" 733 byte buf[2] = {0, 0};
734 size_t len = Peek(buf, 2);
737 value = (buf[0] << 8) | buf[1];
739 value = (buf[1] << 8) | buf[0];
746 byte buf[4] = {0, 0, 0, 0};
747 size_t len = Peek(buf, 4);
750 value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
752 value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
758 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 759 # pragma GCC diagnostic pop 764 return (
size_t)Skip(PeekWord16(value, order));
769 return (
size_t)Skip(PeekWord32(value, order));
774 if (AttachedTransformation() && AttachedTransformation()->Attachable())
775 AttachedTransformation()->Attach(newOut);
789 : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
794 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
797 m_plaintextQueue.Put(inString, length);
802 size_t plaintextLength;
803 if (!
SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
804 throw InvalidArgument(
"PK_DefaultEncryptionFilter: plaintext too long");
805 size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
808 m_plaintextQueue.Get(plaintext, plaintextLength);
809 m_ciphertext.resize(ciphertextLength);
810 m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
813 FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
834 : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
839 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
842 m_ciphertextQueue.Put(inString, length);
847 size_t ciphertextLength;
848 if (!
SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
849 throw InvalidArgument(
"PK_DefaultDecryptionFilter: ciphertext too long");
850 size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
853 m_ciphertextQueue.Get(ciphertext, ciphertextLength);
854 m_plaintext.resize(maxPlaintextLength);
855 m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
881 return SignAndRestart(rng, *m, signature,
false);
887 m->
Update(message, messageLen);
888 return SignAndRestart(rng, *m, signature,
false);
892 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength, byte *signature)
const 895 InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
896 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
897 return SignAndRestart(rng, *m, signature,
false);
903 return VerifyAndRestart(*m);
909 InputSignature(*m, signature, signatureLength);
910 m->
Update(message, messageLen);
911 return VerifyAndRestart(*m);
917 return RecoverAndRestart(recoveredMessage, *m);
921 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength,
922 const byte *signature,
size_t signatureLength)
const 925 InputSignature(*m, signature, signatureLength);
926 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
927 return RecoverAndRestart(recoveredMessage, *m);
932 GeneratePrivateKey(rng, privateKey);
933 GeneratePublicKey(rng, privateKey, publicKey);
938 GenerateStaticPrivateKey(rng, privateKey);
939 GenerateStaticPublicKey(rng, privateKey, publicKey);
944 GenerateEphemeralPrivateKey(rng, privateKey);
945 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.
An invalid argument was detected.
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate private/public key pair.
#define FILTER_END_NO_MESSAGE_END
Classes for working with NameValuePairs.
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.
const byte * GetIVAndThrowIfInvalid(const NameValuePairs ¶ms, size_t &size)
Retrieves and validates the IV.
RandomNumberGenerator & m_rng
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.
#define CRYPTOPP_INIT_PRIORITY
Exception thrown when an invalid key length is encountered.
static const std::string s2("AAD")
const NameValuePairs & m_parameters
void ThrowIfInvalidKeyLength(size_t length)
Validates the key length.
void ThrowIfInvalidIV(const byte *iv)
Validates the IV.
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
#define FILTER_OUTPUT(site, output, length, messageEnd)
#define NAMESPACE_BEGIN(x)
bool FIPS_140_2_ComplianceEnabled()
Determines whether the library provides FIPS validated cryptography.
PK_DefaultDecryptionFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment, const NameValuePairs ¶meters)
Interface for public-key encryptors.
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL)
Generate a random 32 bit word in the range min to max, inclusive.
PowerUpSelfTestStatus CRYPTOPP_API GetPowerUpSelfTestStatus()
Provides the current power-up self test status.
Abstract base classes that provide a uniform interface to this library.
Thrown when an unexpected type is encountered.
SecByteBlock m_ciphertext
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.
Library configuration file.
Interface for random number generators.
const NameValuePairs & m_parameters
ByteQueue m_ciphertextQueue
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.
RandomNumberGenerator & m_rng
BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
size_t ThrowIfInvalidIVLength(int length)
Validates the IV length.
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Classes and functions for secure memory allocations.
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.
A method was called which was not implemented.
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
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.
FascTransaction __attribute__
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
void ThrowIfResynchronizable()
Validates the object.
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 std::string AAD_CHANNEL
Channel for additional authenticated data.
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
unsigned long long word64
PK_DefaultEncryptionFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment, const NameValuePairs ¶meters)
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.
const PK_Decryptor & m_decryptor
#define CRYPTOPP_ASSERT(exp)
virtual byte GenerateByte()
Generate new random byte and return it.
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
std::string AlgorithmName() const
The name of the generator.
void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
Data structure used to store byte strings.
Random Number Generator that does not produce random numbers.
Implementation of BufferedTransformation's attachment interface.
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.
uint8_t const size_t const size
#define CRYPTOPP_UNUSED(x)
RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
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.
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.
std::vector< char * > parameters
bool PowerUpSelfTestInProgressOnThisThread()
CRYPTOPP_COMPILE_ASSERT(sizeof(byte)==1)
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prespecifies the data lengths.
Acts as an input discarding Filter or Sink.
ByteQueue m_plaintextQueue
const simple_ptr< NullNameValuePairs > s_pNullNameValuePairs(new NullNameValuePairs)
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.
const PK_Encryptor & m_encryptor
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 GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
bool VerifyBufsEqual(const byte *buf, const byte *mask, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
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.