3 #define CRYPTOPP_DEFAULT_NO_DLL 4 #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 22 #if (CRYPTOPP_MSC_VERSION >= 1410) 23 # pragma strict_gs_check (on) 26 #if defined(__COVERITY__) 27 extern "C" void __coverity_tainted_data_sanitize__(
void *);
34 static
bool s_thorough = false;
39 TestFailure() : Exception(OTHER_ERROR,
"Validation test failed") {}
42 static const TestData *s_currentTestData = NULL;
44 static void OutputTestData(
const TestData &v)
46 for (TestData::const_iterator i = v.begin(); i != v.end(); ++i)
48 cerr << i->first <<
": " << i->second << endl;
52 static void SignalTestFailure()
54 OutputTestData(*s_currentTestData);
58 static void SignalUnknownAlgorithmError(
const std::string& algType)
60 OutputTestData(*s_currentTestData);
64 static void SignalTestError()
66 OutputTestData(*s_currentTestData);
72 TestData::const_iterator i = data.find(name);
73 return (i != data.end());
78 TestData::const_iterator i = data.find(name);
91 len = source.
Get(buf+start, len);
113 repeat =
atoi(s1.c_str()+1);
114 s1 = s1.substr(s1.find(
' ')+1);
121 s2 = s1.substr(1, s1.find(
'\"', 1)-1);
122 s1 = s1.substr(
s2.length() + 2);
124 else if (s1.substr(0, 2) ==
"0x")
127 s1 = s1.substr(
STDMIN(s1.find(
' '), s1.length()));
132 s1 = s1.substr(
STDMIN(s1.find(
' '), s1.length()));
166 virtual bool GetVoidValue(
const char *
name,
const std::type_info &valueType,
void *pValue)
const 168 TestData::const_iterator i =
m_data.find(name);
171 if (std::string(name) == Name::DigestSize() && valueType ==
typeid(int))
175 i =
m_data.find(
"Digest");
181 *
reinterpret_cast<int *
>(pValue) = (
int)
m_temp.size();
188 const std::string &value = i->second;
190 if (valueType ==
typeid(
int))
191 *
reinterpret_cast<int *
>(pValue) =
atoi(value.c_str());
192 else if (valueType ==
typeid(
Integer))
193 *reinterpret_cast<Integer *>(pValue) =
Integer((std::string(value) +
"h").c_str());
237 if (test ==
"GenerateKey")
246 if (keyFormat ==
"DER")
248 else if (keyFormat ==
"Component")
251 if (test ==
"Verify" || test ==
"NotVerify")
261 else if (test ==
"PublicKeyValid")
268 if (keyFormat ==
"DER")
270 else if (keyFormat ==
"Component")
274 if (test ==
"GenerateKey" || test ==
"KeyPairValidAndConsistent")
278 verifierFilter.Put((
const byte *)
"abc", 3);
281 else if (test ==
"Sign")
287 else if (test ==
"DeterministicSign")
302 else if (test ==
"RandomSign")
324 if (keyFormat ==
"DER")
329 else if (keyFormat ==
"Component")
336 if (test ==
"DecryptMatch")
340 if (decrypted != expected)
343 else if (test ==
"KeyPairValidAndConsistent")
365 if (test ==
"Encrypt" || test ==
"EncryptXorDigest" || test ==
"Resync" || test ==
"EncryptionMCT" || test ==
"DecryptionMCT")
368 static std::string lastName;
370 if (name != lastName)
381 if (test ==
"Resync")
388 encryptor->
SetKey((
const byte *)key.data(), key.size(), pairs);
389 decryptor->
SetKey((
const byte *)key.data(), key.size(), pairs);
395 encryptor->
Seek(seek);
396 decryptor->
Seek(seek);
399 std::string encrypted, xorDigest, ciphertext, ciphertextXorDigest;
400 if (test ==
"EncryptionMCT" || test ==
"DecryptionMCT")
403 SecByteBlock buf((
byte *)plaintext.data(), plaintext.size()), keybuf((
byte *)key.data(), key.size());
405 if (test ==
"DecryptionMCT")
407 cipher = decryptor.
get();
409 buf.Assign((
byte *)ciphertext.data(), ciphertext.size());
412 for (
int i=0; i<400; i++)
414 encrypted.reserve(10000 * plaintext.size());
415 for (
int j=0; j<10000; j++)
418 encrypted.append((
char *)buf.begin(), buf.size());
421 encrypted.erase(0, encrypted.size() - keybuf.size());
422 xorbuf(keybuf.begin(), (
const byte *)encrypted.data(), keybuf.size());
423 cipher->
SetKey(keybuf, keybuf.size());
425 encrypted.assign((
char *)buf.begin(), buf.size());
426 ciphertext =
GetDecodedDatum(v, test ==
"EncryptionMCT" ?
"Ciphertext" :
"Plaintext");
427 if (encrypted != ciphertext)
429 std::cout <<
"incorrectly encrypted: ";
450 if (test !=
"EncryptXorDigest")
455 xorDigest.append(encrypted, 0, 64);
456 for (
size_t i=64; i<encrypted.size(); i++)
457 xorDigest[i%64] ^= encrypted[i];
459 if (test !=
"EncryptXorDigest" ? encrypted != ciphertext : xorDigest != ciphertextXorDigest)
461 std::cout <<
"incorrectly encrypted: ";
467 std::string decrypted;
471 if (decrypted != plaintext)
473 std::cout <<
"incorrectly decrypted: ";
482 std::cout <<
"unexpected test name\n";
503 if (test ==
"Encrypt" || test ==
"EncryptXorDigest" || test ==
"NotVerify")
508 asc1->
SetKey((
const byte *)key.data(), key.size(), pairs);
509 asc2->
SetKey((
const byte *)key.data(), key.size(), pairs);
511 std::string encrypted, decrypted;
522 StringStore sh(header), sp(plaintext), sc(ciphertext), sf(footer),
sm(mac);
538 if (test ==
"Encrypt" && encrypted != ciphertext+mac)
540 std::cout <<
"incorrectly encrypted: ";
546 if (test ==
"Encrypt" && decrypted != plaintext)
548 std::cout <<
"incorrectly decrypted: ";
555 if (ciphertext.size()+mac.size()-plaintext.size() != asc1->
DigestSize())
557 std::cout <<
"bad MAC size\n";
562 std::cout <<
"MAC incorrectly verified\n";
568 std::cout <<
"unexpected test name\n";
577 const char *digestName = testDigest ?
"Digest" :
"MAC";
595 mac->
SetKey((
const byte *)key.c_str(), key.size(), pairs);
598 if (test ==
"Verify" || test ==
"VerifyTruncated" || test ==
"NotVerify")
601 if (test ==
"VerifyTruncated")
622 if(test ==
"Skip")
return;
637 std::string calc; calc.resize(length);
638 unsigned int ret = kdf->
DeriveKey(reinterpret_cast<byte*>(&calc[0]), calc.size(),
639 reinterpret_cast<const byte*
>(key.data()), key.size(),
640 reinterpret_cast<const byte*
>(salt.data()), salt.size(),
641 reinterpret_cast<const byte*
>(info.data()), info.size());
643 if(calc != derived || ret != length)
655 if (name[name.size()-1] !=
':')
663 name.erase(name.size()-1);
665 while (is.peek() ==
' ')
671 bool continueLine, space =
false;
677 is.get(buffer,
sizeof(buffer));
679 if (buffer[0] ==
' ')
682 while (buffer[0] != 0);
686 if (!value.empty() && value[value.size()-1] ==
'\r')
687 value.resize(value.size()-1);
689 if (!value.empty() && value[value.size()-1] ==
'\\')
691 value.resize(value.size()-1);
695 continueLine =
false;
697 std::string::size_type i = value.find(
'#');
698 if (i != std::string::npos)
701 while (continueLine);
704 if (space && (name ==
"Modulus" || name ==
"SubgroupOrder" || name ==
"SubgroupGenerator" ||
705 name ==
"PublicElement" || name ==
"PrivateExponent" || name ==
"Signature"))
708 temp.reserve(value.size());
710 std::string::const_iterator it;
711 for(it = value.begin(); it != value.end(); it++)
728 cout << name <<
": \\\n ";
736 string::size_type i = 0;
737 while (i < names.size())
739 string::size_type j = names.find_first_of (
';', i);
741 if (j == string::npos)
745 std::string
name = names.substr(i, j-i);
746 if (name.find(
':') == string::npos)
757 if (!dataDirectory.empty())
759 if(dataDirectory != filename.substr(0, dataDirectory.length()))
760 filename.insert(0, dataDirectory);
763 std::ifstream file(filename.c_str());
767 s_currentTestData = &v;
768 std::string
name, value, lastAlgName;
772 while (file.peek() ==
'#')
775 if (file.peek() ==
'\n' || file.peek() ==
'\r')
782 if (name ==
"Test" && (s_thorough || v[
"SlowTest"] !=
"1"))
790 cout <<
"\nTesting " << algType.c_str() <<
" algorithm " << lastAlgName.c_str() <<
".\n";
795 if (algType ==
"Signature")
797 else if (algType ==
"SymmetricCipher")
799 else if (algType ==
"AuthenticatedSymmetricCipher")
801 else if (algType ==
"AsymmetricCipher")
803 else if (algType ==
"MessageDigest")
805 else if (algType ==
"MAC")
807 else if (algType ==
"KDF")
809 else if (algType ==
"FileList")
812 SignalUnknownAlgorithmError(algType);
817 cout <<
"\nTest failed.\n";
819 catch (
const CryptoPP::Exception &
e)
821 cout <<
"\nCryptoPP::Exception caught: " << e.what() << endl;
823 catch (
const std::exception &e)
825 cout <<
"\nstd::exception caught: " << e.what() << endl;
830 cout <<
"Skipping to next test.\n";
834 cout <<
"." << flush;
843 s_thorough = thorough;
844 unsigned int totalTests = 0, failedTests = 0;
845 TestDataFile((filename ? filename :
""), overrideParameters, totalTests, failedTests);
846 cout << dec <<
"\nTests complete. Total tests = " << totalTests <<
". Failed tests = " << failedTests <<
"." << endl;
847 if (failedTests != 0)
848 cout <<
"SOME TESTS FAILED!\n";
849 return failedTests == 0;
Used to pass byte array input as part of a NameValuePairs object.
Base class for all exceptions thrown by the library.
Append input to a string object.
virtual void AssignFrom(const NameValuePairs &source)=0
Assign values to this object.
virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
Indicates the hash is at the beginning of the message (i.e., concatenation of hash+message) ...
bool GetField(std::istream &is, std::string &name, std::string &value)
Filter wrapper for PK_Verifier.
virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms=g_nullNameValuePairs)
Sets or reset the key of this object.
void TestDataFile(std::string filename, const NameValuePairs &overrideParameters, unsigned int &totalTests, unsigned int &failedTests)
Class file for Randomness Pool.
void swap(dev::eth::Watch &_a, dev::eth::Watch &_b)
void Encode(byte *output, size_t outputLen, Signedness sign=UNSIGNED) const
Encode in big-endian format.
virtual void Load(BufferedTransformation &bt)
Loads a key from a BufferedTransformation.
virtual bool NeedsPrespecifiedDataLengths() const
Determines if data lengths must be specified prior to inputting data.
static const std::string s2("AAD")
bool GetLastResult() const
Converts given data to base 16.
Classes for HKDF from RFC 5869.
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL)
Generate a random 32 bit word in the range min to max, inclusive.
void OutputPair(const NameValuePairs &v, const char *name)
Decode base 16 data back to bytes.
virtual void Save(BufferedTransformation &bt) const
Saves a key to a BufferedTransformation.
Abstract base classes that provide a uniform interface to this library.
Thrown when an unexpected type is encountered.
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Private Key.
const std::string & GetRequiredDatum(const TestData &data, const char *name)
Some other error occurred not belonging to other categories.
RandomNumberGenerator & GlobalRNG()
Indicates the filter should throw a HashVerificationFailed if a failure is encountered.
std::string GetOptionalDecodedDatum(const TestData &data, const char *name)
Classes for automatic resource management.
Filter wrapper for PK_Signer.
size_t size() const
Length of the memory block.
std::hash for asio::adress
size_t MinEncodedSize(Signedness sign=UNSIGNED) const
Minimum number of bytes to encode this integer.
Combines two sets of NameValuePairs.
const byte * begin() const
Pointer to the first byte in the memory block.
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Private Key.
void TestAsymmetricCipher(TestData &v)
Pointer that overloads operator ->
TestDataNameValuePairs(const TestData &data)
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Classes for an unlimited queue to store bytes.
bool GetValue(const char *name, T &value) const
Get a named value.
bool GetLastResult() const
Filter wrapper for HashTransformation.
Filter wrapper for decrypting with AuthenticatedSymmetricCipher.
virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0
Check this object for errors.
Filter wrapper for encrypting with AuthenticatedSymmetricCipher.
CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
Get a named value with type int, with default.
virtual void Resynchronize(const byte *iv, int ivLength=-1)
Resynchronize with an IV.
Classes for HexEncoder and HexDecoder.
void PutDecodedDatumInto(const TestData &data, const char *name, BufferedTransformation &target)
void TestDigestOrMAC(TestData &v, bool testDigest)
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode...
Multiple precision integer with arithmetic operations.
h256 kdf(Secret const &_priv, h256 const &_hash)
Key derivation.
const std::string AAD_CHANNEL
Channel for additional authenticated data.
Filter wrapper for PK_Decryptor.
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
const CryptoMaterial & GetMaterial() const
Retrieves a reference to a Public Key.
lword Pump(lword pumpMax=(size_t) SIZE_MAX)
Pump data to attached transformation.
virtual PrivateKey & AccessPrivateKey()=0
Retrieves a reference to a Private Key.
Classes and functions for registering and locating library objects.
std::string GetDecodedDatum(const TestData &data, const char *name)
bool DataExists(const TestData &data, const char *name)
String-based implementation of Store interface.
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
#define CRYPTOPP_ASSERT(exp)
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
Redirect input to another BufferedTransformation without owning it.
void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
void TestKeyPairValidAndConsistent(CryptoMaterial &pub, const CryptoMaterial &priv)
Data structure used to store byte strings.
bool GetLastResult() const
Retrieves the result of the last verification.
void TestSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters)
void TestKeyDerivationFunction(TestData &v)
virtual unsigned int DeriveKey(byte *derived, size_t derivedLen, const byte *secret, size_t secretLen, const byte *salt, size_t saltLen, const byte *info=NULL, size_t infoLen=0) const =0
derive a key from secret
Implementation of BufferedTransformation's attachment interface.
#define USING_NAMESPACE(x)
void TestSignatureScheme(TestData &v)
CryptoMaterial & AccessMaterial()
Retrieves a reference to a Public Key.
virtual unsigned int GenerateBit()
Generate new random bit and return it.
PlatformStyle::TableColorType type
virtual PublicKey & AccessPublicKey()=0
Retrieves a reference to a Public Key.
#define CRYPTOPP_UNUSED(x)
Interface for crypto material, such as public and private keys, and crypto parameters.
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶ms=g_nullNameValuePairs)
Generate a random key or crypto parameters.
void TestAuthenticatedSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters)
std::map< std::string, std::string > TestData
Multiple precision integer with arithmetic operations.
void RandomizedTransfer(BufferedTransformation &source, BufferedTransformation &target, bool finish, const std::string &channel=DEFAULT_CHANNEL)
Classes providing file-based library services.
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
Prespecifies the data lengths.
No padding added to a block.
bool RunTestDataFile(const char *filename, const NameValuePairs &overrideParameters, bool thorough)
CRYPTOPP_DLL std::string GetValueNames() const
Get a list of value names that can be retrieved.
Indicates the signature is at the beginning of the message (i.e., concatenation of signature+message)...
void OutputNameValuePairs(const NameValuePairs &v)
Implementation of Store interface.
Indicates the MAC is at the beginning of the message (i.e., concatenation of mac+message) ...
#define CRYPTOPP_DATA_DIR
bool Flush(bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output, with signal propagation.
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
int atoi(const std::string &str)
Interface for retrieving values given their names.