⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 datatest.cpp

📁 lots Elliptic curve cryptography codes. Use Visual c++ to compile
💻 CPP
📖 第 1 页 / 共 2 页
字号:
			ss.PumpAll();			for (int i=0; i<z.length(); i++)				assert(encrypted[i] == z[i]);		}*/		if (test != "EncryptXorDigest")			ciphertext = GetDecodedDatum(v, "Ciphertext");		else		{			ciphertextXorDigest = GetDecodedDatum(v, "CiphertextXorDigest");			xorDigest.append(encrypted, 0, 64);			for (size_t i=64; i<encrypted.size(); i++)				xorDigest[i%64] ^= encrypted[i];		}		if (test != "EncryptXorDigest" ? encrypted != ciphertext : xorDigest != ciphertextXorDigest)		{			std::cout << "incorrectly encrypted: ";			StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout)));			xx.Pump(256); xx.Flush(false);			std::cout << "\n";			SignalTestFailure();		}		std::string decrypted;		StringSource dd(encrypted, false, new StreamTransformationFilter(*decryptor, new StringSink(decrypted), StreamTransformationFilter::NO_PADDING));		dd.Pump(plaintext.size()/2 + 1);		dd.PumpAll();		if (decrypted != plaintext)		{			std::cout << "incorrectly decrypted: ";			StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout)));			xx.Pump(256); xx.Flush(false);			std::cout << "\n";			SignalTestFailure();		}	}	else	{		std::cout << "unexpected test name\n";		SignalTestError();	}}void TestAuthenticatedSymmetricCipher(TestData &v, const NameValuePairs &overrideParameters){	std::string type = GetRequiredDatum(v, "AlgorithmType");	std::string name = GetRequiredDatum(v, "Name");	std::string test = GetRequiredDatum(v, "Test");	std::string key = GetDecodedDatum(v, "Key");	std::string plaintext = GetOptionalDecodedDatum(v, "Plaintext");	std::string ciphertext = GetOptionalDecodedDatum(v, "Ciphertext");	std::string header = GetOptionalDecodedDatum(v, "Header");	std::string footer = GetOptionalDecodedDatum(v, "Footer");	std::string mac = GetOptionalDecodedDatum(v, "MAC");	TestDataNameValuePairs testDataPairs(v);	CombinedNameValuePairs pairs(overrideParameters, testDataPairs);	if (test == "Encrypt" || test == "EncryptXorDigest" || test == "NotVerify")	{		member_ptr<AuthenticatedSymmetricCipher> asc1, asc2;		asc1.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str()));		asc2.reset(ObjectFactoryRegistry<AuthenticatedSymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str()));		asc1->SetKey((const byte *)key.data(), key.size(), pairs);		asc2->SetKey((const byte *)key.data(), key.size(), pairs);		std::string encrypted, decrypted;		AuthenticatedEncryptionFilter ef(*asc1, new StringSink(encrypted));		bool macAtBegin = !mac.empty() && !GlobalRNG().GenerateBit();	// test both ways randomly		AuthenticatedDecryptionFilter df(*asc2, new StringSink(decrypted), macAtBegin ? AuthenticatedDecryptionFilter::MAC_AT_BEGIN : 0);		if (asc1->NeedsPrespecifiedDataLengths())		{			asc1->SpecifyDataLengths(header.size(), plaintext.size(), footer.size());			asc2->SpecifyDataLengths(header.size(), plaintext.size(), footer.size());		}		StringStore sh(header), sp(plaintext), sc(ciphertext), sf(footer), sm(mac);		if (macAtBegin)			sm.TransferTo(df);		sh.CopyTo(df, LWORD_MAX, AAD_CHANNEL);		sc.TransferTo(df);		sf.CopyTo(df, LWORD_MAX, AAD_CHANNEL);		if (!macAtBegin)			sm.TransferTo(df);		df.MessageEnd();		sh.TransferTo(ef, sh.MaxRetrievable()/2+1, AAD_CHANNEL);		sh.TransferTo(ef, LWORD_MAX, AAD_CHANNEL);		sp.TransferTo(ef, sp.MaxRetrievable()/2+1);		sp.TransferTo(ef);		sf.TransferTo(ef, sf.MaxRetrievable()/2+1, AAD_CHANNEL);		sf.TransferTo(ef, LWORD_MAX, AAD_CHANNEL);		ef.MessageEnd();		if (test == "Encrypt" && encrypted != ciphertext+mac)		{			std::cout << "incorrectly encrypted: ";			StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout)));			xx.Pump(256); xx.Flush(false);			std::cout << "\n";			SignalTestFailure();		}		if (test == "Encrypt" && decrypted != plaintext)		{			std::cout << "incorrectly decrypted: ";			StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout)));			xx.Pump(256); xx.Flush(false);			std::cout << "\n";			SignalTestFailure();		}		if (ciphertext.size()+mac.size()-plaintext.size() != asc1->DigestSize())		{			std::cout << "bad MAC size\n";			SignalTestFailure();		}		if (df.GetLastResult() != (test == "Encrypt"))		{			std::cout << "MAC incorrectly verified\n";			SignalTestFailure();		}	}	else	{		std::cout << "unexpected test name\n";		SignalTestError();	}}void TestDigestOrMAC(TestData &v, bool testDigest){	std::string name = GetRequiredDatum(v, "Name");	std::string test = GetRequiredDatum(v, "Test");	const char *digestName = testDigest ? "Digest" : "MAC";	member_ptr<MessageAuthenticationCode> mac;	member_ptr<HashTransformation> hash;	HashTransformation *pHash = NULL;	TestDataNameValuePairs pairs(v);	if (testDigest)	{		hash.reset(ObjectFactoryRegistry<HashTransformation>::Registry().CreateObject(name.c_str()));		pHash = hash.get();	}	else	{		mac.reset(ObjectFactoryRegistry<MessageAuthenticationCode>::Registry().CreateObject(name.c_str()));		pHash = mac.get();		std::string key = GetDecodedDatum(v, "Key");		mac->SetKey((const byte *)key.c_str(), key.size(), pairs);	}	if (test == "Verify" || test == "VerifyTruncated" || test == "NotVerify")	{		int digestSize = -1;		if (test == "VerifyTruncated")			pairs.GetIntValue(Name::DigestSize(), digestSize);		HashVerificationFilter verifierFilter(*pHash, NULL, HashVerificationFilter::HASH_AT_BEGIN, digestSize);		PutDecodedDatumInto(v, digestName, verifierFilter);		PutDecodedDatumInto(v, "Message", verifierFilter);		verifierFilter.MessageEnd();		if (verifierFilter.GetLastResult() == (test == "NotVerify"))			SignalTestFailure();	}	else	{		SignalTestError();		assert(false);	}}bool GetField(std::istream &is, std::string &name, std::string &value){	name.resize(0);		// GCC workaround: 2.95.3 doesn't have clear()	is >> name;	if (name.empty())		return false;	if (name[name.size()-1] != ':')	{		char c;		is >> skipws >> c;		if (c != ':')			SignalTestError();	}	else		name.erase(name.size()-1);	while (is.peek() == ' ')		is.ignore(1);	// VC60 workaround: getline bug	char buffer[128];	value.resize(0);	// GCC workaround: 2.95.3 doesn't have clear()	bool continueLine;	do	{		do		{			is.get(buffer, sizeof(buffer));			value += buffer;		}		while (buffer[0] != 0);		is.clear();		is.ignore();		if (!value.empty() && value[value.size()-1] == '\r')			value.resize(value.size()-1);		if (!value.empty() && value[value.size()-1] == '\\')		{			value.resize(value.size()-1);			continueLine = true;		}		else			continueLine = false;		std::string::size_type i = value.find('#');		if (i != std::string::npos)			value.erase(i);	}	while (continueLine);	return true;}void OutputPair(const NameValuePairs &v, const char *name){	Integer x;	bool b = v.GetValue(name, x);	assert(b);	cout << name << ": \\\n    ";	x.Encode(HexEncoder(new FileSink(cout), false, 64, "\\\n    ").Ref(), x.MinEncodedSize());	cout << endl;}void OutputNameValuePairs(const NameValuePairs &v){	std::string names = v.GetValueNames();	string::size_type i = 0;	while (i < names.size())	{		string::size_type j = names.find_first_of (';', i);		if (j == string::npos)			return;		else		{			std::string name = names.substr(i, j-i);			if (name.find(':') == string::npos)				OutputPair(v, name.c_str());		}		i = j + 1;	}}void TestDataFile(const std::string &filename, const NameValuePairs &overrideParameters, unsigned int &totalTests, unsigned int &failedTests){	std::ifstream file(filename.c_str());	if (!file.good())		throw Exception(Exception::OTHER_ERROR, "Can not open file " + filename + " for reading");	TestData v;	s_currentTestData = &v;	std::string name, value, lastAlgName;	while (file)	{		while (file.peek() == '#')			file.ignore(INT_MAX, '\n');		if (file.peek() == '\n' || file.peek() == '\r')			v.clear();		if (!GetField(file, name, value))			break;		v[name] = value;		if (name == "Test")		{			bool failed = true;			std::string algType = GetRequiredDatum(v, "AlgorithmType");			if (lastAlgName != GetRequiredDatum(v, "Name"))			{				lastAlgName = GetRequiredDatum(v, "Name");				cout << "\nTesting " << algType.c_str() << " algorithm " << lastAlgName.c_str() << ".\n";			}			try			{				if (algType == "Signature")					TestSignatureScheme(v);				else if (algType == "SymmetricCipher")					TestSymmetricCipher(v, overrideParameters);				else if (algType == "AuthenticatedSymmetricCipher")					TestAuthenticatedSymmetricCipher(v, overrideParameters);				else if (algType == "AsymmetricCipher")					TestAsymmetricCipher(v);				else if (algType == "MessageDigest")					TestDigestOrMAC(v, true);				else if (algType == "MAC")					TestDigestOrMAC(v, false);				else if (algType == "FileList")					TestDataFile(GetRequiredDatum(v, "Test"), g_nullNameValuePairs, totalTests, failedTests);				else					SignalTestError();				failed = false;			}			catch (TestFailure &)			{				cout << "\nTest failed.\n";			}			catch (CryptoPP::Exception &e)			{				cout << "\nCryptoPP::Exception caught: " << e.what() << endl;			}			catch (std::exception &e)			{				cout << "\nstd::exception caught: " << e.what() << endl;			}			if (failed)			{				cout << "Skipping to next test.\n";				failedTests++;			}			else				cout << "." << flush;			totalTests++;		}	}}bool RunTestDataFile(const char *filename, const NameValuePairs &overrideParameters){	unsigned int totalTests = 0, failedTests = 0;	TestDataFile(filename, overrideParameters, totalTests, failedTests);	cout << "\nTests complete. Total tests = " << totalTests << ". Failed tests = " << failedTests << ".\n";	if (failedTests != 0)		cout << "SOME TESTS FAILED!\n";	return failedTests == 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -