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
30NAMESPACE_BEGIN(CryptoPP)
32CRYPTOPP_COMPILE_ASSERT(
sizeof(
byte) == 1);
33CRYPTOPP_COMPILE_ASSERT(
sizeof(
word16) == 2);
34CRYPTOPP_COMPILE_ASSERT(
sizeof(
word32) == 4);
35CRYPTOPP_COMPILE_ASSERT(
sizeof(word64) == 8);
36#ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
37CRYPTOPP_COMPILE_ASSERT(
sizeof(dword) == 2*
sizeof(word));
48 if (checkSelfTestStatus && FIPS_140_2_ComplianceEnabled())
51 throw SelfTestFailure(
"Cryptographic algorithms are disabled before the power-up self tests are performed.");
54 throw SelfTestFailure(
"Cryptographic algorithms are disabled after a power-up self test failed.");
96 size =
static_cast<size_t>(
IVSize());
102 size =
static_cast<size_t>(length);
110 const byte *iv = NULLPTR;
113 try {found = params.
GetValue(Name::IV(), ivWithLength);}
118 iv = ivWithLength.
begin();
122 else if (params.
GetValue(Name::IV(), iv))
125 size =
static_cast<size_t>(
IVSize());
143 CRYPTOPP_ASSERT(inBlocks);
144 CRYPTOPP_ASSERT(outBlocks);
145 CRYPTOPP_ASSERT(length);
147 const unsigned int blockSize =
BlockSize();
149 size_t xorIncrement = xorBlocks ? blockSize : 0;
154 inBlocks =
PtrAdd(inBlocks, length - blockSize);
155 xorBlocks =
PtrAdd(xorBlocks, length - blockSize);
156 outBlocks =
PtrAdd(outBlocks, length - blockSize);
157 inIncrement = 0-inIncrement;
158 xorIncrement = 0-xorIncrement;
159 outIncrement = 0-outIncrement;
163 const bool xorFlag = xorBlocks && (flags &
BT_XorInput);
164 while (length >= blockSize)
169 xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
179 const_cast<byte *
>(inBlocks)[blockSize-1]++;
181 inBlocks =
PtrAdd(inBlocks, inIncrement);
182 outBlocks =
PtrAdd(outBlocks, outIncrement);
183 xorBlocks =
PtrAdd(xorBlocks, xorIncrement);
192 return GetAlignmentOf<word32>();
197 return GetAlignmentOf<word32>();
202 return GetAlignmentOf<word32>();
212 else if (length != 0)
224 outLength = inLength;
227 else if (inLength != 0)
244 UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
251 Update(header, headerLength);
260 Update(header, headerLength);
285 const word32 range = max-min;
293 value =
Crop(value, maxBits);
294 }
while (value > range);
313 CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
331 (void)target.
ChannelPut(channel, buffer, len);
343 return static_cast<size_t>(-1);
353 CRYPTOPP_UNUSED(params);
367#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
379 CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
380 throw NotImplemented(
"NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
383#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
393 void Shuffle (IT begin, IT end) {}
410 SecByteBlock calculated(digestLength ? digestLength : 1);
412 return VerifyBufsEqual(calculated, digest, digestLength);
436 CRYPTOPP_UNUSED(propagation);
443 CRYPTOPP_UNUSED(propagation);
450 CRYPTOPP_UNUSED(propagation);
457 byte* space = NULLPTR;
469 size =
Put2(inString, length, messageEnd, blocking);
481 size =
ChannelPut2(channel, inString, length, messageEnd, blocking);
489 result =
Flush(hardFlush, propagation, blocking);
523 result =
Peek(b) != 0;
534 size =
Get(&outByte, 1);
557 size =
Peek(&outByte, 1);
569 size = (size_t)
CopyTo(arraySink, peekMax);
596 unsigned int size = 0;
628 unsigned int size = 0;
642 unsigned int maxMessages = messageCount;
643 for (messageCount=0; messageCount < maxMessages &&
AnyMessages(); messageCount++)
646 lword transferredBytes;
656 blockedBytes =
TransferTo2(target, transferredBytes, channel, blocking);
657 if (blockedBytes > 0)
665 CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result);
673 unsigned int size = 0;
698 unsigned int messageCount;
701 messageCount = UINT_MAX;
706 while (messageCount != 0);
711 byteCount = ULONG_MAX;
712 size_t blockedBytes =
TransferTo2(target, byteCount, channel, blocking);
716 while (byteCount != 0);
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);
753 PutWord(
false, order, m_buf, value);
754 return ChannelPut(channel, m_buf, 8, blocking);
774 byte buf[2] = {0, 0};
775 size_t len =
Peek(buf, 2);
778 value =
word16((buf[0] << 8) | buf[1]);
780 value =
word16((buf[1] << 8) | buf[0]);
787 byte buf[4] = {0, 0, 0, 0};
788 size_t len =
Peek(buf, 4);
791 value =
word32((buf[0] << 24) | (buf[1] << 16) |
792 (buf[2] << 8) | (buf[3] << 0));
794 value =
word32((buf[3] << 24) | (buf[2] << 16) |
795 (buf[1] << 8) | (buf[0] << 0));
802 byte buf[8] = {0, 0, 0, 0, 0, 0, 0, 0};
803 size_t len =
Peek(buf, 8);
806 value = ((word64)buf[0] << 56) | ((word64)buf[1] << 48) | ((word64)buf[2] << 40) |
807 ((word64)buf[3] << 32) | ((word64)buf[4] << 24) | ((word64)buf[5] << 16) |
808 ((word64)buf[6] << 8) | (word64)buf[7];
810 value = ((word64)buf[7] << 56) | ((word64)buf[6] << 48) | ((word64)buf[5] << 40) |
811 ((word64)buf[4] << 32) | ((word64)buf[3] << 24) | ((word64)buf[2] << 16) |
812 ((word64)buf[1] << 8) | (word64)buf[0];
849 : m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
854 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
857 m_plaintextQueue.
Put(inString, length);
862 size_t plaintextLength;
864 throw InvalidArgument(
"PK_DefaultEncryptionFilter: plaintext too long");
868 m_plaintextQueue.
Get(plaintext, plaintextLength);
869 m_ciphertext.
resize(ciphertextLength);
870 m_encryptor.
Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
873 FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.
size(), messageEnd);
875 FILTER_END_NO_MESSAGE_END;
894 : m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
899 size_t Put2(
const byte *inString,
size_t length,
int messageEnd,
bool blocking)
902 m_ciphertextQueue.
Put(inString, length);
907 size_t ciphertextLength;
909 throw InvalidArgument(
"PK_DefaultDecryptionFilter: ciphertext too long");
913 m_ciphertextQueue.
Get(ciphertext, ciphertextLength);
914 m_plaintext.
resize(maxPlaintextLength);
915 m_result = m_decryptor.
Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
920 FILTER_OUTPUT(1, m_plaintext, m_result.
messageLength, messageEnd);
922 FILTER_END_NO_MESSAGE_END;
947 m->Update(message, messageLen);
952 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength,
byte *signature)
const
956 m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
970 m->Update(message, messageLen);
981 const byte *nonrecoverableMessage,
size_t nonrecoverableMessageLength,
982 const byte *signature,
size_t signatureLength)
const
986 m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
1010#ifndef CRYPTOPP_BUILD_VERSION
1011# define CRYPTOPP_BUILD_VERSION CRYPTOPP_VERSION
1013int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT)
1015 return CRYPTOPP_BUILD_VERSION;
1022 bool GetVoidValue(
const char *name,
const std::type_info &valueType,
void *pValue)
const
1023 {CRYPTOPP_UNUSED(name); CRYPTOPP_UNUSED(valueType); CRYPTOPP_UNUSED(pValue);
return false;}
1026#if HAVE_GCC_INIT_PRIORITY
1027 const std::string DEFAULT_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 25))) =
"";
1028 const std::string AAD_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 26))) =
"AAD";
1029 const NullNameValuePairs s_nullNameValuePairs __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 27)));
1030 const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
1031#elif HAVE_MSC_INIT_PRIORITY
1032 #pragma warning(disable: 4073)
1033 #pragma init_seg(lib)
1034 const std::string DEFAULT_CHANNEL =
"";
1035 const std::string AAD_CHANNEL =
"AAD";
1037 const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
1038 #pragma warning(default: 4073)
1039#elif HAVE_XLC_INIT_PRIORITY
1040 #pragma priority(260)
1041 const std::string DEFAULT_CHANNEL =
"";
1042 const std::string AAD_CHANNEL =
"AAD";
1044 const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
1046 const std::string DEFAULT_CHANNEL =
"";
1047 const std::string AAD_CHANNEL =
"AAD";
1049 const NameValuePairs &g_nullNameValuePairs = *s_pNullNameValuePairs.m_p;
Classes for working with NameValuePairs.
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Standard names for retrieving values by name when working with NameValuePairs.
Algorithm(bool checkSelfTestStatus=true)
Interface for all crypto algorithms.
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Copy input to a memory buffer.
virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate static private key in this domain.
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 void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate ephemeral public key.
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate ephemeral private key.
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate private/public key pair.
virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a static private/public key pair.
virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macSize, 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 lword MaxHeaderLength() const =0
Provides the maximum length of AAD that can be input.
const Algorithm & GetAlgorithm() const
Returns the base class Algorithm.
virtual lword MaxFooterLength() const
Provides the maximum length of AAD.
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 SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prescribes the data lengths.
virtual lword MaxMessageLength() const =0
Provides the maximum length of encrypted data.
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Acts as an input discarding Filter or Sink.
Data structure used to store byte strings.
lword CurrentSize() const
Determine data size.
size_t Get(byte &outByte)
Retrieve a 8-bit byte.
Random Number Generator that does not produce random numbers.
void GenerateBlock(byte *output, size_t size)
An implementation that throws NotImplemented.
std::string AlgorithmName() const
The name of the generator.
Namespace containing NaCl library functions.
virtual Clonable * Clone() const
Copies this object.
Used to pass byte array input as part of a NameValuePairs object.
const byte * begin() const
Pointer to the first byte in the memory block.
size_t size() const
Length of the memory block.
void Detach(BufferedTransformation *newAttachment=NULLPTR)
Replace an attached transformation.
Fixed size stack-based SecBlock.
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
Generate a random key or crypto parameters.
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶ms=g_nullNameValuePairs)
Generate a random key or crypto parameters.
An invalid argument was detected.
A decryption filter encountered invalid ciphertext.
Exception thrown when an invalid derived key length is encountered.
Exception thrown when an invalid key length is encountered.
virtual size_t MaxDerivedKeyLength() const
Determine maximum number of bytes.
virtual size_t MinDerivedKeyLength() const
Determine minimum number of bytes.
virtual void SetParameters(const NameValuePairs ¶ms)
Set or change parameters.
void ThrowIfInvalidDerivedKeyLength(size_t length) const
Validates the derived key length.
virtual const Algorithm & GetAlgorithm() const =0
Returns the base class Algorithm.
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
virtual std::string AlgorithmName() const =0
Provides the name of this algorithm.
Thrown when an unexpected type is encountered.
Interface for retrieving values given their names.
bool GetValue(const char *name, T &value) const
Get a named value.
A method was called which was not implemented.
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0
Provides the maximum length of plaintext for a given ciphertext length.
virtual size_t CiphertextLength(size_t plaintextLength) const =0
Calculate the length of ciphertext given length of plaintext.
Interface for public-key decryptors.
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULLPTR, const NameValuePairs ¶meters=g_nullNameValuePairs) const
Create a new decryption filter.
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.
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing.
Interface for public-key encryptors.
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULLPTR, const NameValuePairs ¶meters=g_nullNameValuePairs) const
Create a new encryption filter.
virtual void Encrypt(RandomNumberGenerator &rng, const byte *plaintext, size_t plaintextLength, byte *ciphertext, const NameValuePairs ¶meters=g_nullNameValuePairs) const =0
Encrypt a byte string.
Interface for accumulating messages to be signed or verified.
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
Sign a message.
virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0
Input a recoverable message to an accumulator.
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
Sign and delete the messageAccumulator.
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 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.
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 PK_MessageAccumulator * NewVerificationAccumulator() const =0
Create a new HashTransformation to accumulate the message to be verified.
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
Recover a message from its signature.
virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0
Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulat...
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const
Check whether messageAccumulator contains a valid signature and message.
virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0
Input signature into a message accumulator.
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 DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0
Recover a message from its signature.
Interface for random number generators.
virtual void DiscardBytes(size_t n)
Generate and discard n bytes.
virtual void GenerateBlock(byte *output, size_t size)
Generate random array of bytes.
virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
Generate random bytes into a BufferedTransformation.
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL)
Generate a random 32 bit word in the range min to max, inclusive.
virtual unsigned int GenerateBit()
Generate new random bit and return it.
virtual byte GenerateByte()
Generate new random byte and return it.
void Shuffle(IT begin, IT end)
Randomly shuffle the specified array.
size_type size() const
Provides the count of elements in the SecBlock.
void resize(size_type newSize)
Change size and preserve contents.
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
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 GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate private key in this domain.
void SetKeyWithRounds(const byte *key, size_t length, int rounds)
Sets or reset the key of this object.
void ThrowIfInvalidKeyLength(size_t length)
Validates the key length.
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
Sets or reset the key of this object.
virtual const Algorithm & GetAlgorithm() const =0
Returns the base class Algorithm.
const byte * GetIVAndThrowIfInvalid(const NameValuePairs ¶ms, size_t &size)
Retrieves and validates the IV.
bool IsResynchronizable() const
Determines if the object can be resynchronized.
virtual IV_Requirement IVRequirement() const =0
Minimal requirement for secure IVs.
@ UNPREDICTABLE_RANDOM_IV
The IV must be random and unpredictable.
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms)=0
Sets the key for this object without performing parameter validation.
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
void ThrowIfInvalidIV(const byte *iv)
Validates the IV.
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv)
Retrieves a secure IV for the next message.
virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms=g_nullNameValuePairs)
Sets or reset the key of this object.
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
void ThrowIfResynchronizable()
Validates the object.
size_t ThrowIfInvalidIVLength(int length)
Validates the IV length.
Base class for unflushable filters.
Pointer that overloads operator ->
Manages resources for a single object.
Library configuration file.
unsigned int word32
32-bit unsigned datatype
unsigned short word16
16-bit unsigned datatype
word64 lword
Large word type.
Abstract base classes that provide a uniform interface to this library.
CRYPTOPP_DLL BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
ByteOrder
Provides the byte ordering.
@ BIG_ENDIAN_ORDER
byte order is big-endian
Implementation of BufferedTransformation's attachment interface.
Classes and functions for the FIPS 140-2 validated library.
@ POWER_UP_SELF_TEST_NOT_DONE
The self tests have not been performed.
@ POWER_UP_SELF_TEST_FAILED
The self tests were executed via DoPowerUpSelfTest() or DoDllPowerUpSelfTest(), but the result was fa...
Utility functions for the Crypto++ library.
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULLPTR)
Access a block of memory.
unsigned int BitPrecision(const T &value)
Returns the number of bits required for a value.
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
PTR PtrAdd(PTR pointer, OFF offset)
Create a pointer with an offset.
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be negative and incorrectly promoted.
Classes for access to the operating system's random number generators.
Classes and functions for secure memory allocations.
Classes for automatic resource management.
Returns a decoding results.
bool isValidCoding
Flag to indicate the decoding is valid.
size_t messageLength
Recovered message length if isValidCoding is true, undefined otherwise.