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 *);
33 typedef
std::map<
std::
string,
std::
string> TestData;
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 SignalTestError()
60 OutputTestData(*s_currentTestData);
64 bool DataExists(
const TestData &data,
const char *name)
66 TestData::const_iterator i = data.find(name);
67 return (i != data.end());
70 const std::string & GetRequiredDatum(
const TestData &data,
const char *name)
72 TestData::const_iterator i = data.find(name);
85 len = source.
Get(buf+start, len);
92 std::string s1 = GetRequiredDatum(data, name), s2;
107 repeat = atoi(s1.c_str()+1);
108 s1 = s1.substr(s1.find(
' ')+1);
115 s2 = s1.substr(1, s1.find(
'\"', 1)-1);
116 s1 = s1.substr(s2.length() + 2);
118 else if (s1.substr(0, 2) ==
"0x")
121 s1 = s1.substr(
STDMIN(s1.find(
' '), s1.length()));
126 s1 = s1.substr(
STDMIN(s1.find(
' '), s1.length()));
131 q.
Put((
const byte *)s2.data(), s2.size());
132 RandomizedTransfer(q, target,
false);
137 RandomizedTransfer(q, target,
true);
140 std::string GetDecodedDatum(
const TestData &data,
const char *name)
143 PutDecodedDatumInto(data, name,
StringSink(s).Ref());
147 std::string GetOptionalDecodedDatum(
const TestData &data,
const char *name)
150 if (DataExists(data, name))
151 PutDecodedDatumInto(data, name,
StringSink(s).Ref());
160 virtual bool GetVoidValue(
const char *name,
const std::type_info &valueType,
void *pValue)
const 162 TestData::const_iterator i = m_data.find(name);
163 if (i == m_data.end())
167 i = m_data.find(
"MAC");
168 if (i == m_data.end())
169 i = m_data.find(
"Digest");
170 if (i == m_data.end())
174 PutDecodedDatumInto(m_data, i->first.c_str(),
StringSink(m_temp).
Ref());
175 *
reinterpret_cast<int *
>(pValue) = (
int)m_temp.size();
182 const std::string &value = i->second;
184 if (valueType ==
typeid(
int))
185 *
reinterpret_cast<int *
>(pValue) = atoi(value.c_str());
186 else if (valueType ==
typeid(
Integer))
187 *reinterpret_cast<Integer *>(pValue) =
Integer((std::string(value) +
"h").c_str());
191 PutDecodedDatumInto(m_data, name,
StringSink(m_temp).Ref());
192 reinterpret_cast<ConstByteArrayParameter *
>(pValue)->Assign((
const byte *)m_temp.data(), m_temp.size(),
false);
201 const TestData &m_data;
202 mutable std::string m_temp;
208 if (!pub.
Validate(GlobalRNG(), 2U+!!s_thorough))
210 if (!priv.
Validate(GlobalRNG(), 2U+!!s_thorough))
221 void TestSignatureScheme(TestData &v)
223 std::string name = GetRequiredDatum(v,
"Name");
224 std::string test = GetRequiredDatum(v,
"Test");
231 if (test ==
"GenerateKey")
234 verifier->AccessPublicKey().
AssignFrom(signer->AccessPrivateKey());
238 std::string keyFormat = GetRequiredDatum(v,
"KeyFormat");
240 if (keyFormat ==
"DER")
242 else if (keyFormat ==
"Component")
245 if (test ==
"Verify" || test ==
"NotVerify")
247 VerifierFilter verifierFilter(*verifier, NULL, VerifierFilter::SIGNATURE_AT_BEGIN);
248 PutDecodedDatumInto(v,
"Signature", verifierFilter);
249 PutDecodedDatumInto(v,
"Message", verifierFilter);
251 if (verifierFilter.GetLastResult() == (test ==
"NotVerify"))
255 else if (test ==
"PublicKeyValid")
262 if (keyFormat ==
"DER")
264 else if (keyFormat ==
"Component")
268 if (test ==
"GenerateKey" || test ==
"KeyPairValidAndConsistent")
271 VerifierFilter verifierFilter(*verifier, NULL, VerifierFilter::THROW_EXCEPTION);
272 verifierFilter.Put((
const byte *)
"abc", 3);
275 else if (test ==
"Sign")
281 else if (test ==
"DeterministicSign")
286 else if (test ==
"RandomSign")
298 void TestAsymmetricCipher(TestData &v)
300 std::string name = GetRequiredDatum(v,
"Name");
301 std::string test = GetRequiredDatum(v,
"Test");
306 std::string keyFormat = GetRequiredDatum(v,
"KeyFormat");
308 if (keyFormat ==
"DER")
313 else if (keyFormat ==
"Component")
320 if (test ==
"DecryptMatch")
322 std::string decrypted, expected = GetDecodedDatum(v,
"Plaintext");
324 if (decrypted != expected)
327 else if (test ==
"KeyPairValidAndConsistent")
338 void TestSymmetricCipher(TestData &v,
const NameValuePairs &overrideParameters)
340 std::string name = GetRequiredDatum(v,
"Name");
341 std::string test = GetRequiredDatum(v,
"Test");
343 std::string key = GetDecodedDatum(v,
"Key");
344 std::string plaintext = GetDecodedDatum(v,
"Plaintext");
349 if (test ==
"Encrypt" || test ==
"EncryptXorDigest" || test ==
"Resync" || test ==
"EncryptionMCT" || test ==
"DecryptionMCT")
352 static std::string lastName;
354 if (name != lastName)
365 if (test ==
"Resync")
372 encryptor->
SetKey((
const byte *)key.data(), key.size(), pairs);
373 decryptor->
SetKey((
const byte *)key.data(), key.size(), pairs);
379 encryptor->
Seek(seek);
380 decryptor->
Seek(seek);
383 std::string encrypted, xorDigest, ciphertext, ciphertextXorDigest;
384 if (test ==
"EncryptionMCT" || test ==
"DecryptionMCT")
387 SecByteBlock buf((byte *)plaintext.data(), plaintext.size()), keybuf((byte *)key.data(), key.size());
389 if (test ==
"DecryptionMCT")
391 cipher = decryptor.get();
392 ciphertext = GetDecodedDatum(v,
"Ciphertext");
393 buf.Assign((byte *)ciphertext.data(), ciphertext.size());
396 for (
int i=0; i<400; i++)
398 encrypted.reserve(10000 * plaintext.size());
399 for (
int j=0; j<10000; j++)
402 encrypted.append((
char *)buf.begin(), buf.size());
405 encrypted.erase(0, encrypted.size() - keybuf.size());
406 xorbuf(keybuf.begin(), (
const byte *)encrypted.data(), keybuf.size());
407 cipher->
SetKey(keybuf, keybuf.size());
409 encrypted.assign((
char *)buf.begin(), buf.size());
410 ciphertext = GetDecodedDatum(v, test ==
"EncryptionMCT" ?
"Ciphertext" :
"Plaintext");
411 if (encrypted != ciphertext)
413 std::cout <<
"incorrectly encrypted: ";
415 xx.Pump(256); xx.
Flush(
false);
423 RandomizedTransfer(
StringStore(plaintext).Ref(), encFilter,
true);
434 if (test !=
"EncryptXorDigest")
435 ciphertext = GetDecodedDatum(v,
"Ciphertext");
438 ciphertextXorDigest = GetDecodedDatum(v,
"CiphertextXorDigest");
439 xorDigest.append(encrypted, 0, 64);
440 for (
size_t i=64; i<encrypted.size(); i++)
441 xorDigest[i%64] ^= encrypted[i];
443 if (test !=
"EncryptXorDigest" ? encrypted != ciphertext : xorDigest != ciphertextXorDigest)
445 std::cout <<
"incorrectly encrypted: ";
447 xx.Pump(2048); xx.
Flush(
false);
451 std::string decrypted;
453 RandomizedTransfer(
StringStore(encrypted).Ref(), decFilter,
true);
455 if (decrypted != plaintext)
457 std::cout <<
"incorrectly decrypted: ";
459 xx.Pump(256); xx.
Flush(
false);
466 std::cout <<
"unexpected test name\n";
471 void TestAuthenticatedSymmetricCipher(TestData &v,
const NameValuePairs &overrideParameters)
473 std::string type = GetRequiredDatum(v,
"AlgorithmType");
474 std::string name = GetRequiredDatum(v,
"Name");
475 std::string test = GetRequiredDatum(v,
"Test");
476 std::string key = GetDecodedDatum(v,
"Key");
478 std::string plaintext = GetOptionalDecodedDatum(v,
"Plaintext");
479 std::string ciphertext = GetOptionalDecodedDatum(v,
"Ciphertext");
480 std::string header = GetOptionalDecodedDatum(v,
"Header");
481 std::string footer = GetOptionalDecodedDatum(v,
"Footer");
482 std::string mac = GetOptionalDecodedDatum(v,
"MAC");
487 if (test ==
"Encrypt" || test ==
"EncryptXorDigest" || test ==
"NotVerify")
492 asc1->
SetKey((
const byte *)key.data(), key.size(), pairs);
493 asc2->
SetKey((
const byte *)key.data(), key.size(), pairs);
495 std::string encrypted, decrypted;
497 bool macAtBegin = !mac.empty() && !GlobalRNG().
GenerateBit();
506 StringStore sh(header), sp(plaintext), sc(ciphertext), sf(footer), sm(mac);
509 RandomizedTransfer(sm, df,
true);
511 RandomizedTransfer(sc, df,
true);
514 RandomizedTransfer(sm, df,
true);
518 RandomizedTransfer(sp, ef,
true);
522 if (test ==
"Encrypt" && encrypted != ciphertext+mac)
524 std::cout <<
"incorrectly encrypted: ";
526 xx.Pump(2048); xx.
Flush(
false);
530 if (test ==
"Encrypt" && decrypted != plaintext)
532 std::cout <<
"incorrectly decrypted: ";
534 xx.Pump(256); xx.
Flush(
false);
539 if (ciphertext.size()+mac.size()-plaintext.size() != asc1->
DigestSize())
541 std::cout <<
"bad MAC size\n";
544 if (df.GetLastResult() != (test ==
"Encrypt"))
546 std::cout <<
"MAC incorrectly verified\n";
552 std::cout <<
"unexpected test name\n";
557 void TestDigestOrMAC(TestData &v,
bool testDigest)
559 std::string name = GetRequiredDatum(v,
"Name");
560 std::string test = GetRequiredDatum(v,
"Test");
561 const char *digestName = testDigest ?
"Digest" :
"MAC";
578 std::string key = GetDecodedDatum(v,
"Key");
579 mac->
SetKey((
const byte *)key.c_str(), key.size(), pairs);
582 if (test ==
"Verify" || test ==
"VerifyTruncated" || test ==
"NotVerify")
585 if (test ==
"VerifyTruncated")
588 PutDecodedDatumInto(v, digestName, verifierFilter);
589 PutDecodedDatumInto(v,
"Message", verifierFilter);
591 if (verifierFilter.GetLastResult() == (test ==
"NotVerify"))
601 void TestKeyDerivationFunction(TestData &v)
603 std::string name = GetRequiredDatum(v,
"Name");
604 std::string test = GetRequiredDatum(v,
"Test");
606 if(test ==
"Skip")
return;
607 assert(test ==
"Verify");
609 std::string key = GetDecodedDatum(v,
"Key");
610 std::string salt = GetDecodedDatum(v,
"Salt");
611 std::string info = GetDecodedDatum(v,
"Info");
612 std::string derived = GetDecodedDatum(v,
"DerivedKey");
613 std::string t = GetDecodedDatum(v,
"DerivedKeyLength");
621 std::string calc; calc.resize(length);
622 unsigned int ret = kdf->
DeriveKey(reinterpret_cast<byte*>(&calc[0]), calc.size(),
623 reinterpret_cast<const byte*
>(key.data()), key.size(),
624 reinterpret_cast<const byte*
>(salt.data()), salt.size(),
625 reinterpret_cast<const byte*
>(info.data()), info.size());
627 if(calc != derived || ret != length)
631 bool GetField(std::istream &is, std::string &name, std::string &value)
636 #if defined(__COVERITY__) 644 if (name[name.size()-1] !=
':')
652 name.erase(name.size()-1);
654 while (is.peek() ==
' ')
666 is.get(buffer,
sizeof(buffer));
669 while (buffer[0] != 0);
673 if (!value.empty() && value[value.size()-1] ==
'\r')
674 value.resize(value.size()-1);
676 if (!value.empty() && value[value.size()-1] ==
'\\')
678 value.resize(value.size()-1);
682 continueLine =
false;
684 std::string::size_type i = value.find(
'#');
685 if (i != std::string::npos)
688 while (continueLine);
697 CRYPTOPP_UNUSED(b); assert(b);
698 cout << name <<
": \\\n ";
706 string::size_type i = 0;
707 while (i < names.size())
709 string::size_type j = names.find_first_of (
';', i);
711 if (j == string::npos)
715 std::string name = names.substr(i, j-i);
716 if (name.find(
':') == string::npos)
717 OutputPair(v, name.c_str());
724 void TestDataFile(
const std::string &filename,
const NameValuePairs &overrideParameters,
unsigned int &totalTests,
unsigned int &failedTests)
726 std::ifstream file(filename.c_str());
730 s_currentTestData = &v;
731 std::string name, value, lastAlgName;
735 while (file.peek() ==
'#')
736 file.ignore(std::numeric_limits<std::streamsize>::max(),
'\n');
738 if (file.peek() ==
'\n' || file.peek() ==
'\r')
741 if (!GetField(file, name, value))
745 if (name ==
"Test" && (s_thorough || v[
"SlowTest"] !=
"1"))
748 std::string algType = GetRequiredDatum(v,
"AlgorithmType");
750 if (lastAlgName != GetRequiredDatum(v,
"Name"))
752 lastAlgName = GetRequiredDatum(v,
"Name");
753 cout <<
"\nTesting " << algType.c_str() <<
" algorithm " << lastAlgName.c_str() <<
".\n";
758 if (algType ==
"Signature")
759 TestSignatureScheme(v);
760 else if (algType ==
"SymmetricCipher")
761 TestSymmetricCipher(v, overrideParameters);
762 else if (algType ==
"AuthenticatedSymmetricCipher")
763 TestAuthenticatedSymmetricCipher(v, overrideParameters);
764 else if (algType ==
"AsymmetricCipher")
765 TestAsymmetricCipher(v);
766 else if (algType ==
"MessageDigest")
767 TestDigestOrMAC(v,
true);
768 else if (algType ==
"MAC")
769 TestDigestOrMAC(v,
false);
770 else if (algType ==
"KDF")
771 TestKeyDerivationFunction(v);
772 else if (algType ==
"FileList")
780 cout <<
"\nTest failed.\n";
782 catch (CryptoPP::Exception &e)
784 cout <<
"\nCryptoPP::Exception caught: " << e.what() << endl;
786 catch (std::exception &e)
788 cout <<
"\nstd::exception caught: " << e.what() << endl;
793 cout <<
"Skipping to next test.\n";
797 cout <<
"." << flush;
804 bool RunTestDataFile(
const char *filename,
const NameValuePairs &overrideParameters,
bool thorough)
806 s_thorough = thorough;
807 unsigned int totalTests = 0, failedTests = 0;
808 TestDataFile(filename, overrideParameters, totalTests, failedTests);
809 cout << dec <<
"\nTests complete. Total tests = " << totalTests <<
". Failed tests = " << failedTests <<
".\n";
810 if (failedTests != 0)
811 cout <<
"SOME TESTS FAILED!\n";
812 return failedTests == 0;
used to pass byte array input as part of a NameValuePairs object
Base class for all exceptions thrown by Crypto++.
virtual void AssignFrom(const NameValuePairs &source)=0
Assign values to this object.
int GetIntValueWithDefault(const char *name, int defaultValue) const
Get a named value with type int, with default.
const char * DigestSize()
int, in bytes
Filter Wrapper for PK_Verifier.
virtual bool NeedsPrespecifiedDataLengths() const
if this function returns true, SpecifyDataLengths() must be called before attempting to input data ...
virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms=g_nullNameValuePairs)
Sets or reset the key of this object.
virtual void Load(BufferedTransformation &bt)
Loads a key from a BufferedTransformation.
Converts given data to base 16.
virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const
Get a named value.
const char * DerivedKeyLength()
int, key derivation, derived key length in bytes
virtual word32 GenerateWord32(word32 min=0, word32 max=0xffffffffUL)
Generate a random 32 bit word in the range min to max, inclusive.
Decode base 16 data back to bytes.
Abstract base classes that provide a uniform interface to this library.
Thrown when an unexpected type is encountered.
CryptoMaterial & AccessMaterial()
returns a reference to the crypto material used by this object
Some other error occurred not belong to any of the above categories.
Classes for automatic resource management.
Filter Wrapper for PK_Signer.
Append input to a string object.
SecByteBlock is a SecBlock<byte> typedef.
Pointer that overloads operator→
size_t MinEncodedSize(Signedness sign=UNSIGNED) const
The minimum number of bytes to encode this integer.
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
Classes for an unlimited queue to store bytes.
Filter Wrapper for HashTransformation.
Filter wrapper for decrypting with AuthenticatedSymmetricCipher, optionally handling padding/unpaddin...
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0
Check this object for errors.
Filter wrapper for encrypting with AuthenticatedSymmetricCipher, optionally handling padding/unpaddin...
virtual void Resynchronize(const byte *iv, int ivLength=-1)
resynchronize with an IV. ivLength=-1 means use IVSize()
Classes for HexEncoder and HexDecoder.
Interface for one direction (encryption or decryption) of a stream cipher or cipher mode...
Multiple precision integer with arithmetic operations.
proxy for the filter created by PK_Decryptor::CreateDecryptionFilter
const T1 UnsignedMin(const T1 &a, const T2 &b)
Safe comparison of values that could be neagtive and incorrectly promoted.
virtual unsigned int IVSize() const
Returns length of the IV accepted by this object.
const NameValuePairs & g_nullNameValuePairs
An empty set of name-value pairs.
string-based implementation of Store interface
const T & STDMIN(const T &a, const T &b)
Replacement function for std::min.
Redirect input to another BufferedTransformation without owning it.
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 in cryptlib.h.
const char * IV()
ConstByteArrayParameter, also accepts const byte * for backwards compatibility.
void Encode(byte *output, size_t outputLen, Signedness sign=UNSIGNED) const
Encode in big-endian format.
CryptoMaterial & AccessMaterial()
returns a reference to the crypto material used by this object
virtual unsigned int GenerateBit()
Generate new random bit and return it.
void xorbuf(byte *buf, const byte *mask, size_t count)
Performs an XOR of a buffer with a mask.
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 SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0)
this function only needs to be called if NeedsPrespecifiedDataLengths() returns true ...
No padding added to a block.
Crypto++ library namespace.
bool GetValue(const char *name, T &value) const
Get a named value.
const std::string AAD_CHANNEL
Channel for additional authenticated data.
virtual void Save(BufferedTransformation &bt) const
Saves a key to a BufferedTransformation.
file-based implementation of Sink interface
const CryptoMaterial & GetMaterial() const
returns a const reference to the crypto material used by this object
bool Flush(bool hardFlush, int propagation=-1, bool blocking=true)
Flush buffered input and/or output, with signal propagation.
std::string GetValueNames() const
Get a list of value names that can be retrieved.
Interface for retrieving values given their names.