cryptlib.cpp
// cryptlib.cpp - originally written and placed in the public domain by Wei Dai
#include "pch.h"
#include "config.h"
#if CRYPTOPP_MSC_VERSION
# pragma warning(disable: 4127 4189 4459)
#endif
#if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
# pragma GCC diagnostic ignored "-Wunused-value"
# pragma GCC diagnostic ignored "-Wunused-variable"
# pragma GCC diagnostic ignored "-Wunused-parameter"
#endif
#ifndef CRYPTOPP_IMPORTS
#include "cryptlib.h"
#include "filters.h"
#include "algparam.h"
#include "fips140.h"
#include "argnames.h"
#include "fltrimpl.h"
#include "osrng.h"
#include "secblock.h"
#include "smartptr.h"
#include "stdcpp.h"
#include "misc.h"
NAMESPACE_BEGIN(CryptoPP)
CRYPTOPP_COMPILE_ASSERT(sizeof(byte) == 1);
CRYPTOPP_COMPILE_ASSERT(sizeof(word16) == 2);
CRYPTOPP_COMPILE_ASSERT(sizeof(word32) == 4);
CRYPTOPP_COMPILE_ASSERT(sizeof(word64) == 8);
#ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE
CRYPTOPP_COMPILE_ASSERT(sizeof(dword) == 2*sizeof(word));
#endif
BufferedTransformation & TheBitBucket()
{
static BitBucket bitBucket;
return bitBucket;
}
Algorithm::Algorithm(bool checkSelfTestStatus)
{
if (checkSelfTestStatus && FIPS_140_2_ComplianceEnabled())
{
if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_NOT_DONE && !PowerUpSelfTestInProgressOnThisThread())
throw SelfTestFailure("Cryptographic algorithms are disabled before the power-up self tests are performed.");
if (GetPowerUpSelfTestStatus() == POWER_UP_SELF_TEST_FAILED)
throw SelfTestFailure("Cryptographic algorithms are disabled after a power-up self test failed.");
}
}
void SimpleKeyingInterface::SetKey(const byte *key, size_t length, const NameValuePairs &params)
{
this->ThrowIfInvalidKeyLength(length);
this->UncheckedSetKey(key, static_cast<unsigned int>(length), params);
}
void SimpleKeyingInterface::SetKeyWithRounds(const byte *key, size_t length, int rounds)
{
SetKey(key, length, MakeParameters(Name::Rounds(), rounds));
}
void SimpleKeyingInterface::SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
{
SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, ivLength)));
}
void SimpleKeyingInterface::ThrowIfInvalidKeyLength(size_t length)
{
if (!IsValidKeyLength(length))
throw InvalidKeyLength(GetAlgorithm().AlgorithmName(), length);
}
void SimpleKeyingInterface::ThrowIfResynchronizable()
{
if (IsResynchronizable())
throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object requires an IV");
}
void SimpleKeyingInterface::ThrowIfInvalidIV(const byte *iv)
{
if (!iv && IVRequirement() == UNPREDICTABLE_RANDOM_IV)
throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": this object cannot use a null IV");
}
size_t SimpleKeyingInterface::ThrowIfInvalidIVLength(int length)
{
size_t size = 0;
if (length < 0)
size = static_cast<size_t>(IVSize());
else if ((size_t)length < MinIVLength())
throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(length) + " is less than the minimum of " + IntToString(MinIVLength()));
else if ((size_t)length > MaxIVLength())
throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": IV length " + IntToString(length) + " exceeds the maximum of " + IntToString(MaxIVLength()));
else
size = static_cast<size_t>(length);
return size;
}
const byte * SimpleKeyingInterface::GetIVAndThrowIfInvalid(const NameValuePairs &params, size_t &size)
{
ConstByteArrayParameter ivWithLength;
const byte *iv = NULLPTR;
bool found = false;
try {found = params.GetValue(Name::IV(), ivWithLength);}
catch (const NameValuePairs::ValueTypeMismatch &) {}
if (found)
{
iv = ivWithLength.begin();
ThrowIfInvalidIV(iv);
size = ThrowIfInvalidIVLength(static_cast<int>(ivWithLength.size()));
}
else if (params.GetValue(Name::IV(), iv))
{
ThrowIfInvalidIV(iv);
size = static_cast<size_t>(IVSize());
}
else
{
ThrowIfResynchronizable();
size = 0;
}
return iv;
}
void SimpleKeyingInterface::GetNextIV(RandomNumberGenerator &rng, byte *iv)
{
rng.GenerateBlock(iv, IVSize());
}
size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const
{
CRYPTOPP_ASSERT(inBlocks);
CRYPTOPP_ASSERT(outBlocks);
CRYPTOPP_ASSERT(length);
const unsigned int blockSize = BlockSize();
size_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize;
size_t xorIncrement = xorBlocks ? blockSize : 0;
size_t outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : blockSize;
if (flags & BT_ReverseDirection)
{
inBlocks = PtrAdd(inBlocks, length - blockSize);
xorBlocks = PtrAdd(xorBlocks, length - blockSize);
outBlocks = PtrAdd(outBlocks, length - blockSize);
inIncrement = 0-inIncrement;
xorIncrement = 0-xorIncrement;
outIncrement = 0-outIncrement;
}
// Coverity finding.
const bool xorFlag = xorBlocks && (flags & BT_XorInput);
while (length >= blockSize)
{
if (xorFlag)
{
// xorBlocks non-NULL and with BT_XorInput.
xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
ProcessBlock(outBlocks);
}
else
{
// xorBlocks may be non-NULL and without BT_XorInput.
ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
}
if (flags & BT_InBlockIsCounter)
const_cast<byte *>(inBlocks)[blockSize-1]++;
inBlocks = PtrAdd(inBlocks, inIncrement);
outBlocks = PtrAdd(outBlocks, outIncrement);
xorBlocks = PtrAdd(xorBlocks, xorIncrement);
length -= blockSize;
}
return length;
}
unsigned int BlockTransformation::OptimalDataAlignment() const
{
return GetAlignmentOf<word32>();
}
unsigned int StreamTransformation::OptimalDataAlignment() const
{
return GetAlignmentOf<word32>();
}
unsigned int HashTransformation::OptimalDataAlignment() const
{
return GetAlignmentOf<word32>();
}
#if 0
void StreamTransformation::ProcessLastBlock(byte *outString, const byte *inString, size_t length)
{
CRYPTOPP_ASSERT(MinLastBlockSize() == 0); // this function should be overridden otherwise
if (length == MandatoryBlockSize())
ProcessData(outString, inString, length);
else if (length != 0)
throw NotImplemented(AlgorithmName() + ": this object doesn't support a special last block");
}
#endif
size_t StreamTransformation::ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength)
{
// this function should be overridden otherwise
CRYPTOPP_ASSERT(MinLastBlockSize() == 0);
if (inLength == MandatoryBlockSize())
{
outLength = inLength; // squash unused warning
ProcessData(outString, inString, inLength);
}
else if (inLength != 0)
throw NotImplemented(AlgorithmName() + ": this object doesn't support a special last block");
return outLength;
}
void AuthenticatedSymmetricCipher::SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength)
{
if (headerLength > MaxHeaderLength())
throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": header length " + IntToString(headerLength) + " exceeds the maximum of " + IntToString(MaxHeaderLength()));
if (messageLength > MaxMessageLength())
throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": message length " + IntToString(messageLength) + " exceeds the maximum of " + IntToString(MaxMessageLength()));
if (footerLength > MaxFooterLength())
throw InvalidArgument(GetAlgorithm().AlgorithmName() + ": footer length " + IntToString(footerLength) + " exceeds the maximum of " + IntToString(MaxFooterLength()));
UncheckedSpecifyDataLengths(headerLength, messageLength, footerLength);
}
void AuthenticatedSymmetricCipher::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)
{
Resynchronize(iv, ivLength);
SpecifyDataLengths(headerLength, messageLength);
Update(header, headerLength);
ProcessString(ciphertext, message, messageLength);
TruncatedFinal(mac, macSize);
}
bool AuthenticatedSymmetricCipher::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)
{
Resynchronize(iv, ivLength);
SpecifyDataLengths(headerLength, ciphertextLength);
Update(header, headerLength);
ProcessString(message, ciphertext, ciphertextLength);
return TruncatedVerify(mac, macLength);
}
std::string AuthenticatedSymmetricCipher::AlgorithmName() const
{
// Squash C4505 on Visual Studio 2008 and friends
return "Unknown";
}
unsigned int RandomNumberGenerator::GenerateBit()
{
return GenerateByte() & 1;
}
byte RandomNumberGenerator::GenerateByte()
{
byte b;
GenerateBlock(&b, 1);
return b;
}
word32 RandomNumberGenerator::GenerateWord32(word32 min, word32 max)
{
const word32 range = max-min;
const unsigned int maxBits = BitPrecision(range);
word32 value;
do
{
GenerateBlock((byte *)&value, sizeof(value));
value = Crop(value, maxBits);
} while (value > range);
return value+min;
}
// Stack recursion below... GenerateIntoBufferedTransformation calls GenerateBlock,
// and GenerateBlock calls GenerateIntoBufferedTransformation. Ad infinitum. Also
// see http://github.com/weidai11/cryptopp/issues/38.
//
// According to Wei, RandomNumberGenerator is an interface, and it should not
// be instantiable. Its now spilt milk, and we are going to CRYPTOPP_ASSERT it in Debug
// builds to alert the programmer and throw in Release builds. Developers have
// a reference implementation in case its needed. If a programmer
// unintentionally lands here, then they should ensure use of a
// RandomNumberGenerator pointer or reference so polymorphism can provide the
// proper runtime dispatching.
void RandomNumberGenerator::GenerateBlock(byte *output, size_t size)
{
CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
ArraySink s(output, size);
GenerateIntoBufferedTransformation(s, DEFAULT_CHANNEL, size);
}
void RandomNumberGenerator::DiscardBytes(size_t n)
{
GenerateIntoBufferedTransformation(TheBitBucket(), DEFAULT_CHANNEL, n);
}
void RandomNumberGenerator::GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
{
FixedSizeSecBlock<byte, 256> buffer;
while (length)
{
size_t len = UnsignedMin(buffer.size(), length);
GenerateBlock(buffer, len);
(void)target.ChannelPut(channel, buffer, len);
length -= len;
}
}
size_t KeyDerivationFunction::MinDerivedKeyLength() const
{
return 0;
}
size_t KeyDerivationFunction::MaxDerivedKeyLength() const
{
return static_cast<size_t>(-1);
}
void KeyDerivationFunction::ThrowIfInvalidDerivedKeyLength(size_t length) const
{
if (!IsValidDerivedLength(length))
throw InvalidDerivedKeyLength(GetAlgorithm().AlgorithmName(), length);
}
void KeyDerivationFunction::SetParameters(const NameValuePairs& params) {
CRYPTOPP_UNUSED(params);
}
/// \brief Random Number Generator that does not produce random numbers
/// \details ClassNullRNG can be used for functions that require a RandomNumberGenerator
/// but don't actually use it. The class throws NotImplemented when a generation function is called.
/// \sa NullRNG()
class ClassNullRNG : public RandomNumberGenerator
{
public:
/// \brief The name of the generator
/// \returns the string \a NullRNGs
std::string AlgorithmName() const {return "NullRNG";}
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
/// \brief An implementation that throws NotImplemented
byte GenerateByte () {}
/// \brief An implementation that throws NotImplemented
unsigned int GenerateBit () {}
/// \brief An implementation that throws NotImplemented
word32 GenerateWord32 (word32 min, word32 max) {}
#endif
/// \brief An implementation that throws NotImplemented
void GenerateBlock(byte *output, size_t size)
{
CRYPTOPP_UNUSED(output); CRYPTOPP_UNUSED(size);
throw NotImplemented("NullRNG: NullRNG should only be passed to functions that don't need to generate random bytes");
}
#if defined(CRYPTOPP_DOXYGEN_PROCESSING)
/// \brief An implementation that throws NotImplemented
void GenerateIntoBufferedTransformation (BufferedTransformation &target, const std::string &channel, lword length) {}
/// \brief An implementation that throws NotImplemented
void IncorporateEntropy (const byte *input, size_t length) {}
/// \brief An implementation that returns \p false
bool CanIncorporateEntropy () const {}
/// \brief An implementation that does nothing
void DiscardBytes (size_t n) {}
/// \brief An implementation that does nothing
void Shuffle (IT begin, IT end) {}
private:
Clonable* Clone () const { return NULLPTR; }
#endif
};
RandomNumberGenerator & NullRNG()
{
static ClassNullRNG s_nullRNG;
return s_nullRNG;
}
bool HashTransformation::TruncatedVerify(const byte *digest, size_t digestLength)
{
// Allocate at least 1 for calculated to avoid triggering diagnostics
ThrowIfInvalidTruncatedSize(digestLength);
SecByteBlock calculated(digestLength ? digestLength : 1);
TruncatedFinal(calculated, digestLength);
return VerifyBufsEqual(calculated, digest, digestLength);
}
void HashTransformation::ThrowIfInvalidTruncatedSize(size_t size) const
{
if (size > DigestSize())
throw InvalidArgument("HashTransformation: can't truncate a " + IntToString(DigestSize()) + " byte digest to " + IntToString(size) + " bytes");
}
unsigned int BufferedTransformation::GetMaxWaitObjectCount() const
{
const BufferedTransformation *t = AttachedTransformation();
return t ? t->GetMaxWaitObjectCount() : 0;
}
void BufferedTransformation::GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack)
{
BufferedTransformation *t = AttachedTransformation();
if (t)
t->GetWaitObjects(container, callStack); // reduce clutter by not adding to stack here
}
void BufferedTransformation::Initialize(const NameValuePairs &parameters, int propagation)
{
CRYPTOPP_UNUSED(propagation);
CRYPTOPP_ASSERT(!AttachedTransformation());
IsolatedInitialize(parameters);
}
bool BufferedTransformation::Flush(bool hardFlush, int propagation, bool blocking)
{
CRYPTOPP_UNUSED(propagation);
CRYPTOPP_ASSERT(!AttachedTransformation());
return IsolatedFlush(hardFlush, blocking);
}
bool BufferedTransformation::MessageSeriesEnd(int propagation, bool blocking)
{
CRYPTOPP_UNUSED(propagation);
CRYPTOPP_ASSERT(!AttachedTransformation());
return IsolatedMessageSeriesEnd(blocking);
}
byte * BufferedTransformation::ChannelCreatePutSpace(const std::string &channel, size_t &size)
{
byte* space = NULLPTR;
if (channel.empty())
space = CreatePutSpace(size);
else
throw NoChannelSupport(AlgorithmName());
return space;
}
size_t BufferedTransformation::ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking)
{
size_t size = 0;
if (channel.empty())
size = Put2(inString, length, messageEnd, blocking);
else
throw NoChannelSupport(AlgorithmName());
return size;
}
size_t BufferedTransformation::ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking)
{
size_t size = 0;
if (channel.empty())
size = PutModifiable2(inString, length, messageEnd, blocking);
else
size = ChannelPut2(channel, inString, length, messageEnd, blocking);
return size;
}
bool BufferedTransformation::ChannelFlush(const std::string &channel, bool hardFlush, int propagation, bool blocking)
{
bool result = 0;
if (channel.empty())
result = Flush(hardFlush, propagation, blocking);
else
throw NoChannelSupport(AlgorithmName());
return result;
}
bool BufferedTransformation::ChannelMessageSeriesEnd(const std::string &channel, int propagation, bool blocking)
{
bool result = false;
if (channel.empty())
result = MessageSeriesEnd(propagation, blocking);
else
throw NoChannelSupport(AlgorithmName());
return result;
}
lword BufferedTransformation::MaxRetrievable() const
{
lword size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->MaxRetrievable();
else
size = CopyTo(TheBitBucket());
return size;
}
bool BufferedTransformation::AnyRetrievable() const
{
bool result = false;
if (AttachedTransformation())
result = AttachedTransformation()->AnyRetrievable();
else
{
byte b;
result = Peek(b) != 0;
}
return result;
}
size_t BufferedTransformation::Get(byte &outByte)
{
size_t size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->Get(outByte);
else
size = Get(&outByte, 1);
return size;
}
size_t BufferedTransformation::Get(byte *outString, size_t getMax)
{
size_t size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->Get(outString, getMax);
else
{
ArraySink arraySink(outString, getMax);
size = (size_t)TransferTo(arraySink, getMax);
}
return size;
}
size_t BufferedTransformation::Peek(byte &outByte) const
{
size_t size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->Peek(outByte);
else
size = Peek(&outByte, 1);
return size;
}
size_t BufferedTransformation::Peek(byte *outString, size_t peekMax) const
{
size_t size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->Peek(outString, peekMax);
else
{
ArraySink arraySink(outString, peekMax);
size = (size_t)CopyTo(arraySink, peekMax);
}
return size;
}
lword BufferedTransformation::Skip(lword skipMax)
{
lword size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->Skip(skipMax);
else
size = TransferTo(TheBitBucket(), skipMax);
return size;
}
lword BufferedTransformation::TotalBytesRetrievable() const
{
lword size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->TotalBytesRetrievable();
else
size = MaxRetrievable();
return size;
}
unsigned int BufferedTransformation::NumberOfMessages() const
{
unsigned int size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->NumberOfMessages();
else
size = CopyMessagesTo(TheBitBucket());
return size;
}
bool BufferedTransformation::AnyMessages() const
{
bool result = false;
if (AttachedTransformation())
result = AttachedTransformation()->AnyMessages();
else
result = NumberOfMessages() != 0;
return result;
}
bool BufferedTransformation::GetNextMessage()
{
bool result = false;
if (AttachedTransformation())
result = AttachedTransformation()->GetNextMessage();
else
{
CRYPTOPP_ASSERT(!AnyMessages());
}
return result;
}
unsigned int BufferedTransformation::SkipMessages(unsigned int count)
{
unsigned int size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->SkipMessages(count);
else
size = TransferMessagesTo(TheBitBucket(), count);
return size;
}
size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel, bool blocking)
{
if (AttachedTransformation())
return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
else
{
unsigned int maxMessages = messageCount;
for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
{
size_t blockedBytes;
lword transferredBytes;
while (AnyRetrievable())
{
// MaxRetrievable() instead of LWORD_MAX due to GH #962. If
// the target calls CreatePutSpace(), then the allocation
// size will be LWORD_MAX. That happens when target is a
// ByteQueue. Maybe ByteQueue should check the size, and if
// it is LWORD_MAX or -1, then use a default like 4096.
transferredBytes = MaxRetrievable();
blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
if (blockedBytes > 0)
return blockedBytes;
}
if (target.ChannelMessageEnd(channel, GetAutoSignalPropagation(), blocking))
return 1;
bool result = GetNextMessage();
CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result);
}
return 0;
}
}
unsigned int BufferedTransformation::CopyMessagesTo(BufferedTransformation &target, unsigned int count, const std::string &channel) const
{
unsigned int size = 0;
if (AttachedTransformation())
size = AttachedTransformation()->CopyMessagesTo(target, count, channel);
return size;
}
void BufferedTransformation::SkipAll()
{
if (AttachedTransformation())
AttachedTransformation()->SkipAll();
else
{
while (SkipMessages()) {}
while (Skip()) {}
}
}
size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, const std::string &channel, bool blocking)
{
if (AttachedTransformation())
return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
else
{
CRYPTOPP_ASSERT(!NumberOfMessageSeries());
unsigned int messageCount;
do
{
messageCount = UINT_MAX;
size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
if (blockedBytes)
return blockedBytes;
}
while (messageCount != 0);
lword byteCount;
do
{
byteCount = ULONG_MAX;
size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
if (blockedBytes)
return blockedBytes;
}
while (byteCount != 0);
return 0;
}
}
void BufferedTransformation::CopyAllTo(BufferedTransformation &target, const std::string &channel) const
{
if (AttachedTransformation())
AttachedTransformation()->CopyAllTo(target, channel);
else
{
CRYPTOPP_ASSERT(!NumberOfMessageSeries());
while (CopyMessagesTo(target, UINT_MAX, channel)) {}
}
}
void BufferedTransformation::SetRetrievalChannel(const std::string &channel)
{
if (AttachedTransformation())
AttachedTransformation()->SetRetrievalChannel(channel);
}
size_t BufferedTransformation::ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order, bool blocking)
{
PutWord(false, order, m_buf, value);
return ChannelPut(channel, m_buf, 2, blocking);
}
size_t BufferedTransformation::ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order, bool blocking)
{
PutWord(false, order, m_buf, value);
return ChannelPut(channel, m_buf, 4, blocking);
}
size_t BufferedTransformation::ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order, bool blocking)
{
PutWord(false, order, m_buf, value);
return ChannelPut(channel, m_buf, 8, blocking);
}
size_t BufferedTransformation::PutWord16(word16 value, ByteOrder order, bool blocking)
{
return ChannelPutWord16(DEFAULT_CHANNEL, value, order, blocking);
}
size_t BufferedTransformation::PutWord32(word32 value, ByteOrder order, bool blocking)
{
return ChannelPutWord32(DEFAULT_CHANNEL, value, order, blocking);
}
size_t BufferedTransformation::PutWord64(word64 value, ByteOrder order, bool blocking)
{
return ChannelPutWord64(DEFAULT_CHANNEL, value, order, blocking);
}
size_t BufferedTransformation::PeekWord16(word16 &value, ByteOrder order) const
{
byte buf[2] = {0, 0};
size_t len = Peek(buf, 2);
if (order == BIG_ENDIAN_ORDER)
value = word16((buf[0] << 8) | buf[1]);
else
value = word16((buf[1] << 8) | buf[0]);
return len;
}
size_t BufferedTransformation::PeekWord32(word32 &value, ByteOrder order) const
{
byte buf[4] = {0, 0, 0, 0};
size_t len = Peek(buf, 4);
if (order == BIG_ENDIAN_ORDER)
value = word32((buf[0] << 24) | (buf[1] << 16) |
(buf[2] << 8) | (buf[3] << 0));
else
value = word32((buf[3] << 24) | (buf[2] << 16) |
(buf[1] << 8) | (buf[0] << 0));
return len;
}
size_t BufferedTransformation::PeekWord64(word64 &value, ByteOrder order) const
{
byte buf[8] = {0, 0, 0, 0, 0, 0, 0, 0};
size_t len = Peek(buf, 8);
if (order == BIG_ENDIAN_ORDER)
value = ((word64)buf[0] << 56) | ((word64)buf[1] << 48) | ((word64)buf[2] << 40) |
((word64)buf[3] << 32) | ((word64)buf[4] << 24) | ((word64)buf[5] << 16) |
((word64)buf[6] << 8) | (word64)buf[7];
else
value = ((word64)buf[7] << 56) | ((word64)buf[6] << 48) | ((word64)buf[5] << 40) |
((word64)buf[4] << 32) | ((word64)buf[3] << 24) | ((word64)buf[2] << 16) |
((word64)buf[1] << 8) | (word64)buf[0];
return len;
}
size_t BufferedTransformation::GetWord16(word16 &value, ByteOrder order)
{
return (size_t)Skip(PeekWord16(value, order));
}
size_t BufferedTransformation::GetWord32(word32 &value, ByteOrder order)
{
return (size_t)Skip(PeekWord32(value, order));
}
size_t BufferedTransformation::GetWord64(word64 &value, ByteOrder order)
{
return (size_t)Skip(PeekWord64(value, order));
}
void BufferedTransformation::Attach(BufferedTransformation *newAttachment)
{
if (AttachedTransformation() && AttachedTransformation()->Attachable())
AttachedTransformation()->Attach(newAttachment);
else
Detach(newAttachment);
}
void GeneratableCryptoMaterial::GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
{
GenerateRandom(rng, MakeParameters("KeySize", (int)keySize));
}
class PK_DefaultEncryptionFilter : public Unflushable<Filter>
{
public:
PK_DefaultEncryptionFilter(RandomNumberGenerator &rng, const PK_Encryptor &encryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
: m_rng(rng), m_encryptor(encryptor), m_parameters(parameters)
{
Detach(attachment);
}
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
{
FILTER_BEGIN;
m_plaintextQueue.Put(inString, length);
if (messageEnd)
{
{
size_t plaintextLength;
if (!SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
throw InvalidArgument("PK_DefaultEncryptionFilter: plaintext too long");
size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);
SecByteBlock plaintext(plaintextLength);
m_plaintextQueue.Get(plaintext, plaintextLength);
m_ciphertext.resize(ciphertextLength);
m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
}
FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
}
FILTER_END_NO_MESSAGE_END;
}
RandomNumberGenerator &m_rng;
const PK_Encryptor &m_encryptor;
const NameValuePairs &m_parameters;
ByteQueue m_plaintextQueue;
SecByteBlock m_ciphertext;
};
BufferedTransformation * PK_Encryptor::CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment, const NameValuePairs &parameters) const
{
return new PK_DefaultEncryptionFilter(rng, *this, attachment, parameters);
}
class PK_DefaultDecryptionFilter : public Unflushable<Filter>
{
public:
PK_DefaultDecryptionFilter(RandomNumberGenerator &rng, const PK_Decryptor &decryptor, BufferedTransformation *attachment, const NameValuePairs &parameters)
: m_rng(rng), m_decryptor(decryptor), m_parameters(parameters)
{
Detach(attachment);
}
size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
{
FILTER_BEGIN;
m_ciphertextQueue.Put(inString, length);
if (messageEnd)
{
{
size_t ciphertextLength;
if (!SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
throw InvalidArgument("PK_DefaultDecryptionFilter: ciphertext too long");
size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);
SecByteBlock ciphertext(ciphertextLength);
m_ciphertextQueue.Get(ciphertext, ciphertextLength);
m_plaintext.resize(maxPlaintextLength);
m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
if (!m_result.isValidCoding)
throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
}
FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
}
FILTER_END_NO_MESSAGE_END;
}
RandomNumberGenerator &m_rng;
const PK_Decryptor &m_decryptor;
const NameValuePairs &m_parameters;
ByteQueue m_ciphertextQueue;
SecByteBlock m_plaintext;
DecodingResult m_result;
};
BufferedTransformation * PK_Decryptor::CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment, const NameValuePairs &parameters) const
{
return new PK_DefaultDecryptionFilter(rng, *this, attachment, parameters);
}
size_t PK_Signer::Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
{
member_ptr<PK_MessageAccumulator> m(messageAccumulator);
return SignAndRestart(rng, *m, signature, false);
}
size_t PK_Signer::SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
{
member_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
m->Update(message, messageLen);
return SignAndRestart(rng, *m, signature, false);
}
size_t PK_Signer::SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const
{
member_ptr<PK_MessageAccumulator> m(NewSignatureAccumulator(rng));
InputRecoverableMessage(*m, recoverableMessage, recoverableMessageLength);
m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
return SignAndRestart(rng, *m, signature, false);
}
bool PK_Verifier::Verify(PK_MessageAccumulator *messageAccumulator) const
{
member_ptr<PK_MessageAccumulator> m(messageAccumulator);
return VerifyAndRestart(*m);
}
bool PK_Verifier::VerifyMessage(const byte *message, size_t messageLen, const byte *signature, size_t signatureLen) const
{
member_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
InputSignature(*m, signature, signatureLen);
m->Update(message, messageLen);
return VerifyAndRestart(*m);
}
DecodingResult PK_Verifier::Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
{
member_ptr<PK_MessageAccumulator> m(messageAccumulator);
return RecoverAndRestart(recoveredMessage, *m);
}
DecodingResult PK_Verifier::RecoverMessage(byte *recoveredMessage,
const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
const byte *signature, size_t signatureLength) const
{
member_ptr<PK_MessageAccumulator> m(NewVerificationAccumulator());
InputSignature(*m, signature, signatureLength);
m->Update(nonrecoverableMessage, nonrecoverableMessageLength);
return RecoverAndRestart(recoveredMessage, *m);
}
void SimpleKeyAgreementDomain::GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
{
GeneratePrivateKey(rng, privateKey);
GeneratePublicKey(rng, privateKey, publicKey);
}
void AuthenticatedKeyAgreementDomain::GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
{
GenerateStaticPrivateKey(rng, privateKey);
GenerateStaticPublicKey(rng, privateKey, publicKey);
}
void AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
{
GenerateEphemeralPrivateKey(rng, privateKey);
GenerateEphemeralPublicKey(rng, privateKey, publicKey);
}
// Allow a distro or packager to override the build-time version
// http://github.com/weidai11/cryptopp/issues/371
#ifndef CRYPTOPP_BUILD_VERSION
# define CRYPTOPP_BUILD_VERSION CRYPTOPP_VERSION
#endif
int LibraryVersion(CRYPTOPP_NOINLINE_DOTDOTDOT)
{
return CRYPTOPP_BUILD_VERSION;
}
class NullNameValuePairs : public NameValuePairs
{
public:
NullNameValuePairs() {} // Clang complains a default ctor must be available
bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
{CRYPTOPP_UNUSED(name); CRYPTOPP_UNUSED(valueType); CRYPTOPP_UNUSED(pValue); return false;}
};
#if HAVE_GCC_INIT_PRIORITY
const std::string DEFAULT_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 25))) = "";
const std::string AAD_CHANNEL __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 26))) = "AAD";
const NullNameValuePairs s_nullNameValuePairs __attribute__ ((init_priority (CRYPTOPP_INIT_PRIORITY + 27)));
const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
#elif HAVE_MSC_INIT_PRIORITY
#pragma warning(disable: 4073)
#pragma init_seg(lib)
const std::string DEFAULT_CHANNEL = "";
const std::string AAD_CHANNEL = "AAD";
const NullNameValuePairs s_nullNameValuePairs;
const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
#pragma warning(default: 4073)
#elif HAVE_XLC_INIT_PRIORITY
#pragma priority(260)
const std::string DEFAULT_CHANNEL = "";
const std::string AAD_CHANNEL = "AAD";
const NullNameValuePairs s_nullNameValuePairs;
const NameValuePairs& g_nullNameValuePairs = s_nullNameValuePairs;
#else
const std::string DEFAULT_CHANNEL = "";
const std::string AAD_CHANNEL = "AAD";
const simple_ptr<NullNameValuePairs> s_pNullNameValuePairs(new NullNameValuePairs);
const NameValuePairs &g_nullNameValuePairs = *s_pNullNameValuePairs.m_p;
#endif
NAMESPACE_END // CryptoPP
#endif // CRYPTOPP_IMPORTS
algparam.h
Classes for working with NameValuePairs.
MakeParameters
AlgorithmParameters MakeParameters(const char *name, const T &value, bool throwIfNotUsed=true)
Create an object that implements NameValuePairs.
Definition: algparam.h:508
argnames.h
Standard names for retrieving values by name when working with NameValuePairs.
Algorithm::Algorithm
Algorithm(bool checkSelfTestStatus=true)
Interface for all crypto algorithms.
Algorithm::AlgorithmName
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
Definition: cryptlib.h:619
ArraySink
Copy input to a memory buffer.
Definition: filters.h:1200
AuthenticatedKeyAgreementDomain::GenerateStaticPrivateKey
virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate static private key in this domain.
AuthenticatedKeyAgreementDomain::GenerateStaticPublicKey
virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a static public key from a private key in this domain.
AuthenticatedKeyAgreementDomain::GenerateEphemeralPublicKey
virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate ephemeral public key.
AuthenticatedKeyAgreementDomain::GenerateEphemeralPrivateKey
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate ephemeral private key.
AuthenticatedKeyAgreementDomain::GenerateStaticKeyPair
virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a static private/public key pair.
AuthenticatedKeyAgreementDomain::GenerateEphemeralKeyPair
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate private/public key pair.
AuthenticatedSymmetricCipher::MaxHeaderLength
virtual lword MaxHeaderLength() const =0
Provides the maximum length of AAD that can be input.
AuthenticatedSymmetricCipher::MaxFooterLength
virtual lword MaxFooterLength() const
Provides the maximum length of AAD.
Definition: cryptlib.h:1345
AuthenticatedSymmetricCipher::EncryptAndAuthenticate
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.
AuthenticatedSymmetricCipher::SpecifyDataLengths
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prescribes the data lengths.
AuthenticatedSymmetricCipher::MaxMessageLength
virtual lword MaxMessageLength() const =0
Provides the maximum length of encrypted data.
AuthenticatedSymmetricCipher::DecryptAndVerify
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.
AuthenticatedSymmetricCipher::AlgorithmName
virtual std::string AlgorithmName() const
Provides the name of this algorithm.
BitBucket
Acts as an input discarding Filter or Sink.
Definition: simple.h:491
BlockTransformation::ProcessAndXorBlock
virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0
Encrypt or decrypt a block.
BlockTransformation::ProcessBlock
void ProcessBlock(const byte *inBlock, byte *outBlock) const
Encrypt or decrypt a block.
Definition: cryptlib.h:879
BlockTransformation::AdvancedProcessBlocks
virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const
Encrypt and xor multiple blocks using additional flags.
BlockTransformation::BT_InBlockIsCounter
@ BT_InBlockIsCounter
inBlock is a counter
Definition: cryptlib.h:917
BlockTransformation::BT_ReverseDirection
@ BT_ReverseDirection
perform the transformation in reverse
Definition: cryptlib.h:923
BlockTransformation::BT_XorInput
@ BT_XorInput
Xor inputs before transformation.
Definition: cryptlib.h:921
BlockTransformation::BT_DontIncrementInOutPointers
@ BT_DontIncrementInOutPointers
should not modify block pointers
Definition: cryptlib.h:919
BlockTransformation::BlockSize
virtual unsigned int BlockSize() const =0
Provides the block size of the cipher.
BlockTransformation::OptimalDataAlignment
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
BufferedTransformation
Interface for buffered transformations.
Definition: cryptlib.h:1652
BufferedTransformation::AnyRetrievable
virtual bool AnyRetrievable() const
Determines whether bytes are ready for retrieval.
BufferedTransformation::AnyMessages
virtual bool AnyMessages() const
Determines if any messages are available for retrieval.
BufferedTransformation::TransferMessagesTo
unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
Transfer messages from this object to another BufferedTransformation.
Definition: cryptlib.h:2071
BufferedTransformation::GetMaxWaitObjectCount
unsigned int GetMaxWaitObjectCount() const
Retrieves the maximum number of waitable objects.
BufferedTransformation::ChannelPutWord64
size_t ChannelPutWord64(const std::string &channel, word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 64-bit word for processing on a channel.
BufferedTransformation::Initialize
virtual void Initialize(const NameValuePairs &parameters=g_nullNameValuePairs, int propagation=-1)
Initialize or reinitialize this object, with signal propagation.
BufferedTransformation::GetWaitObjects
void GetWaitObjects(WaitObjectContainer &container, CallStack const &callStack)
Retrieves waitable objects.
BufferedTransformation::SkipMessages
virtual unsigned int SkipMessages(unsigned int count=UINT_MAX)
Skip a number of meessages.
BufferedTransformation::CopyAllTo
void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const
Copy messages from this object to another BufferedTransformation.
BufferedTransformation::Get
virtual size_t Get(byte &outByte)
Retrieve a 8-bit byte.
BufferedTransformation::TransferMessagesTo2
size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)
Transfer messages from this object to another BufferedTransformation.
BufferedTransformation::GetWord16
size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER)
Retrieve a 16-bit word.
BufferedTransformation::Attachable
virtual bool Attachable()
Determines whether the object allows attachment.
Definition: cryptlib.h:2335
BufferedTransformation::NumberOfMessages
virtual unsigned int NumberOfMessages() const
Provides the number of meesages processed by this object.
BufferedTransformation::TransferTo2
virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)=0
Transfer bytes from this object to another BufferedTransformation.
BufferedTransformation::SetRetrievalChannel
virtual void SetRetrievalChannel(const std::string &channel)
Sets the default retrieval channel.
BufferedTransformation::ChannelFlush
virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output on a channel.
BufferedTransformation::CopyMessagesTo
unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const
Copy messages from this object to another BufferedTransformation.
BufferedTransformation::Peek
virtual size_t Peek(byte &outByte) const
Peek a 8-bit byte.
BufferedTransformation::TransferAllTo2
size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true)
Transfer all bytes from this object to another BufferedTransformation.
BufferedTransformation::PeekWord16
size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 16-bit word.
BufferedTransformation::Attach
virtual void Attach(BufferedTransformation *newAttachment)
Add newAttachment to the end of attachment chain.
BufferedTransformation::PeekWord32
size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 32-bit word.
BufferedTransformation::PutWord64
size_t PutWord64(word64 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 64-bit word for processing.
BufferedTransformation::ChannelPutModifiable2
virtual size_t ChannelPutModifiable2(const std::string &channel, byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes that may be modified by callee on a channel.
BufferedTransformation::IsolatedFlush
virtual bool IsolatedFlush(bool hardFlush, bool blocking)=0
Flushes data buffered by this object, without signal propagation.
BufferedTransformation::GetWord32
size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER)
Retrieve a 32-bit word.
BufferedTransformation::CopyTo
lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
Copy bytes from this object to another BufferedTransformation.
Definition: cryptlib.h:2013
BufferedTransformation::GetAutoSignalPropagation
virtual int GetAutoSignalPropagation() const
Retrieve automatic signal propagation value.
Definition: cryptlib.h:1887
BufferedTransformation::PutModifiable2
virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes that may be modified by callee.
Definition: cryptlib.h:1778
BufferedTransformation::IsolatedInitialize
virtual void IsolatedInitialize(const NameValuePairs &parameters)
Initialize or reinitialize this object, without signal propagation.
Definition: cryptlib.h:1816
BufferedTransformation::ChannelCreatePutSpace
virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size)
Request space which can be written into by the caller.
BufferedTransformation::ChannelPut2
virtual size_t ChannelPut2(const std::string &channel, const byte *inString, size_t length, int messageEnd, bool blocking)
Input multiple bytes for processing on a channel.
BufferedTransformation::SkipAll
virtual void SkipAll()
Skip all messages in the series.
BufferedTransformation::PutWord16
size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 16-bit word for processing.
BufferedTransformation::ChannelPut
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
Input a byte for processing on a channel.
Definition: cryptlib.h:2194
BufferedTransformation::MessageSeriesEnd
virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true)
Marks the end of a series of messages, with signal propagation.
BufferedTransformation::ChannelPutWord16
size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 16-bit word for processing on a channel.
BufferedTransformation::GetNextMessage
virtual bool GetNextMessage()
Start retrieving the next message.
BufferedTransformation::IsolatedMessageSeriesEnd
virtual bool IsolatedMessageSeriesEnd(bool blocking)
Marks the end of a series of messages, without signal propagation.
Definition: cryptlib.h:1832
BufferedTransformation::AttachedTransformation
virtual BufferedTransformation * AttachedTransformation()
Returns the object immediately attached to this object.
Definition: cryptlib.h:2341
BufferedTransformation::TransferTo
lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
move transferMax bytes of the buffered output to target as input
Definition: cryptlib.h:1991
BufferedTransformation::Flush
virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output, with signal propagation.
BufferedTransformation::Detach
virtual void Detach(BufferedTransformation *newAttachment=NULL)
Delete the current attachment chain and attach a new one.
Definition: cryptlib.h:2356
BufferedTransformation::ChannelMessageSeriesEnd
virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Marks the end of a series of messages on a channel.
BufferedTransformation::TotalBytesRetrievable
virtual lword TotalBytesRetrievable() const
Provides the number of bytes ready for retrieval.
BufferedTransformation::ChannelPutWord32
size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 32-bit word for processing on a channel.
BufferedTransformation::NumberOfMessageSeries
virtual unsigned int NumberOfMessageSeries() const
Provides the number of messages in a series.
Definition: cryptlib.h:2111
BufferedTransformation::Put2
virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)=0
Input multiple bytes for processing.
BufferedTransformation::GetWord64
size_t GetWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER)
Retrieve a 64-bit word.
BufferedTransformation::ChannelMessageEnd
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Signal the end of a message.
Definition: cryptlib.h:2252
BufferedTransformation::PeekWord64
size_t PeekWord64(word64 &value, ByteOrder order=BIG_ENDIAN_ORDER) const
Peek a 64-bit word.
BufferedTransformation::Skip
virtual lword Skip(lword skipMax=LWORD_MAX)
Discard skipMax bytes from the output buffer.
BufferedTransformation::CreatePutSpace
virtual byte * CreatePutSpace(size_t &size)
Request space which can be written into by the caller.
Definition: cryptlib.h:1720
BufferedTransformation::MaxRetrievable
virtual lword MaxRetrievable() const
Provides the number of bytes ready for retrieval.
BufferedTransformation::PutWord32
size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true)
Input a 32-bit word for processing.
ByteQueue
Data structure used to store byte strings.
Definition: queue.h:23
Clonable
Interface for cloning objects.
Definition: cryptlib.h:585
Clonable::Clone
virtual Clonable * Clone() const
Copies this object.
Definition: cryptlib.h:594
ConstByteArrayParameter
Used to pass byte array input as part of a NameValuePairs object.
Definition: algparam.h:25
ConstByteArrayParameter::size
size_t size() const
Length of the memory block.
Definition: algparam.h:88
ConstByteArrayParameter::begin
const byte * begin() const
Pointer to the first byte in the memory block.
Definition: algparam.h:84
FixedSizeSecBlock< byte, 256 >
GeneratableCryptoMaterial::GenerateRandomWithKeySize
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize)
Generate a random key or crypto parameters.
GeneratableCryptoMaterial::GenerateRandom
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &params=g_nullNameValuePairs)
Generate a random key or crypto parameters.
Definition: cryptlib.h:2520
HashTransformation::OptimalDataAlignment
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
HashTransformation::TruncatedFinal
virtual void TruncatedFinal(byte *digest, size_t digestSize)=0
Computes the hash of the current message.
HashTransformation::DigestSize
virtual unsigned int DigestSize() const =0
Provides the digest size of the hash.
HashTransformation::Update
virtual void Update(const byte *input, size_t length)=0
Updates a hash with additional input.
HashTransformation::TruncatedVerify
virtual bool TruncatedVerify(const byte *digest, size_t digestLength)
Verifies the hash of the current message.
InvalidArgument
An invalid argument was detected.
Definition: cryptlib.h:203
InvalidCiphertext
A decryption filter encountered invalid ciphertext.
Definition: cryptlib.h:223
InvalidDerivedKeyLength
Exception thrown when an invalid derived key length is encountered.
Definition: simple.h:86
InvalidKeyLength
Exception thrown when an invalid key length is encountered.
Definition: simple.h:56
KeyDerivationFunction::MinDerivedKeyLength
virtual size_t MinDerivedKeyLength() const
Determine minimum number of bytes.
KeyDerivationFunction::SetParameters
virtual void SetParameters(const NameValuePairs &params)
Set or change parameters.
KeyDerivationFunction::MaxDerivedKeyLength
virtual size_t MaxDerivedKeyLength() const
Determine maximum number of bytes.
KeyDerivationFunction::IsValidDerivedLength
virtual bool IsValidDerivedLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:1548
KeyDerivationFunction::AlgorithmName
virtual std::string AlgorithmName() const =0
Provides the name of this algorithm.
NameValuePairs::ValueTypeMismatch
Thrown when an unexpected type is encountered.
Definition: cryptlib.h:330
NameValuePairs
Interface for retrieving values given their names.
Definition: cryptlib.h:322
NameValuePairs::GetVoidValue
virtual CRYPTOPP_DLL bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0
Get a named value.
NameValuePairs::GetValue
bool GetValue(const char *name, T &value) const
Get a named value.
Definition: cryptlib.h:379
NotImplemented
A method was called which was not implemented.
Definition: cryptlib.h:233
PK_Decryptor
Interface for public-key decryptors.
Definition: cryptlib.h:2733
PK_Decryptor::CreateDecryptionFilter
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new decryption filter.
PK_Encryptor
Interface for public-key encryptors.
Definition: cryptlib.h:2698
PK_Encryptor::CreateEncryptionFilter
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng, BufferedTransformation *attachment=NULL, const NameValuePairs &parameters=g_nullNameValuePairs) const
Create a new encryption filter.
PK_MessageAccumulator
Interface for accumulating messages to be signed or verified.
Definition: cryptlib.h:2861
PK_Signer::SignMessageWithRecovery
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.
PK_Signer::InputRecoverableMessage
virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0
Input a recoverable message to an accumulator.
PK_Signer::Sign
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const
Sign and delete the messageAccumulator.
PK_Signer::SignMessage
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const
Sign a message.
PK_Signer::SignAndRestart
virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0
Sign and restart messageAccumulator.
PK_Signer::NewSignatureAccumulator
virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0
Create a new HashTransformation to accumulate the message to be signed.
PK_Verifier::VerifyMessage
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.
PK_Verifier::RecoverMessage
virtual DecodingResult RecoverMessage(byte *recoveredMessage, const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, const byte *signature, size_t signatureLength) const
Recover a message from its signature.
PK_Verifier::VerifyAndRestart
virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0
Check whether messageAccumulator contains a valid signature and message, and restart messageAccumulat...
PK_Verifier::InputSignature
virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0
Input signature into a message accumulator.
PK_Verifier::RecoverAndRestart
virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0
Recover a message from its signature.
PK_Verifier::Recover
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const
Recover a message from its signature.
PK_Verifier::NewVerificationAccumulator
virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0
Create a new HashTransformation to accumulate the message to be verified.
PK_Verifier::Verify
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const
Check whether messageAccumulator contains a valid signature and message.
RandomNumberGenerator
Interface for random number generators.
Definition: cryptlib.h:1435
RandomNumberGenerator::DiscardBytes
virtual void DiscardBytes(size_t n)
Generate and discard n bytes.
RandomNumberGenerator::GenerateWord32
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL)
Generate a random 32 bit word in the range min to max, inclusive.
RandomNumberGenerator::GenerateByte
virtual byte GenerateByte()
Generate new random byte and return it.
RandomNumberGenerator::IncorporateEntropy
virtual void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: cryptlib.h:1447
RandomNumberGenerator::CanIncorporateEntropy
virtual bool CanIncorporateEntropy() const
Determines if a generator can accept additional entropy.
Definition: cryptlib.h:1455
RandomNumberGenerator::GenerateIntoBufferedTransformation
virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length)
Generate random bytes into a BufferedTransformation.
RandomNumberGenerator::GenerateBit
virtual unsigned int GenerateBit()
Generate new random bit and return it.
RandomNumberGenerator::GenerateBlock
virtual void GenerateBlock(byte *output, size_t size)
Generate random array of bytes.
RandomNumberGenerator::Shuffle
void Shuffle(IT begin, IT end)
Randomly shuffle the specified array.
Definition: cryptlib.h:1510
SecBlock::size
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:867
SecByteBlock
SecBlock<byte> typedef.
Definition: secblock.h:1226
SelfTestFailure
Exception thrown when a crypto algorithm is used after a self test fails.
Definition: fips140.h:23
SimpleKeyAgreementDomain::GeneratePublicKey
virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0
Generate a public key from a private key in this domain.
SimpleKeyAgreementDomain::GenerateKeyPair
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const
Generate a private/public key pair.
SimpleKeyAgreementDomain::GeneratePrivateKey
virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0
Generate private key in this domain.
SimpleKeyingInterface::SetKeyWithRounds
void SetKeyWithRounds(const byte *key, size_t length, int rounds)
Sets or reset the key of this object.
SimpleKeyingInterface::GetNextIV
virtual void GetNextIV(RandomNumberGenerator &rng, byte *iv)
Retrieves a secure IV for the next message.
SimpleKeyingInterface::IsValidKeyLength
virtual bool IsValidKeyLength(size_t keylength) const
Returns whether keylength is a valid key length.
Definition: cryptlib.h:672
SimpleKeyingInterface::SetKeyWithIV
void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength)
Sets or reset the key of this object.
SimpleKeyingInterface::IsResynchronizable
bool IsResynchronizable() const
Determines if the object can be resynchronized.
Definition: cryptlib.h:740
SimpleKeyingInterface::IVRequirement
virtual IV_Requirement IVRequirement() const =0
Minimal requirement for secure IVs.
SimpleKeyingInterface::UNPREDICTABLE_RANDOM_IV
@ UNPREDICTABLE_RANDOM_IV
The IV must be random and unpredictable.
Definition: cryptlib.h:725
SimpleKeyingInterface::MaxIVLength
virtual unsigned int MaxIVLength() const
Provides the maximum size of an IV.
Definition: cryptlib.h:776
SimpleKeyingInterface::SetKey
virtual void SetKey(const byte *key, size_t length, const NameValuePairs &params=g_nullNameValuePairs)
Sets or reset the key of this object.
SimpleKeyingInterface::MinIVLength
virtual unsigned int MinIVLength() const
Provides the minimum size of an IV.
Definition: cryptlib.h:771
SimpleKeyingInterface::IVSize
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
Definition: cryptlib.h:761
SimpleKeyingInterface::Resynchronize
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Definition: cryptlib.h:783
StreamTransformation::MinLastBlockSize
virtual unsigned int MinLastBlockSize() const
Provides the size of the last block.
Definition: cryptlib.h:1021
StreamTransformation::ProcessData
virtual void ProcessData(byte *outString, const byte *inString, size_t length)=0
Encrypt or decrypt an array of bytes.
StreamTransformation::ProcessLastBlock
virtual size_t ProcessLastBlock(byte *outString, size_t outLength, const byte *inString, size_t inLength)
Encrypt or decrypt the last block of data.
StreamTransformation::OptimalDataAlignment
virtual unsigned int OptimalDataAlignment() const
Provides input and output data alignment for optimal performance.
StreamTransformation::ProcessString
void ProcessString(byte *inoutString, size_t length)
Encrypt or decrypt a string of bytes.
Definition: cryptlib.h:1060
StreamTransformation::MandatoryBlockSize
virtual unsigned int MandatoryBlockSize() const
Provides the mandatory block size of the cipher.
Definition: cryptlib.h:965
Unflushable
Base class for unflushable filters.
Definition: simple.h:134
member_ptr< PK_MessageAccumulator >
simple_ptr
Manages resources for a single object.
Definition: smartptr.h:19
config.h
Library configuration file.
word
word64 word
Full word used for multiprecision integer arithmetic.
Definition: config_int.h:182
word32
unsigned int word32
32-bit unsigned datatype
Definition: config_int.h:62
word16
unsigned short word16
16-bit unsigned datatype
Definition: config_int.h:59
dword
word128 dword
Double word used for multiprecision integer arithmetic.
Definition: config_int.h:193
word64
unsigned long long word64
64-bit unsigned datatype
Definition: config_int.h:91
lword
word64 lword
Large word type.
Definition: config_int.h:158
cryptlib.h
Abstract base classes that provide a uniform interface to this library.
LibraryVersion
int LibraryVersion(...)
Specifies the build-time version of the library.
DEFAULT_CHANNEL
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.h:511
g_nullNameValuePairs
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Definition: cryptlib.h:529
ByteOrder
ByteOrder
Provides the byte ordering.
Definition: cryptlib.h:143
BIG_ENDIAN_ORDER
@ BIG_ENDIAN_ORDER
byte order is big-endian
Definition: cryptlib.h:147
TheBitBucket
CRYPTOPP_DLL BufferedTransformation & TheBitBucket()
An input discarding BufferedTransformation.
NullRNG
CRYPTOPP_DLL RandomNumberGenerator & NullRNG()
Random Number Generator that does not produce random numbers.
AAD_CHANNEL
const std::string AAD_CHANNEL
Channel for additional authenticated data.
Definition: cryptlib.h:520
filters.h
Implementation of BufferedTransformation's attachment interface.
fips140.h
Classes and functions for the FIPS 140-2 validated library.
FIPS_140_2_ComplianceEnabled
CRYPTOPP_DLL bool FIPS_140_2_ComplianceEnabled()
Determines whether the library provides FIPS validated cryptography.
GetPowerUpSelfTestStatus
CRYPTOPP_DLL PowerUpSelfTestStatus GetPowerUpSelfTestStatus()
Provides the current power-up self test status.
POWER_UP_SELF_TEST_NOT_DONE
@ POWER_UP_SELF_TEST_NOT_DONE
The self tests have not been performed.
Definition: fips140.h:40
POWER_UP_SELF_TEST_FAILED
@ POWER_UP_SELF_TEST_FAILED
The self tests were executed via DoPowerUpSelfTest() or DoDllPowerUpSelfTest(), but the result was fa...
Definition: fips140.h:43
misc.h
Utility functions for the Crypto++ library.
BitPrecision
unsigned int BitPrecision(const T &value)
Returns the number of bits required for a value.
Definition: misc.h:842
Crop
T Crop(T value, size_t bits)
Truncates the value to the specified number of bits.
Definition: misc.h:926
CRYPTOPP_COMPILE_ASSERT
#define CRYPTOPP_COMPILE_ASSERT(expr)
Compile time assertion.
Definition: misc.h:151
IntToString
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:724
SafeConvert
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
Definition: misc.h:710
PtrAdd
PTR PtrAdd(PTR pointer, OFF offset)
Create a pointer with an offset.
Definition: misc.h:386
UnsignedMin
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be negative and incorrectly promoted.
Definition: misc.h:694
PutWord
void PutWord(bool assumeAligned, ByteOrder order, byte *block, T value, const byte *xorBlock=NULL)
Access a block of memory.
Definition: misc.h:2502
VerifyBufsEqual
CRYPTOPP_DLL bool VerifyBufsEqual(const byte *buf1, const byte *buf2, size_t count)
Performs a near constant-time comparison of two equally sized buffers.
xorbuf
CRYPTOPP_DLL void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
CryptoPP
Crypto++ library namespace.
Name::IV
const char * IV()
ConstByteArrayParameter, also accepts const byte * for backwards compatibility.
Definition: argnames.h:21
Name::Rounds
const char * Rounds()
int
Definition: argnames.h:24
osrng.h
Classes for access to the operating system's random number generators.
pch.h
Precompiled header file.
secblock.h
Classes and functions for secure memory allocations.
smartptr.h
Classes for automatic resource management.
stdcpp.h
Common C++ header files.
DecodingResult
Returns a decoding results.
Definition: cryptlib.h:278
CRYPTOPP_ASSERT
#define CRYPTOPP_ASSERT(exp)
Debugging and diagnostic assertion.
Definition: trap.h:68