Crypto++  5.6.3
Free C++ class library of cryptographic schemes
test.cpp
1 // test.cpp - written and placed in the public domain by Wei Dai
2 
3 #define CRYPTOPP_DEFAULT_NO_DLL
4 #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1
5 
6 #include "dll.h"
7 #include "aes.h"
8 #include "cryptlib.h"
9 #include "filters.h"
10 #include "md5.h"
11 #include "ripemd.h"
12 #include "rng.h"
13 #include "gzip.h"
14 #include "default.h"
15 #include "randpool.h"
16 #include "ida.h"
17 #include "base64.h"
18 #include "socketft.h"
19 #include "wait.h"
20 #include "factory.h"
21 #include "whrlpool.h"
22 #include "tiger.h"
23 #include "smartptr.h"
24 
25 #include "validate.h"
26 #include "bench.h"
27 
28 #include <algorithm>
29 #include <iostream>
30 #include <sstream>
31 #include <string>
32 #include <locale>
33 #include <time.h>
34 
35 #ifdef CRYPTOPP_WIN32_AVAILABLE
36 #define WIN32_LEAN_AND_MEAN
37 #include <windows.h>
38 #endif
39 
40 #if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh)
41 #include <netinet/in.h>
42 #include <netinet/tcp.h>
43 #endif
44 
45 #if (_MSC_VER >= 1000)
46 #include <crtdbg.h> // for the debug heap
47 #endif
48 
49 #if defined(__MWERKS__) && defined(macintosh)
50 #include <console.h>
51 #endif
52 
53 #ifdef _OPENMP
54 # include <omp.h>
55 #endif
56 
57 #ifdef __BORLANDC__
58 #pragma comment(lib, "cryptlib_bds.lib")
59 #pragma comment(lib, "ws2_32.lib")
60 #endif
61 
62 // Aggressive stack checking with VS2005 SP1 and above.
63 #if (CRYPTOPP_MSC_VERSION >= 1410)
64 # pragma strict_gs_check (on)
65 #endif
66 
67 // Quiet deprecated warnings intended to benefit users.
68 #if CRYPTOPP_MSC_VERSION
69 # pragma warning(disable: 4996)
70 #endif
71 
72 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE
73 # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
74 #endif
75 
76 USING_NAMESPACE(CryptoPP)
77 USING_NAMESPACE(std)
78 
79 const int MAX_PHRASE_LENGTH=250;
80 
81 void RegisterFactories();
82 void PrintSeedAndThreads(const std::string& seed);
83 
84 void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed);
85 string RSAEncryptString(const char *pubFilename, const char *seed, const char *message);
86 string RSADecryptString(const char *privFilename, const char *ciphertext);
87 void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename);
88 bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename);
89 
90 void DigestFile(const char *file);
91 void HmacFile(const char *hexKey, const char *file);
92 
93 void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile);
94 
95 string EncryptString(const char *plaintext, const char *passPhrase);
96 string DecryptString(const char *ciphertext, const char *passPhrase);
97 
98 void EncryptFile(const char *in, const char *out, const char *passPhrase);
99 void DecryptFile(const char *in, const char *out, const char *passPhrase);
100 
101 void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed);
102 void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
103 
104 void InformationDisperseFile(int threshold, int nShares, const char *filename);
105 void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
106 
107 void GzipFile(const char *in, const char *out, int deflate_level);
108 void GunzipFile(const char *in, const char *out);
109 
110 void Base64Encode(const char *infile, const char *outfile);
111 void Base64Decode(const char *infile, const char *outfile);
112 void HexEncode(const char *infile, const char *outfile);
113 void HexDecode(const char *infile, const char *outfile);
114 
115 void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort);
116 
117 void FIPS140_SampleApplication();
118 void FIPS140_GenerateRandomFiles();
119 
120 bool Validate(int, bool, const char *);
121 void PrintSeedAndThreads(const std::string& seed);
122 
123 int (*AdhocTest)(int argc, char *argv[]) = NULL;
124 
125 RandomNumberGenerator & GlobalRNG()
126 {
127  static OFB_Mode<AES>::Encryption s_globalRNG;
128  return dynamic_cast<RandomNumberGenerator&>(s_globalRNG);
129 }
130 
131 int CRYPTOPP_API main(int argc, char *argv[])
132 {
133 #ifdef _CRTDBG_LEAK_CHECK_DF
134  // Turn on leak-checking
135  int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
136  tempflag |= _CRTDBG_LEAK_CHECK_DF;
137  _CrtSetDbgFlag( tempflag );
138 #endif
139 
140 #if defined(__MWERKS__) && defined(macintosh)
141  argc = ccommand(&argv);
142 #endif
143 
144  try
145  {
146  RegisterFactories();
147 
148  // Some editors have problems with the '\0' character when redirecting output.
149  std::string seed = IntToString(time(NULL));
150  seed.resize(16, ' ');
151 
152  OFB_Mode<AES>::Encryption& prng = dynamic_cast<OFB_Mode<AES>::Encryption&>(GlobalRNG());
153  prng.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());
154 
155  std::string command, executableName, macFilename;
156 
157  if (argc < 2)
158  command = 'h';
159  else
160  command = argv[1];
161 
162  if (command == "g")
163  {
164  char thisSeed[1024], privFilename[128], pubFilename[128];
165  unsigned int keyLength;
166 
167  cout << "Key length in bits: ";
168  cin >> keyLength;
169 
170  cout << "\nSave private key to file: ";
171  cin >> privFilename;
172 
173  cout << "\nSave public key to file: ";
174  cin >> pubFilename;
175 
176  cout << "\nRandom Seed: ";
177  ws(cin);
178  cin.getline(thisSeed, 1024);
179 
180  GenerateRSAKey(keyLength, privFilename, pubFilename, thisSeed);
181  }
182  else if (command == "rs")
183  RSASignFile(argv[2], argv[3], argv[4]);
184  else if (command == "rv")
185  {
186  bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
187  cout << (verified ? "valid signature" : "invalid signature") << endl;
188  }
189  else if (command == "r")
190  {
191  char privFilename[128], pubFilename[128];
192  char thisSeed[1024], message[1024];
193 
194  cout << "Private key file: ";
195  cin >> privFilename;
196 
197  cout << "\nPublic key file: ";
198  cin >> pubFilename;
199 
200  cout << "\nRandom Seed: ";
201  ws(cin);
202  cin.getline(thisSeed, 1024);
203 
204  cout << "\nMessage: ";
205  cin.getline(message, 1024);
206 
207  string ciphertext = RSAEncryptString(pubFilename, thisSeed, message);
208  cout << "\nCiphertext: " << ciphertext << endl;
209 
210  string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
211  cout << "\nDecrypted: " << decrypted << endl;
212  }
213  else if (command == "mt")
214  {
216  FileStore fs(argv[2]);
217  fs.TransferAllTo(mt);
218  cout << "Maurer Test Value: " << mt.GetTestValue() << endl;
219  }
220  else if (command == "mac_dll")
221  {
222  std::string fname(argv[2] ? argv[2] : "");
223 
224  // sanity check on file size
225  std::fstream dllFile(fname.c_str(), ios::in | ios::out | ios::binary);
226  if (!dllFile.good())
227  {
228  cerr << "Failed to open file \"" << fname << "\"\n";
229  return 1;
230  }
231 
232  std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg();
233  if (fileEnd > 20*1000*1000)
234  {
235  cerr << "Input file " << fname << " is too large";
236  cerr << "(size is " << fileEnd << ").\n";
237  return 1;
238  }
239 
240  // read file into memory
241  unsigned int fileSize = (unsigned int)fileEnd;
242  SecByteBlock buf(fileSize);
243  dllFile.seekg(0, std::ios_base::beg);
244  dllFile.read((char *)buf.begin(), fileSize);
245 
246  // 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
247  word32 coffPos = *(word16 *)(void *)(buf+0x3c);
248  word32 optionalHeaderPos = coffPos + 24;
249  word16 optionalHeaderMagic = *(word16 *)(void *)(buf+optionalHeaderPos);
250  if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b)
251  {
252  cerr << "Target file is not a PE32 or PE32+ image.\n";
253  return 3;
254  }
255  word32 checksumPos = optionalHeaderPos + 64;
256  word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144);
257  word32 certificateTablePos = *(word32 *)(void *)(buf+certificateTableDirectoryPos);
258  word32 certificateTableSize = *(word32 *)(void *)(buf+certificateTableDirectoryPos+4);
259  if (certificateTableSize != 0)
260  cerr << "Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n";
261 
262  // find where to place computed MAC
263  byte mac[] = CRYPTOPP_DUMMY_DLL_MAC;
264  byte *found = std::search(buf.begin(), buf.end(), mac+0, mac+sizeof(mac));
265  if (found == buf.end())
266  {
267  cerr << "MAC placeholder not found. The MAC may already be placed.\n";
268  return 2;
269  }
270  word32 macPos = (unsigned int)(found-buf.begin());
271 
272  // compute MAC
274  assert(pMac->DigestSize() == sizeof(mac));
275  MeterFilter f(new HashFilter(*pMac, new ArraySink(mac, sizeof(mac))));
276  f.AddRangeToSkip(0, checksumPos, 4);
277  f.AddRangeToSkip(0, certificateTableDirectoryPos, 8);
278  f.AddRangeToSkip(0, macPos, sizeof(mac));
279  f.AddRangeToSkip(0, certificateTablePos, certificateTableSize);
280  f.PutMessageEnd(buf.begin(), buf.size());
281 
282  // place MAC
283  cout << "Placing MAC in file " << fname << ", location " << macPos;
284  cout << " (0x" << std::hex << macPos << std::dec << ").\n";
285  dllFile.seekg(macPos, std::ios_base::beg);
286  dllFile.write((char *)mac, sizeof(mac));
287  }
288  else if (command == "m")
289  DigestFile(argv[2]);
290  else if (command == "tv")
291  {
292  // TestDataFile() adds CRYPTOPP_DATA_DIR as required
293  std::string fname = (argv[2] ? argv[2] : "all");
294 #if defined(CRYPTOPP_USE_FIPS_202_SHA3)
295  if (fname == "sha3")
296  fname = "sha3_fips_202";
297  if (fname == "all")
298  fname = "all_fips_202";
299 #endif
300  if (fname.find(".txt") == std::string::npos)
301  fname = "TestVectors/" + fname + ".txt";
302 
303  PrintSeedAndThreads(seed);
304  return !RunTestDataFile(fname.c_str());
305  }
306  else if (command == "t")
307  {
308  // VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug
309  char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];
310 
311  cout << "Passphrase: ";
312  cin.getline(passPhrase, MAX_PHRASE_LENGTH);
313 
314  cout << "\nPlaintext: ";
315  cin.getline(plaintext, 1024);
316 
317  string ciphertext = EncryptString(plaintext, passPhrase);
318  cout << "\nCiphertext: " << ciphertext << endl;
319 
320  string decrypted = DecryptString(ciphertext.c_str(), passPhrase);
321  cout << "\nDecrypted: " << decrypted << endl;
322 
323  return 0;
324  }
325  else if (command == "e64")
326  Base64Encode(argv[2], argv[3]);
327  else if (command == "d64")
328  Base64Decode(argv[2], argv[3]);
329  else if (command == "e16")
330  HexEncode(argv[2], argv[3]);
331  else if (command == "d16")
332  HexDecode(argv[2], argv[3]);
333  else if (command == "e" || command == "d")
334  {
335  char passPhrase[MAX_PHRASE_LENGTH];
336  cout << "Passphrase: ";
337  cin.getline(passPhrase, MAX_PHRASE_LENGTH);
338  if (command == "e")
339  EncryptFile(argv[2], argv[3], passPhrase);
340  else
341  DecryptFile(argv[2], argv[3], passPhrase);
342  }
343  else if (command == "ss")
344  {
345  char thisSeed[1024];
346  cout << "\nRandom Seed: ";
347  ws(cin);
348  cin.getline(thisSeed, 1024);
349  SecretShareFile(StringToValue<int, true>(argv[2]), StringToValue<int, true>(argv[3]), argv[4], thisSeed);
350  }
351  else if (command == "sr")
352  SecretRecoverFile(argc-3, argv[2], argv+3);
353  else if (command == "id")
354  InformationDisperseFile(StringToValue<int, true>(argv[2]), StringToValue<int, true>(argv[3]), argv[4]);
355  else if (command == "ir")
356  InformationRecoverFile(argc-3, argv[2], argv+3);
357  else if (command == "v" || command == "vv")
358  return !Validate(argc>2 ? StringToValue<int, true>(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL);
359  else if (command == "b")
360  BenchmarkAll(argc<3 ? 1 : StringToValue<float, true>(argv[2]), argc<4 ? 0 : StringToValue<float, true>(argv[3])*1e9);
361  else if (command == "b2")
362  BenchmarkAll2(argc<3 ? 1 : StringToValue<float, true>(argv[2]), argc<4 ? 0 : StringToValue<float, true>(argv[3])*1e9);
363  else if (command == "z")
364  GzipFile(argv[3], argv[4], argv[2][0]-'0');
365  else if (command == "u")
366  GunzipFile(argv[2], argv[3]);
367  else if (command == "fips")
368  FIPS140_SampleApplication();
369  else if (command == "fips-rand")
370  FIPS140_GenerateRandomFiles();
371  else if (command == "ft")
372  ForwardTcpPort(argv[2], argv[3], argv[4]);
373  else if (command == "a")
374  {
375  if (AdhocTest)
376  return (*AdhocTest)(argc, argv);
377  else
378  {
379  cerr << "AdhocTest not defined.\n";
380  return 1;
381  }
382  }
383  else if (command == "hmac")
384  HmacFile(argv[2], argv[3]);
385  else if (command == "ae")
386  AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]);
387  else if (command == "h")
388  {
389  FileSource usage(CRYPTOPP_DATA_DIR "TestData/usage.dat", true, new FileSink(cout));
390  return 1;
391  }
392  else if (command == "V")
393  {
394  cout << CRYPTOPP_VERSION / 100 << '.' << (CRYPTOPP_VERSION % 100) / 10 << '.' << CRYPTOPP_VERSION % 10 << endl;
395  }
396  else
397  {
398  cerr << "Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";
399  return 1;
400  }
401  return 0;
402  }
403  catch(const CryptoPP::Exception &e)
404  {
405  cout << "\nCryptoPP::Exception caught: " << e.what() << endl;
406  return -1;
407  }
408  catch(const std::exception &e)
409  {
410  cout << "\nstd::exception caught: " << e.what() << endl;
411  return -2;
412  }
413 } // End main()
414 
415 void FIPS140_GenerateRandomFiles()
416 {
417 #ifdef OS_RNG_AVAILABLE
419  RandomNumberStore store(rng, ULONG_MAX);
420 
421  for (unsigned int i=0; i<100000; i++)
422  store.TransferTo(FileSink((IntToString(i) + ".rnd").c_str()).Ref(), 20000);
423 #else
424  cout << "OS provided RNG not available.\n";
425  exit(-1);
426 #endif
427 }
428 
429 template <class T, bool NON_NEGATIVE>
430 T StringToValue(const std::string& str) {
431  std::istringstream iss(str);
432  T value;
433  iss >> value;
434 
435  // Use fail(), not bad()
436  if (iss.fail())
437  throw InvalidArgument("cryptest.exe: '" + str +"' is not a value");
438 
439 #if NON_NEGATIVE
440  if (value < 0)
441  throw InvalidArgument("cryptest.exe: '" + str +"' is negative");
442 #endif
443 
444  return value;
445 }
446 
447 template<>
448 int StringToValue<int, true>(const std::string& str)
449 {
450  Integer n(str.c_str());
451  long l = n.ConvertToLong();
452 
453  int r;
454  if(!SafeConvert(l, r))
455  throw InvalidArgument("cryptest.exe: '" + str +"' is not an integer value");
456 
457  return r;
458 }
459 
460 void PrintSeedAndThreads(const std::string& seed)
461 {
462  cout << "Using seed: " << seed << endl;
463 
464 #ifdef _OPENMP
465  int tc = 0;
466  #pragma omp parallel
467  {
468  tc = omp_get_num_threads();
469  }
470 
471  std::cout << "Using " << tc << " OMP " << (tc == 1 ? "thread" : "threads") << std::endl;
472 #endif
473 }
474 
475 SecByteBlock HexDecodeString(const char *hex)
476 {
477  StringSource ss(hex, true, new HexDecoder);
478  SecByteBlock result((size_t)ss.MaxRetrievable());
479  ss.Get(result, result.size());
480  return result;
481 }
482 
483 void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed)
484 {
485  RandomPool randPool;
486  randPool.IncorporateEntropy((byte *)seed, strlen(seed));
487 
488  RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);
489  HexEncoder privFile(new FileSink(privFilename));
490  priv.DEREncode(privFile);
491  privFile.MessageEnd();
492 
493  RSAES_OAEP_SHA_Encryptor pub(priv);
494  HexEncoder pubFile(new FileSink(pubFilename));
495  pub.DEREncode(pubFile);
496  pubFile.MessageEnd();
497 }
498 
499 string RSAEncryptString(const char *pubFilename, const char *seed, const char *message)
500 {
501  FileSource pubFile(pubFilename, true, new HexDecoder);
502  RSAES_OAEP_SHA_Encryptor pub(pubFile);
503 
504  RandomPool randPool;
505  randPool.IncorporateEntropy((byte *)seed, strlen(seed));
506 
507  string result;
508  StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(result))));
509  return result;
510 }
511 
512 string RSADecryptString(const char *privFilename, const char *ciphertext)
513 {
514  FileSource privFile(privFilename, true, new HexDecoder);
515  RSAES_OAEP_SHA_Decryptor priv(privFile);
516 
517  string result;
518  StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result))));
519  return result;
520 }
521 
522 void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename)
523 {
524  FileSource privFile(privFilename, true, new HexDecoder);
525  RSASS<PKCS1v15, SHA>::Signer priv(privFile);
526  FileSource f(messageFilename, true, new SignerFilter(GlobalRNG(), priv, new HexEncoder(new FileSink(signatureFilename))));
527 }
528 
529 bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename)
530 {
531  FileSource pubFile(pubFilename, true, new HexDecoder);
532  RSASS<PKCS1v15, SHA>::Verifier pub(pubFile);
533 
534  FileSource signatureFile(signatureFilename, true, new HexDecoder);
535  if (signatureFile.MaxRetrievable() != pub.SignatureLength())
536  return false;
537  SecByteBlock signature(pub.SignatureLength());
538  signatureFile.Get(signature, signature.size());
539 
540  VerifierFilter *verifierFilter = new VerifierFilter(pub);
541  verifierFilter->Put(signature, pub.SignatureLength());
542  FileSource f(messageFilename, true, verifierFilter);
543 
544  return verifierFilter->GetLastResult();
545 }
546 
547 void DigestFile(const char *filename)
548 {
549  SHA1 sha;
550  RIPEMD160 ripemd;
551  SHA256 sha256;
552  Tiger tiger;
553  SHA512 sha512;
554  Whirlpool whirlpool;
556  filters[0].reset(new HashFilter(sha));
557  filters[1].reset(new HashFilter(ripemd));
558  filters[2].reset(new HashFilter(tiger));
559  filters[3].reset(new HashFilter(sha256));
560  filters[4].reset(new HashFilter(sha512));
561  filters[5].reset(new HashFilter(whirlpool));
562 
563  member_ptr<ChannelSwitch> channelSwitch(new ChannelSwitch);
564  size_t i;
565  for (i=0; i<filters.size(); i++)
566  channelSwitch->AddDefaultRoute(*filters[i]);
567  FileSource(filename, true, channelSwitch.release());
568 
569  HexEncoder encoder(new FileSink(cout), false);
570  for (i=0; i<filters.size(); i++)
571  {
572  cout << filters[i]->AlgorithmName() << ": ";
573  filters[i]->TransferTo(encoder);
574  cout << "\n";
575  }
576 }
577 
578 void HmacFile(const char *hexKey, const char *file)
579 {
581  if (strcmp(hexKey, "selftest") == 0)
582  {
583  cerr << "Computing HMAC/SHA1 value for self test.\n";
584  mac.reset(NewIntegrityCheckingMAC());
585  }
586  else
587  {
588  std::string decodedKey;
589  StringSource(hexKey, true, new HexDecoder(new StringSink(decodedKey)));
590  mac.reset(new HMAC<SHA1>((const byte *)decodedKey.data(), decodedKey.size()));
591  }
592  FileSource(file, true, new HashFilter(*mac, new HexEncoder(new FileSink(cout))));
593 }
594 
595 void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile)
596 {
597  SecByteBlock key = HexDecodeString(hexKey);
598  SecByteBlock iv = HexDecodeString(hexIV);
599  CTR_Mode<AES>::Encryption aes(key, key.size(), iv);
600  FileSource(infile, true, new StreamTransformationFilter(aes, new FileSink(outfile)));
601 }
602 
603 string EncryptString(const char *instr, const char *passPhrase)
604 {
605  string outstr;
606 
607  DefaultEncryptorWithMAC encryptor(passPhrase, new HexEncoder(new StringSink(outstr)));
608  encryptor.Put((byte *)instr, strlen(instr));
609  encryptor.MessageEnd();
610 
611  return outstr;
612 }
613 
614 string DecryptString(const char *instr, const char *passPhrase)
615 {
616  string outstr;
617 
618  HexDecoder decryptor(new DefaultDecryptorWithMAC(passPhrase, new StringSink(outstr)));
619  decryptor.Put((byte *)instr, strlen(instr));
620  decryptor.MessageEnd();
621 
622  return outstr;
623 }
624 
625 void EncryptFile(const char *in, const char *out, const char *passPhrase)
626 {
627  FileSource f(in, true, new DefaultEncryptorWithMAC(passPhrase, new FileSink(out)));
628 }
629 
630 void DecryptFile(const char *in, const char *out, const char *passPhrase)
631 {
632  FileSource f(in, true, new DefaultDecryptorWithMAC(passPhrase, new FileSink(out)));
633 }
634 
635 void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed)
636 {
637  assert(nShares >= 1 && nShares<=1000);
638  if (nShares < 1 || nShares > 1000)
639  throw InvalidArgument("SecretShareFile: " + IntToString(nShares) + " is not in range [1, 1000]");
640 
641  RandomPool rng;
642  rng.IncorporateEntropy((byte *)seed, strlen(seed));
643 
644  ChannelSwitch *channelSwitch = NULL;
645  FileSource source(filename, false, new SecretSharing(rng, threshold, nShares, channelSwitch = new ChannelSwitch));
646 
647  vector_member_ptrs<FileSink> fileSinks(nShares);
648  string channel;
649  for (int i=0; i<nShares; i++)
650  {
651  char extension[5] = ".000";
652  extension[1]='0'+byte(i/100);
653  extension[2]='0'+byte((i/10)%10);
654  extension[3]='0'+byte(i%10);
655  fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
656 
657  channel = WordToString<word32>(i);
658  fileSinks[i]->Put((const byte *)channel.data(), 4);
659  channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
660  }
661 
662  source.PumpAll();
663 }
664 
665 void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
666 {
667  assert(threshold >= 1 && threshold <=1000);
668  if (threshold < 1 || threshold > 1000)
669  throw InvalidArgument("SecretRecoverFile: " + IntToString(threshold) + " is not in range [1, 1000]");
670 
671  SecretRecovery recovery(threshold, new FileSink(outFilename));
672 
673  vector_member_ptrs<FileSource> fileSources(threshold);
674  SecByteBlock channel(4);
675  int i;
676  for (i=0; i<threshold; i++)
677  {
678  fileSources[i].reset(new FileSource(inFilenames[i], false));
679  fileSources[i]->Pump(4);
680  fileSources[i]->Get(channel, 4);
681  fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
682  }
683 
684  while (fileSources[0]->Pump(256))
685  for (i=1; i<threshold; i++)
686  fileSources[i]->Pump(256);
687 
688  for (i=0; i<threshold; i++)
689  fileSources[i]->PumpAll();
690 }
691 
692 void InformationDisperseFile(int threshold, int nShares, const char *filename)
693 {
694  assert(threshold >= 1 && threshold <=1000);
695  if (threshold < 1 || threshold > 1000)
696  throw InvalidArgument("InformationDisperseFile: " + IntToString(nShares) + " is not in range [1, 1000]");
697 
698  ChannelSwitch *channelSwitch = NULL;
699  FileSource source(filename, false, new InformationDispersal(threshold, nShares, channelSwitch = new ChannelSwitch));
700 
701  vector_member_ptrs<FileSink> fileSinks(nShares);
702  string channel;
703  for (int i=0; i<nShares; i++)
704  {
705  char extension[5] = ".000";
706  extension[1]='0'+byte(i/100);
707  extension[2]='0'+byte((i/10)%10);
708  extension[3]='0'+byte(i%10);
709  fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
710 
711  channel = WordToString<word32>(i);
712  fileSinks[i]->Put((const byte *)channel.data(), 4);
713  channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
714  }
715 
716  source.PumpAll();
717 }
718 
719 void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
720 {
721  assert(threshold<=1000);
722  if (threshold < 1 || threshold > 1000)
723  throw InvalidArgument("InformationRecoverFile: " + IntToString(threshold) + " is not in range [1, 1000]");
724 
725  InformationRecovery recovery(threshold, new FileSink(outFilename));
726 
727  vector_member_ptrs<FileSource> fileSources(threshold);
728  SecByteBlock channel(4);
729  int i;
730  for (i=0; i<threshold; i++)
731  {
732  fileSources[i].reset(new FileSource(inFilenames[i], false));
733  fileSources[i]->Pump(4);
734  fileSources[i]->Get(channel, 4);
735  fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
736  }
737 
738  while (fileSources[0]->Pump(256))
739  for (i=1; i<threshold; i++)
740  fileSources[i]->Pump(256);
741 
742  for (i=0; i<threshold; i++)
743  fileSources[i]->PumpAll();
744 }
745 
746 void GzipFile(const char *in, const char *out, int deflate_level)
747 {
748 // FileSource(in, true, new Gzip(new FileSink(out), deflate_level));
749 
750  // use a filter graph to compare decompressed data with original
751  //
752  // Source ----> Gzip ------> Sink
753  // \ |
754  // \ Gunzip
755  // \ |
756  // \ v
757  // > ComparisonFilter
758 
759  EqualityComparisonFilter comparison;
760 
761  Gunzip gunzip(new ChannelSwitch(comparison, "0"));
762  gunzip.SetAutoSignalPropagation(0);
763 
764  FileSink sink(out);
765 
766  ChannelSwitch *cs;
767  Gzip gzip(cs = new ChannelSwitch(sink), deflate_level);
768  cs->AddDefaultRoute(gunzip);
769 
770  cs = new ChannelSwitch(gzip);
771  cs->AddDefaultRoute(comparison, "1");
772  FileSource source(in, true, cs);
773 
774  comparison.ChannelMessageSeriesEnd("0");
775  comparison.ChannelMessageSeriesEnd("1");
776 }
777 
778 void GunzipFile(const char *in, const char *out)
779 {
780  FileSource(in, true, new Gunzip(new FileSink(out)));
781 }
782 
783 void Base64Encode(const char *in, const char *out)
784 {
785  FileSource(in, true, new Base64Encoder(new FileSink(out)));
786 }
787 
788 void Base64Decode(const char *in, const char *out)
789 {
790  FileSource(in, true, new Base64Decoder(new FileSink(out)));
791 }
792 
793 void HexEncode(const char *in, const char *out)
794 {
795  FileSource(in, true, new HexEncoder(new FileSink(out)));
796 }
797 
798 void HexDecode(const char *in, const char *out)
799 {
800  FileSource(in, true, new HexDecoder(new FileSink(out)));
801 }
802 
803 void ForwardTcpPort(const char *sourcePortName, const char *destinationHost, const char *destinationPortName)
804 {
805  // Quiet warnings for Windows Phone and Windows Store builds
806  CRYPTOPP_UNUSED(sourcePortName), CRYPTOPP_UNUSED(destinationHost), CRYPTOPP_UNUSED(destinationPortName);
807 
808 #ifdef SOCKETS_AVAILABLE
809  SocketsInitializer sockInit;
810 
811  Socket sockListen, sockSource, sockDestination;
812 
813  int sourcePort = Socket::PortNameToNumber(sourcePortName);
814  int destinationPort = Socket::PortNameToNumber(destinationPortName);
815 
816  sockListen.Create();
817  sockListen.Bind(sourcePort);
818 
819  int err = setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY, "\x01", 1);
820  assert(err == 0);
821  if(err != 0)
822  throw Socket::Err(sockListen, "setsockopt", sockListen.GetLastError());
823 
824  cout << "Listing on port " << sourcePort << ".\n";
825  sockListen.Listen();
826 
827  sockListen.Accept(sockSource);
828  cout << "Connection accepted on port " << sourcePort << ".\n";
829  sockListen.CloseSocket();
830 
831  cout << "Making connection to " << destinationHost << ", port " << destinationPort << ".\n";
832  sockDestination.Create();
833  sockDestination.Connect(destinationHost, destinationPort);
834 
835  cout << "Connection made to " << destinationHost << ", starting to forward.\n";
836 
837  SocketSource out(sockSource, false, new SocketSink(sockDestination));
838  SocketSource in(sockDestination, false, new SocketSink(sockSource));
839 
840  WaitObjectContainer waitObjects;
841 
842  while (!(in.SourceExhausted() && out.SourceExhausted()))
843  {
844  waitObjects.Clear();
845 
846  out.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - out", NULL));
847  in.GetWaitObjects(waitObjects, CallStack("ForwardTcpPort - in", NULL));
848 
849  waitObjects.Wait(INFINITE_TIME);
850 
851  if (!out.SourceExhausted())
852  {
853  cout << "o" << flush;
854  out.PumpAll2(false);
855  if (out.SourceExhausted())
856  cout << "EOF received on source socket.\n";
857  }
858 
859  if (!in.SourceExhausted())
860  {
861  cout << "i" << flush;
862  in.PumpAll2(false);
863  if (in.SourceExhausted())
864  cout << "EOF received on destination socket.\n";
865  }
866  }
867 #else
868  cout << "Socket support was not enabled at compile time.\n";
869  exit(-1);
870 #endif
871 }
872 
873 bool Validate(int alg, bool thorough, const char *seedInput)
874 {
875  bool result;
876 
877  // Some editors have problems with the '\0' character when redirecting output.
878  // seedInput is argv[3] when issuing 'cryptest.exe v all <seed>'
879  std::string seed = (seedInput ? seedInput : IntToString(time(NULL)));
880  seed.resize(16, ' ');
881 
882  OFB_Mode<AES>::Encryption& prng = dynamic_cast<OFB_Mode<AES>::Encryption&>(GlobalRNG());
883  prng.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());
884 
885  PrintSeedAndThreads(seed);
886 
887  switch (alg)
888  {
889  case 0: result = ValidateAll(thorough); break;
890  case 1: result = TestSettings(); break;
891  case 2: result = TestOS_RNG(); break;
892  case 3: result = ValidateMD5(); break;
893  case 4: result = ValidateSHA(); break;
894  case 5: result = ValidateDES(); break;
895  case 6: result = ValidateIDEA(); break;
896  case 7: result = ValidateARC4(); break;
897  case 8: result = ValidateRC5(); break;
898  case 9: result = ValidateBlowfish(); break;
899 // case 10: result = ValidateDiamond2(); break;
900  case 11: result = ValidateThreeWay(); break;
901  case 12: result = ValidateBBS(); break;
902  case 13: result = ValidateDH(); break;
903  case 14: result = ValidateRSA(); break;
904  case 15: result = ValidateElGamal(); break;
905  case 16: result = ValidateDSA(thorough); break;
906 // case 17: result = ValidateHAVAL(); break;
907  case 18: result = ValidateSAFER(); break;
908  case 19: result = ValidateLUC(); break;
909  case 20: result = ValidateRabin(); break;
910 // case 21: result = ValidateBlumGoldwasser(); break;
911  case 22: result = ValidateECP(); break;
912  case 23: result = ValidateEC2N(); break;
913 // case 24: result = ValidateMD5MAC(); break;
914  case 25: result = ValidateGOST(); break;
915  case 26: result = ValidateTiger(); break;
916  case 27: result = ValidateRIPEMD(); break;
917  case 28: result = ValidateHMAC(); break;
918 // case 29: result = ValidateXMACC(); break;
919  case 30: result = ValidateSHARK(); break;
920  case 32: result = ValidateLUC_DH(); break;
921  case 33: result = ValidateLUC_DL(); break;
922  case 34: result = ValidateSEAL(); break;
923  case 35: result = ValidateCAST(); break;
924  case 36: result = ValidateSquare(); break;
925  case 37: result = ValidateRC2(); break;
926  case 38: result = ValidateRC6(); break;
927  case 39: result = ValidateMARS(); break;
928  case 40: result = ValidateRW(); break;
929  case 41: result = ValidateMD2(); break;
930  case 42: result = ValidateNR(); break;
931  case 43: result = ValidateMQV(); break;
932  case 44: result = ValidateRijndael(); break;
933  case 45: result = ValidateTwofish(); break;
934  case 46: result = ValidateSerpent(); break;
935  case 47: result = ValidateCipherModes(); break;
936  case 48: result = ValidateCRC32(); break;
937  case 49: result = ValidateECDSA(); break;
938  case 50: result = ValidateXTR_DH(); break;
939  case 51: result = ValidateSKIPJACK(); break;
940  case 52: result = ValidateSHA2(); break;
941  case 53: result = ValidatePanama(); break;
942  case 54: result = ValidateAdler32(); break;
943  case 55: result = ValidateMD4(); break;
944  case 56: result = ValidatePBKDF(); break;
945  case 57: result = ValidateESIGN(); break;
946  case 58: result = ValidateDLIES(); break;
947  case 59: result = ValidateBaseCode(); break;
948  case 60: result = ValidateSHACAL2(); break;
949  case 61: result = ValidateCamellia(); break;
950  case 62: result = ValidateWhirlpool(); break;
951  case 63: result = ValidateTTMAC(); break;
952  case 64: result = ValidateSalsa(); break;
953  case 65: result = ValidateSosemanuk(); break;
954  case 66: result = ValidateVMAC(); break;
955  case 67: result = ValidateCCM(); break;
956  case 68: result = ValidateGCM(); break;
957  case 69: result = ValidateCMAC(); break;
958  case 70: result = ValidateHKDF(); break;
959  case 71: result = ValidateBLAKE2s(); break;
960  case 72: result = ValidateBLAKE2b(); break;
961  default: return false;
962  }
963 
964 // Safer functions on Windows for C&A, https://github.com/weidai11/cryptopp/issues/55
965 #if (CRYPTOPP_MSC_VERSION >= 1400)
966  tm localTime = {};
967  char timeBuf[64];
968  errno_t err;
969 
970  const time_t endTime = time(NULL);
971  err = localtime_s(&localTime, &endTime);
972  assert(err == 0);
973  err = asctime_s(timeBuf, sizeof(timeBuf), &localTime);
974  assert(err == 0);
975 
976  cout << "\nTest ended at " << timeBuf;
977 #else
978  const time_t endTime = time(NULL);
979  cout << "\nTest ended at " << asctime(localtime(&endTime));
980 #endif
981 
982  cout << "Seed used was: " << seed << endl;
983 
984  return result;
985 }
void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Definition: randpool.cpp:26
static unsigned int PortNameToNumber(const char *name, const char *protocol="tcp")
look up the port number given its name, returns 0 if not found
Definition: socketft.cpp:301
An invalid argument was detected.
Definition: cryptlib.h:182
container of wait objects
Definition: wait.h:169
Randomness Pool.
Definition: randpool.h:25
Filter wrapper for PK_Verifier.
Definition: filters.h:694
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
Definition: misc.h:517
socket-based implementation of NetworkSource
Definition: socketft.h:192
implements the SHA-256 standard
Definition: sha.h:32
Classes for RIPEMD message digest.
Class file for Randomness Pool.
file-based implementation of Source interface
Definition: files.h:55
Converts given data to base 16.
Definition: hex.h:16
Tiger
Definition: tiger.h:10
GZIP Decompression (RFC 1952)
Definition: gzip.h:52
Base64 decodes data.
Definition: base64.h:59
Decode base 16 data back to bytes.
Definition: hex.h:36
Abstract base classes that provide a uniform interface to this library.
RIPEMD-160
Definition: ripemd.h:15
size_type size() const
Provides the count of elements in the SecBlock.
Definition: secblock.h:521
Classes for automatic resource management.
Filter wrapper for PK_Signer.
Definition: filters.h:668
Classes for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC.
STL namespace.
Interface for random number generators.
Definition: cryptlib.h:1186
SecBlock typedef.
Definition: secblock.h:728
Route input to different and/or multiple channels based on channel ID.
Definition: channels.h:92
Pointer that overloads operator ->
Definition: smartptr.h:39
exception thrown by Socket class
Definition: socketft.h:48
Base64 encodes data.
Definition: base64.h:17
Copy input to a memory buffer.
Definition: filters.h:1016
GZIP compression and decompression (RFC 1952)
socket-based implementation of NetworkSink
Definition: socketft.h:208
Filter wrapper for HashTransformation.
Definition: filters.h:508
RNG-based implementation of Source interface.
Definition: filters.h:1097
size_t Put(byte inByte, bool blocking=true)
Input a byte for processing.
Definition: cryptlib.h:1378
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Definition: cryptlib.cpp:63
RSAES>::Decryptor typedef
Definition: rsa.h:206
signed long ConvertToLong() const
Convert the Integer to Long.
Definition: integer.cpp:2933
Whirlpool
Definition: whrlpool.h:10
bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Marks the end of a series of messages on a channel.
Definition: mqueue.cpp:135
Maurer's Universal Statistical Test for Random Bit Generators.
Definition: rng.h:84
implements the SHA-512 standard
Definition: sha.h:56
Class file for the AES cipher (Rijndael)
Manages resources for an array of objects.
Definition: smartptr.h:284
RSAES>::Encryptor typedef
Definition: rsa.h:209
Multiple precision integer with arithmetic operations.
Definition: integer.h:31
SHA-1
Definition: sha.h:21
Filter wrapper for PK_Decryptor.
Definition: filters.h:943
MessageAuthenticationCode * NewIntegrityCheckingMAC()
Class object that calculates the MAC on the module.
Definition: fipstest.cpp:271
Password-Based encryptor using TripleDES and HMAC/SHA-1.
Definition: default.h:109
Miscellaneous classes for RNGs.
wrapper for Windows or Berkeley Sockets
Definition: socketft.h:44
const unsigned long INFINITE_TIME
Represents infinite time.
Definition: cryptlib.h:110
bool GetLastResult() const
Retrieves the result of the last verification.
Definition: filters.h:735
Implementation of BufferedTransformation's attachment interface.
file-based implementation of Store interface
Definition: files.h:15
Filter wrapper for PK_Encryptor.
Definition: filters.h:928
Classes for the Base64Encoder, Base64Decoder, Base64URLEncoder and Base64URLDecoder.
Filter wrapper for StreamTransformation.
Definition: filters.h:476
#define CRYPTOPP_DUMMY_DLL_MAC
The placeholder used prior to embedding the actual MAC in the module.
Definition: fips140.h:109
HMAC.
Definition: hmac.h:50
a variant of Rabin's Information Dispersal Algorithm
Definition: ida.h:124
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Definition: misc.h:530
Measure how many bytes and messages pass through the filter.
Definition: filters.h:220
Password-Based decryptor using TripleDES and HMAC/SHA-1.
Definition: default.h:141
A filter that checks messages on two channels for equality.
Definition: mqueue.h:71
Crypto++ library namespace.
GZIP Compression (RFC 1952)
Definition: gzip.h:18
a variant of Shamir's Secret Sharing Algorithm
Definition: ida.h:86
file-based implementation of Sink interface
Definition: files.h:78
Functions and definitions required for building the FIPS-140 DLL on Windows.
a variant of Rabin's Information Dispersal Algorithm
Definition: ida.h:103
static int GetLastError()
returns errno or WSAGetLastError
Definition: socketft.cpp:332
a variant of Shamir's Secret Sharing Algorithm
Definition: ida.h:65
Classes for Information Dispersal Algorithm (IDA)
Template implementing constructors for public key algorithm classes.
Definition: pubkey.h:2030
A typedef providing a default generator.
Definition: osrng.h:253