3 #define _CRT_SECURE_NO_DEPRECATE
4 #define CRYPTOPP_DEFAULT_NO_DLL
5 #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
28 #ifdef CRYPTOPP_WIN32_AVAILABLE
32 #if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh)
33 #include <netinet/in.h>
34 #include <netinet/tcp.h>
37 #if (_MSC_VER >= 1000)
41 #if defined(__MWERKS__) && defined(macintosh)
46 #pragma comment(lib, "cryptlib_bds.lib")
47 #pragma comment(lib, "ws2_32.lib")
50 USING_NAMESPACE(CryptoPP)
53 const
int MAX_PHRASE_LENGTH=250;
55 void RegisterFactories();
57 void GenerateRSAKey(
unsigned int keyLength, const
char *privFilename, const
char *pubFilename, const
char *seed);
58 string RSAEncryptString(const
char *pubFilename, const
char *seed, const
char *message);
59 string RSADecryptString(const
char *privFilename, const
char *ciphertext);
60 void RSASignFile(const
char *privFilename, const
char *messageFilename, const
char *signatureFilename);
61 bool RSAVerifyFile(const
char *pubFilename, const
char *messageFilename, const
char *signatureFilename);
63 void DigestFile(const
char *file);
64 void HmacFile(const
char *hexKey, const
char *file);
66 void AES_CTR_Encrypt(const
char *hexKey, const
char *hexIV, const
char *infile, const
char *outfile);
68 string EncryptString(const
char *plaintext, const
char *passPhrase);
69 string DecryptString(const
char *ciphertext, const
char *passPhrase);
71 void EncryptFile(const
char *in, const
char *out, const
char *passPhrase);
72 void DecryptFile(const
char *in, const
char *out, const
char *passPhrase);
74 void SecretShareFile(
int threshold,
int nShares, const
char *filename, const
char *seed);
75 void SecretRecoverFile(
int threshold, const
char *outFilename,
char *const *inFilenames);
77 void InformationDisperseFile(
int threshold,
int nShares, const
char *filename);
78 void InformationRecoverFile(
int threshold, const
char *outFilename,
char *const *inFilenames);
80 void GzipFile(const
char *in, const
char *out,
int deflate_level);
81 void GunzipFile(const
char *in, const
char *out);
83 void Base64Encode(const
char *infile, const
char *outfile);
84 void Base64Decode(const
char *infile, const
char *outfile);
85 void HexEncode(const
char *infile, const
char *outfile);
86 void HexDecode(const
char *infile, const
char *outfile);
88 void ForwardTcpPort(const
char *sourcePort, const
char *destinationHost, const
char *destinationPort);
90 void FIPS140_SampleApplication();
91 void FIPS140_GenerateRandomFiles();
93 bool Validate(
int,
bool, const
char *);
95 int (*AdhocTest)(
int argc,
char *argv[]) = NULL;
104 int CRYPTOPP_API main(
int argc,
char *argv[])
106 #ifdef _CRTDBG_LEAK_CHECK_DF
108 int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
109 tempflag |= _CRTDBG_LEAK_CHECK_DF;
110 _CrtSetDbgFlag( tempflag );
113 #if defined(__MWERKS__) && defined(macintosh)
114 argc = ccommand(&argv);
121 std::string seed = IntToString(time(NULL));
123 s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());
125 std::string command, executableName, macFilename;
134 char seed[1024], privFilename[128], pubFilename[128];
135 unsigned int keyLength;
137 cout <<
"Key length in bits: ";
140 cout <<
"\nSave private key to file: ";
143 cout <<
"\nSave public key to file: ";
146 cout <<
"\nRandom Seed: ";
148 cin.getline(seed, 1024);
150 GenerateRSAKey(keyLength, privFilename, pubFilename, seed);
152 else if (command ==
"rs")
153 RSASignFile(argv[2], argv[3], argv[4]);
154 else if (command ==
"rv")
156 bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
157 cout << (verified ?
"valid signature" :
"invalid signature") << endl;
159 else if (command ==
"r")
161 char privFilename[128], pubFilename[128];
162 char seed[1024], message[1024];
164 cout <<
"Private key file: ";
167 cout <<
"\nPublic key file: ";
170 cout <<
"\nRandom Seed: ";
172 cin.getline(seed, 1024);
174 cout <<
"\nMessage: ";
175 cin.getline(message, 1024);
177 string ciphertext = RSAEncryptString(pubFilename, seed, message);
178 cout <<
"\nCiphertext: " << ciphertext << endl;
180 string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
181 cout <<
"\nDecrypted: " << decrypted << endl;
183 else if (command ==
"mt")
187 fs.TransferAllTo(mt);
188 cout <<
"Maurer Test Value: " << mt.GetTestValue() << endl;
190 else if (command ==
"mac_dll")
193 std::fstream dllFile(argv[2], ios::in | ios::out | ios::binary);
194 std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg();
195 if (fileEnd > 20*1000*1000)
197 cerr <<
"Input file too large (more than 20 MB).\n";
202 unsigned int fileSize = (
unsigned int)fileEnd;
204 dllFile.seekg(0, std::ios_base::beg);
205 dllFile.read((
char *)buf.begin(), fileSize);
208 word32 coffPos = *(word16 *)(buf+0x3c);
209 word32 optionalHeaderPos = coffPos + 24;
210 word16 optionalHeaderMagic = *(word16 *)(buf+optionalHeaderPos);
211 if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b)
213 cerr <<
"Target file is not a PE32 or PE32+ image.\n";
216 word32 checksumPos = optionalHeaderPos + 64;
217 word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144);
218 word32 certificateTablePos = *(word32 *)(buf+certificateTableDirectoryPos);
219 word32 certificateTableSize = *(word32 *)(buf+certificateTableDirectoryPos+4);
220 if (certificateTableSize != 0)
221 cerr <<
"Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n";
224 byte mac[] = CRYPTOPP_DUMMY_DLL_MAC;
225 byte *found = std::search(buf.begin(), buf.end(), mac+0, mac+
sizeof(mac));
226 if (found == buf.end())
228 cerr <<
"MAC placeholder not found. Possibly the actual MAC was already placed.\n";
231 word32 macPos = (
unsigned int)(found-buf.begin());
235 assert(pMac->DigestSize() ==
sizeof(mac));
237 f.AddRangeToSkip(0, checksumPos, 4);
238 f.AddRangeToSkip(0, certificateTableDirectoryPos, 8);
239 f.AddRangeToSkip(0, macPos,
sizeof(mac));
240 f.AddRangeToSkip(0, certificateTablePos, certificateTableSize);
241 f.PutMessageEnd(buf.begin(), buf.size());
244 cout <<
"Placing MAC in file " << argv[2] <<
", location " << macPos <<
".\n";
245 dllFile.seekg(macPos, std::ios_base::beg);
246 dllFile.write((
char *)mac,
sizeof(mac));
248 else if (command ==
"m")
250 else if (command ==
"tv")
252 std::string fname = argv[2];
253 if (fname.find(
".txt") == std::string::npos)
254 fname = PACKAGE_DATA_DIR
"TestVectors/" + fname +
".txt";
255 return !RunTestDataFile(fname.c_str());
257 else if (command ==
"t")
260 char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];
262 cout <<
"Passphrase: ";
263 cin.getline(passPhrase, MAX_PHRASE_LENGTH);
265 cout <<
"\nPlaintext: ";
266 cin.getline(plaintext, 1024);
268 string ciphertext = EncryptString(plaintext, passPhrase);
269 cout <<
"\nCiphertext: " << ciphertext << endl;
271 string decrypted = DecryptString(ciphertext.c_str(), passPhrase);
272 cout <<
"\nDecrypted: " << decrypted << endl;
276 else if (command ==
"e64")
277 Base64Encode(argv[2], argv[3]);
278 else if (command ==
"d64")
279 Base64Decode(argv[2], argv[3]);
280 else if (command ==
"e16")
281 HexEncode(argv[2], argv[3]);
282 else if (command ==
"d16")
283 HexDecode(argv[2], argv[3]);
284 else if (command ==
"e" || command ==
"d")
286 char passPhrase[MAX_PHRASE_LENGTH];
287 cout <<
"Passphrase: ";
288 cin.getline(passPhrase, MAX_PHRASE_LENGTH);
290 EncryptFile(argv[2], argv[3], passPhrase);
292 DecryptFile(argv[2], argv[3], passPhrase);
294 else if (command ==
"ss")
297 cout <<
"\nRandom Seed: ";
299 cin.getline(seed, 1024);
300 SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed);
302 else if (command ==
"sr")
303 SecretRecoverFile(argc-3, argv[2], argv+3);
304 else if (command ==
"id")
305 InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]);
306 else if (command ==
"ir")
307 InformationRecoverFile(argc-3, argv[2], argv+3);
308 else if (command ==
"v" || command ==
"vv")
309 return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] ==
'v', argc>3 ? argv[3] : NULL);
310 else if (command ==
"b")
311 BenchmarkAll(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9);
312 else if (command ==
"b2")
313 BenchmarkAll2(argc<3 ? 1 : atof(argv[2]), argc<4 ? 0 : atof(argv[3])*1e9);
314 else if (command ==
"z")
315 GzipFile(argv[3], argv[4], argv[2][0]-
'0');
316 else if (command ==
"u")
317 GunzipFile(argv[2], argv[3]);
318 else if (command ==
"fips")
319 FIPS140_SampleApplication();
320 else if (command ==
"fips-rand")
321 FIPS140_GenerateRandomFiles();
322 else if (command ==
"ft")
323 ForwardTcpPort(argv[2], argv[3], argv[4]);
324 else if (command ==
"a")
327 return (*AdhocTest)(argc, argv);
330 cerr <<
"AdhocTest not defined.\n";
334 else if (command ==
"hmac")
335 HmacFile(argv[2], argv[3]);
336 else if (command ==
"ae")
337 AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]);
338 else if (command ==
"h")
343 else if (command ==
"V")
345 cout << CRYPTOPP_VERSION / 100 <<
'.' << (CRYPTOPP_VERSION % 100) / 10 <<
'.' << CRYPTOPP_VERSION % 10 << endl;
349 cerr <<
"Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";
354 catch(CryptoPP::Exception &e)
356 cout <<
"\nCryptoPP::Exception caught: " << e.what() << endl;
359 catch(std::exception &e)
361 cout <<
"\nstd::exception caught: " << e.what() << endl;
366 void FIPS140_GenerateRandomFiles()
368 #ifdef OS_RNG_AVAILABLE
372 for (
unsigned int i=0; i<100000; i++)
373 store.TransferTo(
FileSink((IntToString(i) +
".rnd").c_str()).Ref(), 20000);
375 cout <<
"OS provided RNG not available.\n";
384 ss.Get(result, result.size());
388 void GenerateRSAKey(
unsigned int keyLength,
const char *privFilename,
const char *pubFilename,
const char *seed)
395 priv.DEREncode(privFile);
396 privFile.MessageEnd();
400 pub.DEREncode(pubFile);
401 pubFile.MessageEnd();
404 string RSAEncryptString(
const char *pubFilename,
const char *seed,
const char *message)
417 string RSADecryptString(
const char *privFilename,
const char *ciphertext)
427 void RSASignFile(
const char *privFilename,
const char *messageFilename,
const char *signatureFilename)
434 bool RSAVerifyFile(
const char *pubFilename,
const char *messageFilename,
const char *signatureFilename)
440 if (signatureFile.MaxRetrievable() != pub.SignatureLength())
443 signatureFile.Get(signature, signature.size());
446 verifierFilter->
Put(signature, pub.SignatureLength());
447 FileSource f(messageFilename,
true, verifierFilter);
449 return verifierFilter->GetLastResult();
452 void DigestFile(
const char *filename)
470 for (i=0; i<filters.size(); i++)
471 channelSwitch->AddDefaultRoute(*filters[i]);
472 FileSource(filename,
true, channelSwitch.release());
475 for (i=0; i<filters.size(); i++)
477 cout << filters[i]->AlgorithmName() <<
": ";
478 filters[i]->TransferTo(encoder);
483 void HmacFile(
const char *hexKey,
const char *file)
486 if (strcmp(hexKey,
"selftest") == 0)
488 cerr <<
"Computing HMAC/SHA1 value for self test.\n";
489 mac.reset(NewIntegrityCheckingMAC());
493 std::string decodedKey;
495 mac.reset(
new HMAC<SHA1>((
const byte *)decodedKey.data(), decodedKey.size()));
500 void AES_CTR_Encrypt(
const char *hexKey,
const char *hexIV,
const char *infile,
const char *outfile)
508 string EncryptString(
const char *instr,
const char *passPhrase)
513 encryptor.Put((byte *)instr, strlen(instr));
514 encryptor.MessageEnd();
519 string DecryptString(
const char *instr,
const char *passPhrase)
524 decryptor.Put((byte *)instr, strlen(instr));
525 decryptor.MessageEnd();
530 void EncryptFile(
const char *in,
const char *out,
const char *passPhrase)
535 void DecryptFile(
const char *in,
const char *out,
const char *passPhrase)
540 void SecretShareFile(
int threshold,
int nShares,
const char *filename,
const char *seed)
542 assert(nShares<=1000);
552 for (
int i=0; i<nShares; i++)
554 char extension[5] =
".000";
555 extension[1]=
'0'+byte(i/100);
556 extension[2]=
'0'+byte((i/10)%10);
557 extension[3]=
'0'+byte(i%10);
558 fileSinks[i].reset(
new FileSink((
string(filename)+extension).c_str()));
560 channel = WordToString<word32>(i);
561 fileSinks[i]->Put((byte *)channel.data(), 4);
562 channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
568 void SecretRecoverFile(
int threshold,
const char *outFilename,
char *
const *inFilenames)
570 assert(threshold<=1000);
577 for (i=0; i<threshold; i++)
579 fileSources[i].reset(
new FileSource(inFilenames[i],
false));
580 fileSources[i]->Pump(4);
581 fileSources[i]->Get(channel, 4);
582 fileSources[i]->Attach(
new ChannelSwitch(recovery,
string((
char *)channel.begin(), 4)));
585 while (fileSources[0]->Pump(256))
586 for (i=1; i<threshold; i++)
587 fileSources[i]->Pump(256);
589 for (i=0; i<threshold; i++)
590 fileSources[i]->PumpAll();
593 void InformationDisperseFile(
int threshold,
int nShares,
const char *filename)
595 assert(nShares<=1000);
602 for (
int i=0; i<nShares; i++)
604 char extension[5] =
".000";
605 extension[1]=
'0'+byte(i/100);
606 extension[2]=
'0'+byte((i/10)%10);
607 extension[3]=
'0'+byte(i%10);
608 fileSinks[i].reset(
new FileSink((
string(filename)+extension).c_str()));
610 channel = WordToString<word32>(i);
611 fileSinks[i]->Put((byte *)channel.data(), 4);
612 channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
618 void InformationRecoverFile(
int threshold,
const char *outFilename,
char *
const *inFilenames)
620 assert(threshold<=1000);
627 for (i=0; i<threshold; i++)
629 fileSources[i].reset(
new FileSource(inFilenames[i],
false));
630 fileSources[i]->Pump(4);
631 fileSources[i]->Get(channel, 4);
632 fileSources[i]->Attach(
new ChannelSwitch(recovery,
string((
char *)channel.begin(), 4)));
635 while (fileSources[0]->Pump(256))
636 for (i=1; i<threshold; i++)
637 fileSources[i]->Pump(256);
639 for (i=0; i<threshold; i++)
640 fileSources[i]->PumpAll();
643 void GzipFile(
const char *in,
const char *out,
int deflate_level)
659 gunzip.SetAutoSignalPropagation(0);
665 cs->AddDefaultRoute(gunzip);
668 cs->AddDefaultRoute(comparison,
"1");
671 comparison.ChannelMessageSeriesEnd(
"0");
672 comparison.ChannelMessageSeriesEnd(
"1");
675 void GunzipFile(
const char *in,
const char *out)
680 void Base64Encode(
const char *in,
const char *out)
685 void Base64Decode(
const char *in,
const char *out)
690 void HexEncode(
const char *in,
const char *out)
695 void HexDecode(
const char *in,
const char *out)
700 void ForwardTcpPort(
const char *sourcePortName,
const char *destinationHost,
const char *destinationPortName)
702 #ifdef SOCKETS_AVAILABLE
705 Socket sockListen, sockSource, sockDestination;
711 sockListen.Bind(sourcePort);
712 setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY,
"\x01", 1);
714 cout <<
"Listing on port " << sourcePort <<
".\n";
717 sockListen.Accept(sockSource);
718 cout <<
"Connection accepted on port " << sourcePort <<
".\n";
719 sockListen.CloseSocket();
721 cout <<
"Making connection to " << destinationHost <<
", port " << destinationPort <<
".\n";
722 sockDestination.Create();
723 sockDestination.Connect(destinationHost, destinationPort);
725 cout <<
"Connection made to " << destinationHost <<
", starting to forward.\n";
732 while (!(in.SourceExhausted() && out.SourceExhausted()))
736 out.GetWaitObjects(waitObjects,
CallStack(
"ForwardTcpPort - out", NULL));
737 in.GetWaitObjects(waitObjects,
CallStack(
"ForwardTcpPort - in", NULL));
741 if (!out.SourceExhausted())
743 cout <<
"o" << flush;
745 if (out.SourceExhausted())
746 cout <<
"EOF received on source socket.\n";
749 if (!in.SourceExhausted())
751 cout <<
"i" << flush;
753 if (in.SourceExhausted())
754 cout <<
"EOF received on destination socket.\n";
758 cout <<
"Socket support was not enabled at compile time.\n";
763 bool Validate(
int alg,
bool thorough,
const char *seedInput)
767 std::string seed = seedInput ? std::string(seedInput) : IntToString(time(NULL));
770 cout <<
"Using seed: " << seed << endl << endl;
771 s_globalRNG.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());
775 case 0: result = ValidateAll(thorough);
break;
776 case 1: result = TestSettings();
break;
777 case 2: result = TestOS_RNG();
break;
778 case 3: result = ValidateMD5();
break;
779 case 4: result = ValidateSHA();
break;
780 case 5: result = ValidateDES();
break;
781 case 6: result = ValidateIDEA();
break;
782 case 7: result = ValidateARC4();
break;
783 case 8: result = ValidateRC5();
break;
784 case 9: result = ValidateBlowfish();
break;
786 case 11: result = ValidateThreeWay();
break;
787 case 12: result = ValidateBBS();
break;
788 case 13: result = ValidateDH();
break;
789 case 14: result = ValidateRSA();
break;
790 case 15: result = ValidateElGamal();
break;
791 case 16: result = ValidateDSA(thorough);
break;
793 case 18: result = ValidateSAFER();
break;
794 case 19: result = ValidateLUC();
break;
795 case 20: result = ValidateRabin();
break;
797 case 22: result = ValidateECP();
break;
798 case 23: result = ValidateEC2N();
break;
800 case 25: result = ValidateGOST();
break;
801 case 26: result = ValidateTiger();
break;
802 case 27: result = ValidateRIPEMD();
break;
803 case 28: result = ValidateHMAC();
break;
805 case 30: result = ValidateSHARK();
break;
806 case 32: result = ValidateLUC_DH();
break;
807 case 33: result = ValidateLUC_DL();
break;
808 case 34: result = ValidateSEAL();
break;
809 case 35: result = ValidateCAST();
break;
810 case 36: result = ValidateSquare();
break;
811 case 37: result = ValidateRC2();
break;
812 case 38: result = ValidateRC6();
break;
813 case 39: result = ValidateMARS();
break;
814 case 40: result = ValidateRW();
break;
815 case 41: result = ValidateMD2();
break;
816 case 42: result = ValidateNR();
break;
817 case 43: result = ValidateMQV();
break;
818 case 44: result = ValidateRijndael();
break;
819 case 45: result = ValidateTwofish();
break;
820 case 46: result = ValidateSerpent();
break;
821 case 47: result = ValidateCipherModes();
break;
822 case 48: result = ValidateCRC32();
break;
823 case 49: result = ValidateECDSA();
break;
824 case 50: result = ValidateXTR_DH();
break;
825 case 51: result = ValidateSKIPJACK();
break;
826 case 52: result = ValidateSHA2();
break;
827 case 53: result = ValidatePanama();
break;
828 case 54: result = ValidateAdler32();
break;
829 case 55: result = ValidateMD4();
break;
830 case 56: result = ValidatePBKDF();
break;
831 case 57: result = ValidateESIGN();
break;
832 case 58: result = ValidateDLIES();
break;
833 case 59: result = ValidateBaseCode();
break;
834 case 60: result = ValidateSHACAL2();
break;
835 case 61: result = ValidateCamellia();
break;
836 case 62: result = ValidateWhirlpool();
break;
837 case 63: result = ValidateTTMAC();
break;
838 case 64: result = ValidateSalsa();
break;
839 case 65: result = ValidateSosemanuk();
break;
840 case 66: result = ValidateVMAC();
break;
841 case 67: result = ValidateCCM();
break;
842 case 68: result = ValidateGCM();
break;
843 case 69: result = ValidateCMAC();
break;
844 default:
return false;
847 time_t endTime = time(NULL);
848 cout <<
"\nTest ended at " << asctime(localtime(&endTime));
849 cout <<
"Seed used was: " << seed << endl;