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
35 NAMESPACE_BEGIN(CryptoPP)
41 #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
45 #if HAVE_GCC_INIT_PRIORITY
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)
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
68 {CRYPTOPP_UNUSED(name); CRYPTOPP_UNUSED(valueType); CRYPTOPP_UNUSED(pValue);
return false;}
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);
113 void SimpleKeyingInterface::ThrowIfInvalidKeyLength(
size_t length)
119 void SimpleKeyingInterface::ThrowIfResynchronizable()
122 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object requires an IV");
125 void SimpleKeyingInterface::ThrowIfInvalidIV(
const byte *iv)
128 throw InvalidArgument(GetAlgorithm().AlgorithmName() +
": this object cannot use a null IV");
131 size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(
int size)
143 const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(
const NameValuePairs ¶ms,
size_t &size)
154 iv = ivWithLength.
begin();
155 ThrowIfInvalidIV(iv);
156 size = ThrowIfInvalidIVLength((
int)ivWithLength.
size());
161 ThrowIfInvalidIV(iv);
167 ThrowIfResynchronizable();
186 size_t xorIncrement = xorBlocks ? 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;
200 while (length >= blockSize)
202 if (flags & BT_XorInput)
206 #if defined(__COVERITY__)
209 xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
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>();
250 else if (length != 0)
265 UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
272 Update(header, headerLength);
281 Update(header, headerLength);
300 const word32 range = max-min;
308 value =
Crop(value, maxBits);
309 }
while (value > range);
328 CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
332 throw NotImplemented(
"RandomNumberGenerator: GenerateBlock not implemented");
351 size_t rem = target.
ChannelPut(channel, buffer, len);
369 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
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");
385 #if defined(CRYPTOPP_DOXYGEN_PROCESSING)
398 Clonable* Clone ()
const {
return NULL; }
410 ThrowIfInvalidTruncatedSize(digestLength);
416 void HashTransformation::ThrowIfInvalidTruncatedSize(
size_t size)
const
437 CRYPTOPP_UNUSED(propagation);
444 CRYPTOPP_UNUSED(propagation);
451 CRYPTOPP_UNUSED(propagation);
467 return Put2(begin, length, messageEnd, blocking);
477 return ChannelPut2(channel, begin, length, messageEnd, blocking);
483 return Flush(completeFlush, propagation, blocking);
520 return Get(&outByte, 1);
539 return Peek(&outByte, 1);
549 return (
size_t)
CopyTo(arraySink, peekMax);
610 unsigned int maxMessages = messageCount;
611 for (messageCount=0; messageCount < maxMessages &&
AnyMessages(); messageCount++)
614 lword transferredBytes;
618 transferredBytes = LWORD_MAX;
619 blockedBytes =
TransferTo2(target, transferredBytes, channel, blocking);
620 if (blockedBytes > 0)
661 unsigned int messageCount;
664 messageCount = UINT_MAX;
669 while (messageCount != 0);
674 byteCount = ULONG_MAX;
675 size_t blockedBytes =
TransferTo2(target, byteCount, channel, blocking);
679 while (byteCount != 0);
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);
726 byte buf[2] = {0, 0};
727 size_t len =
Peek(buf, 2);
730 value = (buf[0] << 8) | buf[1];
732 value = (buf[1] << 8) | buf[0];
739 byte buf[4] = {0, 0, 0, 0};
740 size_t len =
Peek(buf, 4);
743 value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf [3];
745 value = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf [0];
777 : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
782 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
785 m_plaintextQueue.
Put(inString, length);
790 size_t plaintextLength;
791 if (!
SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
792 throw InvalidArgument(
"PK_DefaultEncryptionFilter: plaintext too long");
796 m_plaintextQueue.
Get(plaintext, plaintextLength);
797 m_ciphertext.
resize(ciphertextLength);
798 m_encryptor.
Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
801 FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.
size(), messageEnd);
803 FILTER_END_NO_MESSAGE_END;
822 : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
827 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
830 m_ciphertextQueue.
Put(inString, length);
835 size_t ciphertextLength;
836 if (!
SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
837 throw InvalidArgument(
"PK_DefaultDecryptionFilter: ciphertext too long");
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);
848 FILTER_OUTPUT(1, m_plaintext, m_result.
messageLength, messageEnd);
850 FILTER_END_NO_MESSAGE_END;
875 m->
Update(message, messageLen);
880 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength, byte *signature)
const
884 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
898 m->
Update(message, messageLen);
909 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength,
910 const byte *signature,
size_t signatureLength)
const
914 m->
Update(nonrecoverableMessage, nonrecoverableMessageLength);
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.
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.
void resize(size_type newSize)
Change size and preserve contents.
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.
virtual void Encrypt(RandomNumberGenerator &rng, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs ¶meters=g_nullNameValuePairs) const =0
Encrypt a byte string.
virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0
Provides the maximum length of plaintext for a given ciphertext length.
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.
virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0
Input a recoverable message to an accumulator.
size_t messageLength
Recovered message length if isValidCoding is true, undefined otherwise.
void SetKeyWithRounds(const byte *key, size_t length, int rounds)
Sets or reset the key of this object.
virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0
Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulat...
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
Recover a message from its signature.
SecBlock<byte> typedef.
virtual lword MaxFooterLength() const
Provides the the maximum length of AAD.
const byte * begin() const
Pointer to the first byte in the memory block.
Interface for cloning objects.
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
virtual lword MaxHeaderLength() const =0
Provides the maximum length of AAD that can be input.
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.
virtual IV_Requirement IVRequirement() const =0
Minimal requirement for secure IVs.
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.
virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate static private key in this domain.
A method was called which was not implemented.
virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0
Recover a message from its signature.
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
void Detach(BufferedTransformation *newAttachment=NULL)
Replace an attached transformation.
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.
bool IsResynchronizable() const
Determines if the object can be resynchronized.
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
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.
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
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 void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a static public key from a private key in this domain.
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.
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
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.
virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a public key from a private key in this domain.
virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate ephemeral public key.
virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0
Create a new HashTransformation to accumulate the message to be verified.
PowerUpSelfTestStatus GetPowerUpSelfTestStatus()
Provides the current power-up self test status.
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
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.
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
The self tests have not been performed.
Interface for accumulating messages to be signed or verified.
virtual lword MaxMessageLength() const =0
Provides the maximum length of encrypted data.
virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate private key in this domain.
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 size_t CiphertextLength(size_t plaintextLength) const =0
Calculate the length of ciphertext given length of plaintext.
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 void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶ms=g_nullNameValuePairs)
Generate a random key or crypto parameters.
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.
virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0
Create a new HashTransformation to accumulate the message to be signed.
virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0
Sign and restart messageAccumulator.
bool isValidCoding
Flag to indicate the decoding is valid.
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prespecifies the data lengths.
Acts as an input discarding Filter or Sink.
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate ephemeral private key.
virtual std::string AlgorithmName() const =0
Provides the name of this algorithm.
The IV must be random and unpredictable.
virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0
Input signature into a message accumulator.
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.
size_t Get(byte &outByte)
Retrieve a 8-bit byte.
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
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.
virtual DecodingResult Decrypt(RandomNumberGenerator &rng, const byte *ciphertext, size_t ciphertextLength, byte *plaintext, const NameValuePairs ¶meters=g_nullNameValuePairs) const =0
Decrypt a byte string.
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.