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

📄 test.cpp

📁 lots Elliptic curve cryptography codes. Use Visual c++ to compile
💻 CPP
📖 第 1 页 / 共 2 页
字号:
// test.cpp - written and placed in the public domain by Wei Dai#define _CRT_SECURE_NO_DEPRECATE#define CRYPTOPP_DEFAULT_NO_DLL#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1#include "dll.h"#include "md5.h"#include "ripemd.h"#include "rng.h"#include "gzip.h"#include "default.h"#include "randpool.h"#include "ida.h"#include "base64.h"#include "socketft.h"#include "wait.h"#include "factory.h"#include "whrlpool.h"#include "tiger.h"#include "validate.h"#include "bench.h"#include <iostream>#include <time.h>#ifdef CRYPTOPP_WIN32_AVAILABLE#include <windows.h>#endif#if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh)#include <netinet/in.h>#include <netinet/tcp.h>#endif#if (_MSC_VER >= 1000)#include <crtdbg.h>		// for the debug heap#endif#if defined(__MWERKS__) && defined(macintosh)#include <console.h>#endif#ifdef __BORLANDC__#pragma comment(lib, "cryptlib_bds.lib")#pragma comment(lib, "ws2_32.lib")#endifUSING_NAMESPACE(CryptoPP)USING_NAMESPACE(std)const int MAX_PHRASE_LENGTH=250;void RegisterFactories();void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed);string RSAEncryptString(const char *pubFilename, const char *seed, const char *message);string RSADecryptString(const char *privFilename, const char *ciphertext);void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename);bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename);void DigestFile(const char *file);void HmacFile(const char *hexKey, const char *file);void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile);string EncryptString(const char *plaintext, const char *passPhrase);string DecryptString(const char *ciphertext, const char *passPhrase);void EncryptFile(const char *in, const char *out, const char *passPhrase);void DecryptFile(const char *in, const char *out, const char *passPhrase);void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed);void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);void InformationDisperseFile(int threshold, int nShares, const char *filename);void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);void GzipFile(const char *in, const char *out, int deflate_level);void GunzipFile(const char *in, const char *out);void Base64Encode(const char *infile, const char *outfile);void Base64Decode(const char *infile, const char *outfile);void HexEncode(const char *infile, const char *outfile);void HexDecode(const char *infile, const char *outfile);void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort);void FIPS140_SampleApplication();void FIPS140_GenerateRandomFiles();bool Validate(int, bool, const char *);int (*AdhocTest)(int argc, char *argv[]) = NULL;static OFB_Mode<AES>::Encryption s_globalRNG;RandomNumberGenerator & GlobalRNG(){	return s_globalRNG;}int CRYPTOPP_API main(int argc, char *argv[]){#ifdef _CRTDBG_LEAK_CHECK_DF	// Turn on leak-checking	int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );	tempflag |= _CRTDBG_LEAK_CHECK_DF;	_CrtSetDbgFlag( tempflag );#endif#if defined(__MWERKS__) && defined(macintosh)	argc = ccommand(&argv);#endif	try	{		RegisterFactories();		std::string seed = IntToString(time(NULL));		seed.resize(16);		s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());		std::string command, executableName, macFilename;		if (argc < 2)			command = 'h';		else			command = argv[1];		if (command == "g")		{			char seed[1024], privFilename[128], pubFilename[128];			unsigned int keyLength;			cout << "Key length in bits: ";			cin >> keyLength;			cout << "\nSave private key to file: ";			cin >> privFilename;			cout << "\nSave public key to file: ";			cin >> pubFilename;			cout << "\nRandom Seed: ";			ws(cin);			cin.getline(seed, 1024);			GenerateRSAKey(keyLength, privFilename, pubFilename, seed);		}		else if (command == "rs")			RSASignFile(argv[2], argv[3], argv[4]);		else if (command == "rv")		{			bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);			cout << (verified ? "valid signature" : "invalid signature") << endl;		}		else if (command == "r")		{			char privFilename[128], pubFilename[128];			char seed[1024], message[1024];			cout << "Private key file: ";			cin >> privFilename;			cout << "\nPublic key file: ";			cin >> pubFilename;			cout << "\nRandom Seed: ";			ws(cin);			cin.getline(seed, 1024);			cout << "\nMessage: ";			cin.getline(message, 1024);			string ciphertext = RSAEncryptString(pubFilename, seed, message);			cout << "\nCiphertext: " << ciphertext << endl;			string decrypted = RSADecryptString(privFilename, ciphertext.c_str());			cout << "\nDecrypted: " << decrypted << endl;		}		else if (command == "mt")		{			MaurerRandomnessTest mt;			FileStore fs(argv[2]);			fs.TransferAllTo(mt);			cout << "Maurer Test Value: " << mt.GetTestValue() << endl;		}		else if (command == "mac_dll")		{			// sanity check on file size			std::fstream dllFile(argv[2], ios::in | ios::out | ios::binary);			std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg();			if (fileEnd > 20*1000*1000)			{				cerr << "Input file too large (more than 20 MB).\n";				return 1;			}			// read file into memory			unsigned int fileSize = (unsigned int)fileEnd;			SecByteBlock buf(fileSize);			dllFile.seekg(0, std::ios_base::beg);			dllFile.read((char *)buf.begin(), fileSize);			// find positions of relevant sections in the file, based on version 8 of documentation from http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx			word32 coffPos = *(word16 *)(buf+0x3c);			word32 optionalHeaderPos = coffPos + 24;			word16 optionalHeaderMagic = *(word16 *)(buf+optionalHeaderPos);			if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b)			{				cerr << "Target file is not a PE32 or PE32+ image.\n";				return 3;			}			word32 checksumPos = optionalHeaderPos + 64;			word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144);			word32 certificateTablePos = *(word32 *)(buf+certificateTableDirectoryPos);			word32 certificateTableSize = *(word32 *)(buf+certificateTableDirectoryPos+4);			if (certificateTableSize != 0)				cerr << "Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n";			// find where to place computed MAC			byte mac[] = CRYPTOPP_DUMMY_DLL_MAC;			byte *found = std::search(buf.begin(), buf.end(), mac+0, mac+sizeof(mac));			if (found == buf.end())			{				cerr << "MAC placeholder not found. Possibly the actual MAC was already placed.\n";				return 2;			}			word32 macPos = (unsigned int)(found-buf.begin());			// compute MAC			member_ptr<MessageAuthenticationCode> pMac(NewIntegrityCheckingMAC());			assert(pMac->DigestSize() == sizeof(mac));			MeterFilter f(new HashFilter(*pMac, new ArraySink(mac, sizeof(mac))));			f.AddRangeToSkip(0, checksumPos, 4);			f.AddRangeToSkip(0, certificateTableDirectoryPos, 8);			f.AddRangeToSkip(0, macPos, sizeof(mac));			f.AddRangeToSkip(0, certificateTablePos, certificateTableSize);			f.PutMessageEnd(buf.begin(), buf.size());			// place MAC			cout << "Placing MAC in file " << argv[2] << ", location " << macPos << ".\n";			dllFile.seekg(macPos, std::ios_base::beg);			dllFile.write((char *)mac, sizeof(mac));		}		else if (command == "m")			DigestFile(argv[2]);		else if (command == "tv")		{			std::string fname = argv[2];			if (fname.find(".txt") == std::string::npos)				fname = "TestVectors/" + fname + ".txt";			return !RunTestDataFile(fname.c_str());		}		else if (command == "t")		{			// VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug			char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];			cout << "Passphrase: ";			cin.getline(passPhrase, MAX_PHRASE_LENGTH);			cout << "\nPlaintext: ";			cin.getline(plaintext, 1024);			string ciphertext = EncryptString(plaintext, passPhrase);			cout << "\nCiphertext: " << ciphertext << endl;			string decrypted = DecryptString(ciphertext.c_str(), passPhrase);			cout << "\nDecrypted: " << decrypted << endl;			return 0;		}		else if (command == "e64")			Base64Encode(argv[2], argv[3]);		else if (command == "d64")			Base64Decode(argv[2], argv[3]);		else if (command == "e16")			HexEncode(argv[2], argv[3]);		else if (command == "d16")			HexDecode(argv[2], argv[3]);		else if (command == "e" || command == "d")		{			char passPhrase[MAX_PHRASE_LENGTH];			cout << "Passphrase: ";			cin.getline(passPhrase, MAX_PHRASE_LENGTH);			if (command == "e")				EncryptFile(argv[2], argv[3], passPhrase);			else				DecryptFile(argv[2], argv[3], passPhrase);		}		else if (command == "ss")		{			char seed[1024];			cout << "\nRandom Seed: ";			ws(cin);			cin.getline(seed, 1024);			SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed);		}		else if (command == "sr")			SecretRecoverFile(argc-3, argv[2], argv+3);		else if (command == "id")			InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]);		else if (command == "ir")			InformationRecoverFile(argc-3, argv[2], argv+3);		else if (command == "v" || command == "vv")			return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL);		else if (command == "b")			BenchmarkAll(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9);		else if (command == "b2")			BenchmarkAll2(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9);		else if (command == "z")			GzipFile(argv[3], argv[4], argv[2][0]-'0');		else if (command == "u")			GunzipFile(argv[2], argv[3]);		else if (command == "fips")			FIPS140_SampleApplication();		else if (command == "fips-rand")			FIPS140_GenerateRandomFiles();		else if (command == "ft")			ForwardTcpPort(argv[2], argv[3], argv[4]);		else if (command == "a")		{			if (AdhocTest)				return (*AdhocTest)(argc, argv);			else			{				cerr << "AdhocTest not defined.\n";				return 1;			}		}		else if (command == "hmac")			HmacFile(argv[2], argv[3]);		else if (command == "ae")			AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]);		else if (command == "h")		{			FileSource usage("TestData/usage.dat", true, new FileSink(cout));			return 1;		}		else if (command == "V")		{			cout << CRYPTOPP_VERSION / 100 << '.' << (CRYPTOPP_VERSION % 100) / 10 << '.' << CRYPTOPP_VERSION % 10 << endl;		}		else		{			cerr << "Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";			return 1;		}		return 0;	}	catch(CryptoPP::Exception &e)	{		cout << "\nCryptoPP::Exception caught: " << e.what() << endl;		return -1;	}	catch(std::exception &e)	{		cout << "\nstd::exception caught: " << e.what() << endl;		return -2;	}}void FIPS140_GenerateRandomFiles(){#ifdef OS_RNG_AVAILABLE	DefaultAutoSeededRNG rng;	RandomNumberStore store(rng, ULONG_MAX);	for (unsigned int i=0; i<100000; i++)		store.TransferTo(FileSink((IntToString(i) + ".rnd").c_str()).Ref(), 20000);#else	cout << "OS provided RNG not available.\n";	exit(-1);#endif}SecByteBlock HexDecodeString(const char *hex){	StringSource ss(hex, true, new HexDecoder);	SecByteBlock result((size_t)ss.MaxRetrievable());	ss.Get(result, result.size());	return result;}void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed){	RandomPool randPool;	randPool.IncorporateEntropy((byte *)seed, strlen(seed));	RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);	HexEncoder privFile(new FileSink(privFilename));	priv.DEREncode(privFile);	privFile.MessageEnd();	RSAES_OAEP_SHA_Encryptor pub(priv);	HexEncoder pubFile(new FileSink(pubFilename));	pub.DEREncode(pubFile);	pubFile.MessageEnd();}string RSAEncryptString(const char *pubFilename, const char *seed, const char *message){	FileSource pubFile(pubFilename, true, new HexDecoder);	RSAES_OAEP_SHA_Encryptor pub(pubFile);	RandomPool randPool;	randPool.IncorporateEntropy((byte *)seed, strlen(seed));	string result;	StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(result))));	return result;}string RSADecryptString(const char *privFilename, const char *ciphertext){	FileSource privFile(privFilename, true, new HexDecoder);	RSAES_OAEP_SHA_Decryptor priv(privFile);	string result;	StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result))));	return result;}void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename)

⌨️ 快捷键说明

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