test.cpp

00001 // test.cpp - written and placed in the public domain by Wei Dai
00002 
00003 #define _CRT_SECURE_NO_DEPRECATE
00004 #define CRYPTOPP_DEFAULT_NO_DLL
00005 
00006 #include "dll.h"
00007 #include "md5.h"
00008 #include "ripemd.h"
00009 #include "rng.h"
00010 #include "gzip.h"
00011 #include "default.h"
00012 #include "randpool.h"
00013 #include "ida.h"
00014 #include "base64.h"
00015 #include "socketft.h"
00016 #include "wait.h"
00017 #include "factory.h"
00018 
00019 #include "validate.h"
00020 #include "bench.h"
00021 
00022 #include <iostream>
00023 #include <time.h>
00024 
00025 #ifdef CRYPTOPP_WIN32_AVAILABLE
00026 #include <windows.h>
00027 #endif
00028 
00029 #if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh)
00030 #include <netinet/in.h>
00031 #include <netinet/tcp.h>
00032 #endif
00033 
00034 #if (_MSC_VER >= 1000)
00035 #include <crtdbg.h>             // for the debug heap
00036 #endif
00037 
00038 #if defined(__MWERKS__) && defined(macintosh)
00039 #include <console.h>
00040 #endif
00041 
00042 #ifdef __BORLANDC__
00043 #pragma comment(lib, "cryptlib_bds.lib")
00044 #pragma comment(lib, "ws2_32.lib")
00045 #endif
00046 
00047 USING_NAMESPACE(CryptoPP)
00048 USING_NAMESPACE(std)
00049 
00050 const int MAX_PHRASE_LENGTH=250;
00051 
00052 void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed);
00053 string RSAEncryptString(const char *pubFilename, const char *seed, const char *message);
00054 string RSADecryptString(const char *privFilename, const char *ciphertext);
00055 void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename);
00056 bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename);
00057 
00058 void DigestFile(const char *file);
00059 void HmacFile(const char *hexKey, const char *file);
00060 
00061 void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile);
00062 
00063 string EncryptString(const char *plaintext, const char *passPhrase);
00064 string DecryptString(const char *ciphertext, const char *passPhrase);
00065 
00066 void EncryptFile(const char *in, const char *out, const char *passPhrase);
00067 void DecryptFile(const char *in, const char *out, const char *passPhrase);
00068 
00069 void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed);
00070 void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
00071 
00072 void InformationDisperseFile(int threshold, int nShares, const char *filename);
00073 void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
00074 
00075 void GzipFile(const char *in, const char *out, int deflate_level);
00076 void GunzipFile(const char *in, const char *out);
00077 
00078 void Base64Encode(const char *infile, const char *outfile);
00079 void Base64Decode(const char *infile, const char *outfile);
00080 void HexEncode(const char *infile, const char *outfile);
00081 void HexDecode(const char *infile, const char *outfile);
00082 
00083 void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort);
00084 
00085 void FIPS140_SampleApplication();
00086 void FIPS140_GenerateRandomFiles();
00087 
00088 bool Validate(int, bool, const char *);
00089 
00090 int (*AdhocTest)(int argc, char *argv[]) = NULL;
00091 
00092 int CRYPTOPP_API main(int argc, char *argv[])
00093 {
00094 #ifdef _CRTDBG_LEAK_CHECK_DF
00095         // Turn on leak-checking
00096         int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
00097         tempflag |= _CRTDBG_LEAK_CHECK_DF;
00098         _CrtSetDbgFlag( tempflag );
00099 #endif
00100 
00101 #if defined(__MWERKS__) && defined(macintosh)
00102         argc = ccommand(&argv);
00103 #endif
00104 
00105         try
00106         {
00107                 std::string command, executableName, macFilename;
00108 
00109                 if (argc < 2)
00110                         command = 'h';
00111                 else
00112                         command = argv[1];
00113 
00114                 if (command == "g")
00115                 {
00116                         char seed[1024], privFilename[128], pubFilename[128];
00117                         unsigned int keyLength;
00118 
00119                         cout << "Key length in bits: ";
00120                         cin >> keyLength;
00121 
00122                         cout << "\nSave private key to file: ";
00123                         cin >> privFilename;
00124 
00125                         cout << "\nSave public key to file: ";
00126                         cin >> pubFilename;
00127 
00128                         cout << "\nRandom Seed: ";
00129                         ws(cin);
00130                         cin.getline(seed, 1024);
00131 
00132                         GenerateRSAKey(keyLength, privFilename, pubFilename, seed);
00133                 }
00134                 else if (command == "rs")
00135                         RSASignFile(argv[2], argv[3], argv[4]);
00136                 else if (command == "rv")
00137                 {
00138                         bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
00139                         cout << (verified ? "valid signature" : "invalid signature") << endl;
00140                 }
00141                 else if (command == "r")
00142                 {
00143                         char privFilename[128], pubFilename[128];
00144                         char seed[1024], message[1024];
00145 
00146                         cout << "Private key file: ";
00147                         cin >> privFilename;
00148 
00149                         cout << "\nPublic key file: ";
00150                         cin >> pubFilename;
00151 
00152                         cout << "\nRandom Seed: ";
00153                         ws(cin);
00154                         cin.getline(seed, 1024);
00155 
00156                         cout << "\nMessage: ";
00157                         cin.getline(message, 1024);
00158 
00159                         string ciphertext = RSAEncryptString(pubFilename, seed, message);
00160                         cout << "\nCiphertext: " << ciphertext << endl;
00161 
00162                         string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
00163                         cout << "\nDecrypted: " << decrypted << endl;
00164                 }
00165                 else if (command == "mt")
00166                 {
00167                         MaurerRandomnessTest mt;
00168                         FileStore fs(argv[2]);
00169                         fs.TransferAllTo(mt);
00170                         cout << "Maurer Test Value: " << mt.GetTestValue() << endl;
00171                 }
00172                 else if (command == "mac_dll")
00173                 {
00174                         // sanity check on file size
00175                         std::fstream dllFile(argv[2], ios::in | ios::out | ios::binary);
00176                         std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg();
00177                         if (fileEnd > 20*1000*1000)
00178                         {
00179                                 cerr << "Input file too large (more than 20 MB).\n";
00180                                 return 1;
00181                         }
00182 
00183                         // read file into memory
00184                         unsigned int fileSize = (unsigned int)fileEnd;
00185                         SecByteBlock buf(fileSize);
00186                         dllFile.seekg(0, std::ios_base::beg);
00187                         dllFile.read((char *)buf.begin(), fileSize);
00188 
00189                         // 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
00190                         word32 coffPos = *(word16 *)(buf+0x3c);
00191                         word32 optionalHeaderPos = coffPos + 24;
00192                         word16 optionalHeaderMagic = *(word16 *)(buf+optionalHeaderPos);
00193                         if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b)
00194                         {
00195                                 cerr << "Target file is not a PE32 or PE32+ image.\n";
00196                                 return 3;
00197                         }
00198                         word32 checksumPos = optionalHeaderPos + 64;
00199                         word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144);
00200                         word32 certificateTablePos = *(word32 *)(buf+certificateTableDirectoryPos);
00201                         word32 certificateTableSize = *(word32 *)(buf+certificateTableDirectoryPos+4);
00202                         if (certificateTableSize != 0)
00203                                 cerr << "Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n";
00204 
00205                         // find where to place computed MAC
00206                         byte mac[] = CRYPTOPP_DUMMY_DLL_MAC;
00207                         byte *found = std::search(buf.begin(), buf.end(), mac+0, mac+sizeof(mac));
00208                         if (found == buf.end())
00209                         {
00210                                 cerr << "MAC placeholder not found. Possibly the actual MAC was already placed.\n";
00211                                 return 2;
00212                         }
00213                         word32 macPos = (unsigned int)(found-buf.begin());
00214 
00215                         // compute MAC
00216                         member_ptr<MessageAuthenticationCode> pMac(NewIntegrityCheckingMAC());
00217                         assert(pMac->DigestSize() == sizeof(mac));
00218                         MeterFilter f(new HashFilter(*pMac, new ArraySink(mac, sizeof(mac))));
00219                         f.AddRangeToSkip(0, checksumPos, 4);
00220                         f.AddRangeToSkip(0, certificateTableDirectoryPos, 8);
00221                         f.AddRangeToSkip(0, macPos, sizeof(mac));
00222                         f.AddRangeToSkip(0, certificateTablePos, certificateTableSize);
00223                         f.PutMessageEnd(buf.begin(), buf.size());
00224 
00225                         // place MAC
00226                         cout << "Placing MAC in file " << argv[2] << ", location " << macPos << ".\n";
00227                         dllFile.seekg(macPos, std::ios_base::beg);
00228                         dllFile.write((char *)mac, sizeof(mac));
00229                 }
00230                 else if (command == "m")
00231                         DigestFile(argv[2]);
00232                 else if (command == "tv")
00233                         return !RunTestDataFile(argv[2]);
00234                 else if (command == "t")
00235                 {
00236                         // VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug
00237                         char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];
00238 
00239                         cout << "Passphrase: ";
00240                         cin.getline(passPhrase, MAX_PHRASE_LENGTH);
00241 
00242                         cout << "\nPlaintext: ";
00243                         cin.getline(plaintext, 1024);
00244 
00245                         string ciphertext = EncryptString(plaintext, passPhrase);
00246                         cout << "\nCiphertext: " << ciphertext << endl;
00247 
00248                         string decrypted = DecryptString(ciphertext.c_str(), passPhrase);
00249                         cout << "\nDecrypted: " << decrypted << endl;
00250 
00251                         return 0;
00252                 }
00253                 else if (command == "e64")
00254                         Base64Encode(argv[2], argv[3]);
00255                 else if (command == "d64")
00256                         Base64Decode(argv[2], argv[3]);
00257                 else if (command == "e16")
00258                         HexEncode(argv[2], argv[3]);
00259                 else if (command == "d16")
00260                         HexDecode(argv[2], argv[3]);
00261                 else if (command == "e" || command == "d")
00262                 {
00263                         char passPhrase[MAX_PHRASE_LENGTH];
00264                         cout << "Passphrase: ";
00265                         cin.getline(passPhrase, MAX_PHRASE_LENGTH);
00266                         if (command == "e")
00267                                 EncryptFile(argv[2], argv[3], passPhrase);
00268                         else
00269                                 DecryptFile(argv[2], argv[3], passPhrase);
00270                 }
00271                 else if (command == "ss")
00272                 {
00273                         char seed[1024];
00274                         cout << "\nRandom Seed: ";
00275                         ws(cin);
00276                         cin.getline(seed, 1024);
00277                         SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed);
00278                 }
00279                 else if (command == "sr")
00280                         SecretRecoverFile(argc-3, argv[2], argv+3);
00281                 else if (command == "id")
00282                         InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]);
00283                 else if (command == "ir")
00284                         InformationRecoverFile(argc-3, argv[2], argv+3);
00285                 else if (command == "v")
00286                         return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL);
00287                 else if (command == "b")
00288                         BenchmarkAll(argc<3 ? 1 : atof(argv[2]));
00289                 else if (command == "b2")
00290                         BenchmarkAll2(argc<3 ? 1 : atof(argv[2]));
00291                 else if (command == "z")
00292                         GzipFile(argv[3], argv[4], argv[2][0]-'0');
00293                 else if (command == "u")
00294                         GunzipFile(argv[2], argv[3]);
00295                 else if (command == "fips")
00296                         FIPS140_SampleApplication();
00297                 else if (command == "fips-rand")
00298                         FIPS140_GenerateRandomFiles();
00299                 else if (command == "ft")
00300                         ForwardTcpPort(argv[2], argv[3], argv[4]);
00301                 else if (command == "a")
00302                 {
00303                         if (AdhocTest)
00304                                 return (*AdhocTest)(argc, argv);
00305                         else
00306                         {
00307                                 cerr << "AdhocTest not defined.\n";
00308                                 return 1;
00309                         }
00310                 }
00311                 else if (command == "hmac")
00312                         HmacFile(argv[2], argv[3]);
00313                 else if (command == "ae")
00314                         AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]);
00315                 else if (command == "h")
00316                 {
00317                         FileSource usage("usage.dat", true, new FileSink(cout));
00318                         return 1;
00319                 }
00320                 else if (command == "V")
00321                 {
00322                         cout << "5.4" << endl;
00323                 }
00324                 else
00325                 {
00326                         cerr << "Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";
00327                         return 1;
00328                 }
00329                 return 0;
00330         }
00331         catch(CryptoPP::Exception &e)
00332         {
00333                 cout << "\nCryptoPP::Exception caught: " << e.what() << endl;
00334                 return -1;
00335         }
00336         catch(std::exception &e)
00337         {
00338                 cout << "\nstd::exception caught: " << e.what() << endl;
00339                 return -2;
00340         }
00341 }
00342 
00343 void FIPS140_GenerateRandomFiles()
00344 {
00345 #ifdef OS_RNG_AVAILABLE
00346         AutoSeededX917RNG<DES_EDE3> rng;
00347         RandomNumberStore store(rng, ULONG_MAX);
00348 
00349         for (unsigned int i=0; i<100000; i++)
00350                 store.TransferTo(FileSink((IntToString(i) + ".rnd").c_str()).Ref(), 20000);
00351 #else
00352         cout << "OS provided RNG not available.\n";
00353         exit(-1);
00354 #endif
00355 }
00356 
00357 SecByteBlock HexDecodeString(const char *hex)
00358 {
00359         StringSource ss(hex, true, new HexDecoder);
00360         SecByteBlock result((size_t)ss.MaxRetrievable());
00361         ss.Get(result, result.size());
00362         return result;
00363 }
00364 
00365 RandomPool & GlobalRNG()
00366 {
00367         static RandomPool randomPool;
00368         return randomPool;
00369 }
00370 
00371 void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed)
00372 {
00373         RandomPool randPool;
00374         randPool.Put((byte *)seed, strlen(seed));
00375 
00376         RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);
00377         HexEncoder privFile(new FileSink(privFilename));
00378         priv.DEREncode(privFile);
00379         privFile.MessageEnd();
00380 
00381         RSAES_OAEP_SHA_Encryptor pub(priv);
00382         HexEncoder pubFile(new FileSink(pubFilename));
00383         pub.DEREncode(pubFile);
00384         pubFile.MessageEnd();
00385 }
00386 
00387 string RSAEncryptString(const char *pubFilename, const char *seed, const char *message)
00388 {
00389         FileSource pubFile(pubFilename, true, new HexDecoder);
00390         RSAES_OAEP_SHA_Encryptor pub(pubFile);
00391 
00392         RandomPool randPool;
00393         randPool.Put((byte *)seed, strlen(seed));
00394 
00395         string result;
00396         StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(result))));
00397         return result;
00398 }
00399 
00400 string RSADecryptString(const char *privFilename, const char *ciphertext)
00401 {
00402         FileSource privFile(privFilename, true, new HexDecoder);
00403         RSAES_OAEP_SHA_Decryptor priv(privFile);
00404 
00405         string result;
00406         StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result))));
00407         return result;
00408 }
00409 
00410 void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename)
00411 {
00412         FileSource privFile(privFilename, true, new HexDecoder);
00413         RSASS<PKCS1v15, SHA>::Signer priv(privFile);
00414         FileSource f(messageFilename, true, new SignerFilter(GlobalRNG(), priv, new HexEncoder(new FileSink(signatureFilename))));
00415 }
00416 
00417 bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename)
00418 {
00419         FileSource pubFile(pubFilename, true, new HexDecoder);
00420         RSASS<PKCS1v15, SHA>::Verifier pub(pubFile);
00421 
00422         FileSource signatureFile(signatureFilename, true, new HexDecoder);
00423         if (signatureFile.MaxRetrievable() != pub.SignatureLength())
00424                 return false;
00425         SecByteBlock signature(pub.SignatureLength());
00426         signatureFile.Get(signature, signature.size());
00427 
00428         VerifierFilter *verifierFilter = new VerifierFilter(pub);
00429         verifierFilter->Put(signature, pub.SignatureLength());
00430         FileSource f(messageFilename, true, verifierFilter);
00431 
00432         return verifierFilter->GetLastResult();
00433 }
00434 
00435 void DigestFile(const char *filename)
00436 {
00437         MD5 md5;
00438         SHA sha;
00439         RIPEMD160 ripemd;
00440         SHA256 sha256;
00441         HashFilter md5Filter(md5), shaFilter(sha), ripemdFilter(ripemd), sha256Filter(sha256);
00442 
00443         auto_ptr<ChannelSwitch> channelSwitch(new ChannelSwitch);
00444         channelSwitch->AddDefaultRoute(md5Filter);
00445         channelSwitch->AddDefaultRoute(shaFilter);
00446         channelSwitch->AddDefaultRoute(ripemdFilter);
00447         channelSwitch->AddDefaultRoute(sha256Filter);
00448         FileSource(filename, true, channelSwitch.release());
00449 
00450         HexEncoder encoder(new FileSink(cout), false);
00451         cout << "\nMD5: ";
00452         md5Filter.TransferTo(encoder);
00453         cout << "\nSHA-1: ";
00454         shaFilter.TransferTo(encoder);
00455         cout << "\nRIPEMD-160: ";
00456         ripemdFilter.TransferTo(encoder);
00457         cout << "\nSHA-256: ";
00458         sha256Filter.TransferTo(encoder);
00459 }
00460 
00461 void HmacFile(const char *hexKey, const char *file)
00462 {
00463         member_ptr<MessageAuthenticationCode> mac;
00464         if (strcmp(hexKey, "selftest") == 0)
00465         {
00466                 cerr << "Computing HMAC/SHA1 value for self test.\n";
00467                 mac.reset(NewIntegrityCheckingMAC());
00468         }
00469         else
00470         {
00471                 std::string decodedKey;
00472                 StringSource(hexKey, true, new HexDecoder(new StringSink(decodedKey)));
00473                 mac.reset(new HMAC<SHA1>((const byte *)decodedKey.data(), decodedKey.size()));
00474         }
00475         FileSource(file, true, new HashFilter(*mac, new HexEncoder(new FileSink(cout))));
00476 }
00477 
00478 void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile)
00479 {
00480         SecByteBlock key = HexDecodeString(hexKey);
00481         SecByteBlock iv = HexDecodeString(hexIV);
00482         CTR_Mode<AES>::Encryption aes(key, key.size(), iv);
00483         FileSource(infile, true, new StreamTransformationFilter(aes, new FileSink(outfile)));
00484 }
00485 
00486 string EncryptString(const char *instr, const char *passPhrase)
00487 {
00488         string outstr;
00489 
00490         DefaultEncryptorWithMAC encryptor(passPhrase, new HexEncoder(new StringSink(outstr)));
00491         encryptor.Put((byte *)instr, strlen(instr));
00492         encryptor.MessageEnd();
00493 
00494         return outstr;
00495 }
00496 
00497 string DecryptString(const char *instr, const char *passPhrase)
00498 {
00499         string outstr;
00500 
00501         HexDecoder decryptor(new DefaultDecryptorWithMAC(passPhrase, new StringSink(outstr)));
00502         decryptor.Put((byte *)instr, strlen(instr));
00503         decryptor.MessageEnd();
00504 
00505         return outstr;
00506 }
00507 
00508 void EncryptFile(const char *in, const char *out, const char *passPhrase)
00509 {
00510         FileSource f(in, true, new DefaultEncryptorWithMAC(passPhrase, new FileSink(out)));
00511 }
00512 
00513 void DecryptFile(const char *in, const char *out, const char *passPhrase)
00514 {
00515         FileSource f(in, true, new DefaultDecryptorWithMAC(passPhrase, new FileSink(out)));
00516 }
00517 
00518 void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed)
00519 {
00520         assert(nShares<=1000);
00521 
00522         RandomPool rng;
00523         rng.Put((byte *)seed, strlen(seed));
00524 
00525         ChannelSwitch *channelSwitch;
00526         FileSource source(filename, false, new SecretSharing(rng, threshold, nShares, channelSwitch = new ChannelSwitch));
00527 
00528         vector_member_ptrs<FileSink> fileSinks(nShares);
00529         string channel;
00530         for (int i=0; i<nShares; i++)
00531         {
00532                 char extension[5] = ".000";
00533                 extension[1]='0'+byte(i/100);
00534                 extension[2]='0'+byte((i/10)%10);
00535                 extension[3]='0'+byte(i%10);
00536                 fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
00537 
00538                 channel = WordToString<word32>(i);
00539                 fileSinks[i]->Put((byte *)channel.data(), 4);
00540                 channelSwitch->AddRoute(channel, *fileSinks[i], BufferedTransformation::NULL_CHANNEL);
00541         }
00542 
00543         source.PumpAll();
00544 }
00545 
00546 void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
00547 {
00548         assert(threshold<=1000);
00549 
00550         SecretRecovery recovery(threshold, new FileSink(outFilename));
00551 
00552         vector_member_ptrs<FileSource> fileSources(threshold);
00553         SecByteBlock channel(4);
00554         int i;
00555         for (i=0; i<threshold; i++)
00556         {
00557                 fileSources[i].reset(new FileSource(inFilenames[i], false));
00558                 fileSources[i]->Pump(4);
00559                 fileSources[i]->Get(channel, 4);
00560                 fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
00561         }
00562 
00563         while (fileSources[0]->Pump(256))
00564                 for (i=1; i<threshold; i++)
00565                         fileSources[i]->Pump(256);
00566 
00567         for (i=0; i<threshold; i++)
00568                 fileSources[i]->PumpAll();
00569 }
00570 
00571 void InformationDisperseFile(int threshold, int nShares, const char *filename)
00572 {
00573         assert(nShares<=1000);
00574 
00575         ChannelSwitch *channelSwitch;
00576         FileSource source(filename, false, new InformationDispersal(threshold, nShares, channelSwitch = new ChannelSwitch));
00577 
00578         vector_member_ptrs<FileSink> fileSinks(nShares);
00579         string channel;
00580         for (int i=0; i<nShares; i++)
00581         {
00582                 char extension[5] = ".000";
00583                 extension[1]='0'+byte(i/100);
00584                 extension[2]='0'+byte((i/10)%10);
00585                 extension[3]='0'+byte(i%10);
00586                 fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
00587 
00588                 channel = WordToString<word32>(i);
00589                 fileSinks[i]->Put((byte *)channel.data(), 4);
00590                 channelSwitch->AddRoute(channel, *fileSinks[i], BufferedTransformation::NULL_CHANNEL);
00591         }
00592 
00593         source.PumpAll();
00594 }
00595 
00596 void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
00597 {
00598         assert(threshold<=1000);
00599 
00600         InformationRecovery recovery(threshold, new FileSink(outFilename));
00601 
00602         vector_member_ptrs<FileSource> fileSources(threshold);
00603         SecByteBlock channel(4);
00604         int i;
00605         for (i=0; i<threshold; i++)
00606         {
00607                 fileSources[i].reset(new FileSource(inFilenames[i], false));
00608                 fileSources[i]->Pump(4);
00609                 fileSources[i]->Get(channel, 4);
00610                 fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
00611         }
00612 
00613         while (fileSources[0]->Pump(256))
00614                 for (i=1; i<threshold; i++)
00615                         fileSources[i]->Pump(256);
00616 
00617         for (i=0; i<threshold; i++)
00618                 fileSources[i]->PumpAll();
00619 }
00620 
00621 void GzipFile(const char *in, const char *out, int deflate_level)
00622 {
00623 //      FileSource(in, true, new Gzip(new FileSink(out), deflate_level));
00624 
00625         // use a filter graph to compare decompressed data with original
00626         //
00627         // Source ----> Gzip ------> Sink
00628         //    \           |
00629         //          \       Gunzip
00630         //                \       |
00631         //                  \     v
00632         //                    > ComparisonFilter 
00633                            
00634         EqualityComparisonFilter comparison;
00635 
00636         Gunzip gunzip(new ChannelSwitch(comparison, "0"));
00637         gunzip.SetAutoSignalPropagation(0);
00638 
00639         FileSink sink(out);
00640 
00641         ChannelSwitch *cs;
00642         Gzip gzip(cs = new ChannelSwitch(sink), deflate_level);
00643         cs->AddDefaultRoute(gunzip);
00644 
00645         cs = new ChannelSwitch(gzip);
00646         cs->AddDefaultRoute(comparison, "1");
00647         FileSource source(in, true, cs);
00648 
00649         comparison.ChannelMessageSeriesEnd("0");
00650         comparison.ChannelMessageSeriesEnd("1");
00651 }
00652 
00653 void GunzipFile(const char *in, const char *out)
00654 {
00655         FileSource(in, true, new Gunzip(new FileSink(out)));
00656 }
00657 
00658 void Base64Encode(const char *in, const char *out)
00659 {
00660         FileSource(in, true, new Base64Encoder(new FileSink(out)));
00661 }
00662 
00663 void Base64Decode(const char *in, const char *out)
00664 {
00665         FileSource(in, true, new Base64Decoder(new FileSink(out)));
00666 }
00667 
00668 void HexEncode(const char *in, const char *out)
00669 {
00670         FileSource(in, true, new HexEncoder(new FileSink(out)));
00671 }
00672 
00673 void HexDecode(const char *in, const char *out)
00674 {
00675         FileSource(in, true, new HexDecoder(new FileSink(out)));
00676 }
00677 
00678 void ForwardTcpPort(const char *sourcePortName, const char *destinationHost, const char *destinationPortName)
00679 {
00680 #ifdef SOCKETS_AVAILABLE
00681         SocketsInitializer sockInit;
00682 
00683         Socket sockListen, sockSource, sockDestination;
00684 
00685         int sourcePort = Socket::PortNameToNumber(sourcePortName);
00686         int destinationPort = Socket::PortNameToNumber(destinationPortName);
00687 
00688         sockListen.Create();
00689         sockListen.Bind(sourcePort);
00690         setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY, "\x01", 1);
00691 
00692         cout << "Listing on port " << sourcePort << ".\n";
00693         sockListen.Listen();
00694 
00695         sockListen.Accept(sockSource);
00696         cout << "Connection accepted on port " << sourcePort << ".\n";
00697         sockListen.CloseSocket();
00698 
00699         cout << "Making connection to " << destinationHost << ", port " << destinationPort << ".\n";
00700         sockDestination.Create();
00701         sockDestination.Connect(destinationHost, destinationPort);
00702 
00703         cout << "Connection made to " << destinationHost << ", starting to forward.\n";
00704 
00705         SocketSource out(sockSource, false, new SocketSink(sockDestination));
00706         SocketSource in(sockDestination, false, new SocketSink(sockSource));
00707 
00708         WaitObjectContainer waitObjects;
00709 
00710         while (!(in.SourceExhausted() && out.SourceExhausted()))
00711         {
00712                 waitObjects.Clear();
00713 
00714                 out.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - out", NULL));
00715                 in.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - in", NULL));
00716 
00717                 waitObjects.Wait(INFINITE_TIME);
00718 
00719                 if (!out.SourceExhausted())
00720                 {
00721                         cout << "o" << flush;
00722                         out.PumpAll2(false);
00723                         if (out.SourceExhausted())
00724                                 cout << "EOF received on source socket.\n";
00725                 }
00726 
00727                 if (!in.SourceExhausted())
00728                 {
00729                         cout << "i" << flush;
00730                         in.PumpAll2(false);
00731                         if (in.SourceExhausted())
00732                                 cout << "EOF received on destination socket.\n";
00733                 }
00734         }
00735 #else
00736         cout << "Socket support was not enabled at compile time.\n";
00737         exit(-1);
00738 #endif
00739 }
00740 
00741 bool Validate(int alg, bool thorough, const char *seed)
00742 {
00743         bool result;
00744 
00745         std::string timeSeed;
00746         if (!seed)
00747         {
00748                 timeSeed = IntToString(time(NULL));
00749                 seed = timeSeed.c_str();
00750         }
00751 
00752         cout << "Using seed: " << seed << endl << endl;
00753         GlobalRNG().Put((const byte *)seed, strlen(seed));
00754 
00755         switch (alg)
00756         {
00757         case 0: result = ValidateAll(thorough); break;
00758         case 1: result = TestSettings(); break;
00759         case 2: result = TestOS_RNG(); break;
00760         case 3: result = ValidateMD5(); break;
00761         case 4: result = ValidateSHA(); break;
00762         case 5: result = ValidateDES(); break;
00763         case 6: result = ValidateIDEA(); break;
00764         case 7: result = ValidateARC4(); break;
00765         case 8: result = ValidateRC5(); break;
00766         case 9: result = ValidateBlowfish(); break;
00767 //      case 10: result = ValidateDiamond2(); break;
00768         case 11: result = ValidateThreeWay(); break;
00769         case 12: result = ValidateBBS(); break;
00770         case 13: result = ValidateDH(); break;
00771         case 14: result = ValidateRSA(); break;
00772         case 15: result = ValidateElGamal(); break;
00773         case 16: result = ValidateDSA(thorough); break;
00774         case 17: result = ValidateHAVAL(); break;
00775         case 18: result = ValidateSAFER(); break;
00776         case 19: result = ValidateLUC(); break;
00777         case 20: result = ValidateRabin(); break;
00778 //      case 21: result = ValidateBlumGoldwasser(); break;
00779         case 22: result = ValidateECP(); break;
00780         case 23: result = ValidateEC2N(); break;
00781         case 24: result = ValidateMD5MAC(); break;
00782         case 25: result = ValidateGOST(); break;
00783         case 26: result = ValidateTiger(); break;
00784         case 27: result = ValidateRIPEMD(); break;
00785         case 28: result = ValidateHMAC(); break;
00786         case 29: result = ValidateXMACC(); break;
00787         case 30: result = ValidateSHARK(); break;
00788         case 32: result = ValidateLUC_DH(); break;
00789         case 33: result = ValidateLUC_DL(); break;
00790         case 34: result = ValidateSEAL(); break;
00791         case 35: result = ValidateCAST(); break;
00792         case 36: result = ValidateSquare(); break;
00793         case 37: result = ValidateRC2(); break;
00794         case 38: result = ValidateRC6(); break;
00795         case 39: result = ValidateMARS(); break;
00796         case 40: result = ValidateRW(); break;
00797         case 41: result = ValidateMD2(); break;
00798         case 42: result = ValidateNR(); break;
00799         case 43: result = ValidateMQV(); break;
00800         case 44: result = ValidateRijndael(); break;
00801         case 45: result = ValidateTwofish(); break;
00802         case 46: result = ValidateSerpent(); break;
00803         case 47: result = ValidateCipherModes(); break;
00804         case 48: result = ValidateCRC32(); break;
00805         case 49: result = ValidateECDSA(); break;
00806         case 50: result = ValidateXTR_DH(); break;
00807         case 51: result = ValidateSKIPJACK(); break;
00808         case 52: result = ValidateSHA2(); break;
00809         case 53: result = ValidatePanama(); break;
00810         case 54: result = ValidateAdler32(); break;
00811         case 55: result = ValidateMD4(); break;
00812         case 56: result = ValidatePBKDF(); break;
00813         case 57: result = ValidateESIGN(); break;
00814         case 58: result = ValidateDLIES(); break;
00815         case 59: result = ValidateBaseCode(); break;
00816         case 60: result = ValidateSHACAL2(); break;
00817         case 61: result = ValidateCamellia(); break;
00818         case 62: result = ValidateWhirlpool(); break;
00819         case 63: result = ValidateTTMAC(); break;
00820         case 64: result = ValidateSalsa(); break;
00821         default: return false;
00822         }
00823 
00824         time_t endTime = time(NULL);
00825         cout << "\nTest ended at " << asctime(localtime(&endTime));
00826         cout << "Seed used was: " << seed << endl;
00827 
00828         return result;
00829 }

Generated on Sat Dec 23 02:07:10 2006 for Crypto++ by  doxygen 1.5.1-p1