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 #include "ocb.h"
25 
26 #include "validate.h"
27 #include "bench.h"
28 
29 #include <algorithm>
30 #include <iostream>
31 #include <sstream>
32 #include <string>
33 #include <locale>
34 #include <time.h>
35 
36 #ifdef CRYPTOPP_WIN32_AVAILABLE
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  {
148 
149  RegisterFactories();
150 
151  // Some editors have problems with the '\0' character when redirecting output.
152  std::string seed = IntToString(time(NULL));
153  seed.resize(16, ' ');
154 
155  OFB_Mode<AES>::Encryption& prng = dynamic_cast<OFB_Mode<AES>::Encryption&>(GlobalRNG());
156  prng.SetKeyWithIV((byte *)seed.data(), 16, (byte *)seed.data());
157 
158  std::string command, executableName, macFilename;
159 
160  if (argc < 2)
161  command = 'h';
162  else
163  command = argv[1];
164 
165  if (command == "g")
166  {
167  char thisSeed[1024], privFilename[128], pubFilename[128];
168  unsigned int keyLength;
169 
170  cout << "Key length in bits: ";
171  cin >> keyLength;
172 
173  cout << "\nSave private key to file: ";
174  cin >> privFilename;
175 
176  cout << "\nSave public key to file: ";
177  cin >> pubFilename;
178 
179  cout << "\nRandom Seed: ";
180  ws(cin);
181  cin.getline(thisSeed, 1024);
182 
183  GenerateRSAKey(keyLength, privFilename, pubFilename, thisSeed);
184  }
185  else if (command == "rs")
186  RSASignFile(argv[2], argv[3], argv[4]);
187  else if (command == "rv")
188  {
189  bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
190  cout << (verified ? "valid signature" : "invalid signature") << endl;
191  }
192  else if (command == "r")
193  {
194  char privFilename[128], pubFilename[128];
195  char thisSeed[1024], message[1024];
196 
197  cout << "Private key file: ";
198  cin >> privFilename;
199 
200  cout << "\nPublic key file: ";
201  cin >> pubFilename;
202 
203  cout << "\nRandom Seed: ";
204  ws(cin);
205  cin.getline(thisSeed, 1024);
206 
207  cout << "\nMessage: ";
208  cin.getline(message, 1024);
209 
210  string ciphertext = RSAEncryptString(pubFilename, thisSeed, message);
211  cout << "\nCiphertext: " << ciphertext << endl;
212 
213  string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
214  cout << "\nDecrypted: " << decrypted << endl;
215  }
216  else if (command == "mt")
217  {
219  FileStore fs(argv[2]);
220  fs.TransferAllTo(mt);
221  cout << "Maurer Test Value: " << mt.GetTestValue() << endl;
222  }
223  else if (command == "mac_dll")
224  {
225  std::string fname(argv[2] ? argv[2] : "");
226 
227  // sanity check on file size
228  std::fstream dllFile(fname.c_str(), ios::in | ios::out | ios::binary);
229  if (!dllFile.good())
230  {
231  cerr << "Failed to open file \"" << fname << "\"\n";
232  return 1;
233  }
234 
235  std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg();
236  if (fileEnd > 20*1000*1000)
237  {
238  cerr << "Input file " << fname << " is too large";
239  cerr << "(size is " << fileEnd << ").\n";
240  return 1;
241  }
242 
243  // read file into memory
244  unsigned int fileSize = (unsigned int)fileEnd;
245  SecByteBlock buf(fileSize);
246  dllFile.seekg(0, std::ios_base::beg);
247  dllFile.read((char *)buf.begin(), fileSize);
248 
249  // 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
250  word32 coffPos = *(word16 *)(void *)(buf+0x3c);
251  word32 optionalHeaderPos = coffPos + 24;
252  word16 optionalHeaderMagic = *(word16 *)(void *)(buf+optionalHeaderPos);
253  if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b)
254  {
255  cerr << "Target file is not a PE32 or PE32+ image.\n";
256  return 3;
257  }
258  word32 checksumPos = optionalHeaderPos + 64;
259  word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144);
260  word32 certificateTablePos = *(word32 *)(void *)(buf+certificateTableDirectoryPos);
261  word32 certificateTableSize = *(word32 *)(void *)(buf+certificateTableDirectoryPos+4);
262  if (certificateTableSize != 0)
263  cerr << "Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n";
264 
265  // find where to place computed MAC
266  byte mac[] = CRYPTOPP_DUMMY_DLL_MAC;
267  byte *found = std::search(buf.begin(), buf.end(), mac+0, mac+sizeof(mac));
268  if (found == buf.end())
269  {
270  cerr << "MAC placeholder not found. The MAC may already be placed.\n";
271  return 2;
272  }
273  word32 macPos = (unsigned int)(found-buf.begin());
274 
275  // compute MAC
277  assert(pMac->DigestSize() == sizeof(mac));
278  MeterFilter f(new HashFilter(*pMac, new ArraySink(mac, sizeof(mac))));
279  f.AddRangeToSkip(0, checksumPos, 4);
280  f.AddRangeToSkip(0, certificateTableDirectoryPos, 8);
281  f.AddRangeToSkip(0, macPos, sizeof(mac));
282  f.AddRangeToSkip(0, certificateTablePos, certificateTableSize);
283  f.PutMessageEnd(buf.begin(), buf.size());
284 
285  // place MAC
286  cout << "Placing MAC in file " << fname << ", location " << macPos;
287  cout << " (0x" << std::hex << macPos << std::dec << ").\n";
288  dllFile.seekg(macPos, std::ios_base::beg);
289  dllFile.write((char *)mac, sizeof(mac));
290  }
291  else if (command == "m")
292  DigestFile(argv[2]);
293  else if (command == "tv")
294  {
295  // TestDataFile() adds CRYPTOPP_DATA_DIR as required
296  std::string fname = (argv[2] ? argv[2] : "all");
297 #if defined(CRYPTOPP_USE_FIPS_202_SHA3)
298  if (fname == "sha3")
299  fname = "sha3_fips_202";
300  if (fname == "all")
301  fname = "all_fips_202";
302 #endif
303  if (fname.find(".txt") == std::string::npos)
304  fname = "TestVectors/" + fname + ".txt";
305 
306  PrintSeedAndThreads(seed);
307  return !RunTestDataFile(fname.c_str());
308  }
309  else if (command == "t")
310  {
311  // VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug
312  char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];
313 
314  cout << "Passphrase: ";
315  cin.getline(passPhrase, MAX_PHRASE_LENGTH);
316 
317  cout << "\nPlaintext: ";
318  cin.getline(plaintext, 1024);
319 
320  string ciphertext = EncryptString(plaintext, passPhrase);
321  cout << "\nCiphertext: " << ciphertext << endl;
322 
323  string decrypted = DecryptString(ciphertext.c_str(), passPhrase);
324  cout << "\nDecrypted: " << decrypted << endl;
325 
326  return 0;
327  }
328  else if (command == "e64")
329  Base64Encode(argv[2], argv[3]);
330  else if (command == "d64")
331  Base64Decode(argv[2], argv[3]);
332  else if (command == "e16")
333  HexEncode(argv[2], argv[3]);
334  else if (command == "d16")
335  HexDecode(argv[2], argv[3]);
336  else if (command == "e" || command == "d")
337  {
338  char passPhrase[MAX_PHRASE_LENGTH];
339  cout << "Passphrase: ";
340  cin.getline(passPhrase, MAX_PHRASE_LENGTH);
341  if (command == "e")
342  EncryptFile(argv[2], argv[3], passPhrase);
343  else
344  DecryptFile(argv[2], argv[3], passPhrase);
345  }
346  else if (command == "ss")
347  {
348  char thisSeed[1024];
349  cout << "\nRandom Seed: ";
350  ws(cin);
351  cin.getline(thisSeed, 1024);
352  SecretShareFile(StringToValue<int, true>(argv[2]), StringToValue<int, true>(argv[3]), argv[4], thisSeed);
353  }
354  else if (command == "sr")
355  SecretRecoverFile(argc-3, argv[2], argv+3);
356  else if (command == "id")
357  InformationDisperseFile(StringToValue<int, true>(argv[2]), StringToValue<int, true>(argv[3]), argv[4]);
358  else if (command == "ir")
359  InformationRecoverFile(argc-3, argv[2], argv+3);
360  else if (command == "v" || command == "vv")
361  return !Validate(argc>2 ? StringToValue<int, true>(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL);
362  else if (command == "b")
363  BenchmarkAll(argc<3 ? 1 : StringToValue<float, true>(argv[2]), argc<4 ? 0 : StringToValue<float, true>(argv[3])*1e9);
364  else if (command == "b2")
365  BenchmarkAll2(argc<3 ? 1 : StringToValue<float, true>(argv[2]), argc<4 ? 0 : StringToValue<float, true>(argv[3])*1e9);
366  else if (command == "z")
367  GzipFile(argv[3], argv[4], argv[2][0]-'0');
368  else if (command == "u")
369  GunzipFile(argv[2], argv[3]);
370  else if (command == "fips")
371  FIPS140_SampleApplication();
372  else if (command == "fips-rand")
373  FIPS140_GenerateRandomFiles();
374  else if (command == "ft")
375  ForwardTcpPort(argv[2], argv[3], argv[4]);
376  else if (command == "a")
377  {
378  if (AdhocTest)
379  return (*AdhocTest)(argc, argv);
380  else
381  {
382  cerr << "AdhocTest not defined.\n";
383  return 1;
384  }
385  }
386  else if (command == "hmac")
387  HmacFile(argv[2], argv[3]);
388  else if (command == "ae")
389  AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]);
390  else if (command == "h")
391  {
392  FileSource usage(CRYPTOPP_DATA_DIR "TestData/usage.dat", true, new FileSink(cout));
393  return 1;
394  }
395  else if (command == "V")
396  {
397  cout << CRYPTOPP_VERSION / 100 << '.' << (CRYPTOPP_VERSION % 100) / 10 << '.' << CRYPTOPP_VERSION % 10 << endl;
398  }
399  else
400  {
401  cerr << "Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";
402  return 1;
403  }
404  return 0;
405  }
406  catch(const CryptoPP::Exception &e)
407  {
408  cout << "\nCryptoPP::Exception caught: " << e.what() << endl;
409  return -1;
410  }
411  catch(const std::exception &e)
412  {
413  cout << "\nstd::exception caught: " << e.what() << endl;
414  return -2;
415  }
416 } // End main()
417 
418 void FIPS140_GenerateRandomFiles()
419 {
420 #ifdef OS_RNG_AVAILABLE
422  RandomNumberStore store(rng, ULONG_MAX);
423 
424  for (unsigned int i=0; i<100000; i++)
425  store.TransferTo(FileSink((IntToString(i) + ".rnd").c_str()).Ref(), 20000);
426 #else
427  cout << "OS provided RNG not available.\n";
428  exit(-1);
429 #endif
430 }
431 
432 template <class T, bool NON_NEGATIVE>
433 T StringToValue(const std::string& str) {
434  std::istringstream iss(str);
435  T value;
436  iss >> value;
437 
438  // Use fail(), not bad()
439  if (iss.fail())
440  throw InvalidArgument("cryptest.exe: '" + str +"' is not a value");
441 
442 #if NON_NEGATIVE
443  if (value < 0)
444  throw InvalidArgument("cryptest.exe: '" + str +"' is negative");
445 #endif
446 
447  return value;
448 }
449 
450 template<>
451 int StringToValue<int, true>(const std::string& str)
452 {
453  Integer n(str.c_str());
454  long l = n.ConvertToLong();
455 
456  int r;
457  if(!SafeConvert(l, r))
458  throw InvalidArgument("cryptest.exe: '" + str +"' is not an integer value");
459 
460  return r;
461 }
462 
463 void PrintSeedAndThreads(const std::string& seed)
464 {
465  cout << "Using seed: " << seed << endl;
466 
467 #ifdef _OPENMP
468  int tc = 0;
469  #pragma omp parallel
470  {
471  tc = omp_get_num_threads();
472  }
473 
474  std::cout << "Using " << tc << " OMP " << (tc == 1 ? "thread" : "threads") << std::endl;
475 #endif
476 }
477 
478 SecByteBlock HexDecodeString(const char *hex)
479 {
480  StringSource ss(hex, true, new HexDecoder);
481  SecByteBlock result((size_t)ss.MaxRetrievable());
482  ss.Get(result, result.size());
483  return result;
484 }
485 
486 void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed)
487 {
488  RandomPool randPool;
489  randPool.IncorporateEntropy((byte *)seed, strlen(seed));
490 
491  RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);
492  HexEncoder privFile(new FileSink(privFilename));
493  priv.DEREncode(privFile);
494  privFile.MessageEnd();
495 
496  RSAES_OAEP_SHA_Encryptor pub(priv);
497  HexEncoder pubFile(new FileSink(pubFilename));
498  pub.DEREncode(pubFile);
499  pubFile.MessageEnd();
500 }
501 
502 string RSAEncryptString(const char *pubFilename, const char *seed, const char *message)
503 {
504  FileSource pubFile(pubFilename, true, new HexDecoder);
505  RSAES_OAEP_SHA_Encryptor pub(pubFile);
506 
507  RandomPool randPool;
508  randPool.IncorporateEntropy((byte *)seed, strlen(seed));
509 
510  string result;
511  StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(result))));
512  return result;
513 }
514 
515 string RSADecryptString(const char *privFilename, const char *ciphertext)
516 {
517  FileSource privFile(privFilename, true, new HexDecoder);
518  RSAES_OAEP_SHA_Decryptor priv(privFile);
519 
520  string result;
521  StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result))));
522  return result;
523 }
524 
525 void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename)
526 {
527  FileSource privFile(privFilename, true, new HexDecoder);
528  RSASS<PKCS1v15, SHA>::Signer priv(privFile);
529  FileSource f(messageFilename, true, new SignerFilter(GlobalRNG(), priv, new HexEncoder(new FileSink(signatureFilename))));
530 }
531 
532 bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename)
533 {
534  FileSource pubFile(pubFilename, true, new HexDecoder);
535  RSASS<PKCS1v15, SHA>::Verifier pub(pubFile);
536 
537  FileSource signatureFile(signatureFilename, true, new HexDecoder);
538  if (signatureFile.MaxRetrievable() != pub.SignatureLength())
539  return false;
540  SecByteBlock signature(pub.SignatureLength());
541  signatureFile.Get(signature, signature.size());
542 
543  VerifierFilter *verifierFilter = new VerifierFilter(pub);
544  verifierFilter->Put(signature, pub.SignatureLength());
545  FileSource f(messageFilename, true, verifierFilter);
546 
547  return verifierFilter->GetLastResult();
548 }
549 
550 void DigestFile(const char *filename)
551 {
552  SHA1 sha;
553  RIPEMD160 ripemd;
554  SHA256 sha256;
555  Tiger tiger;
556  SHA512 sha512;
557  Whirlpool whirlpool;
559  filters[0].reset(new HashFilter(sha));
560  filters[1].reset(new HashFilter(ripemd));
561  filters[2].reset(new HashFilter(tiger));
562  filters[3].reset(new HashFilter(sha256));
563  filters[4].reset(new HashFilter(sha512));
564  filters[5].reset(new HashFilter(whirlpool));
565 
566  member_ptr<ChannelSwitch> channelSwitch(new ChannelSwitch);
567  size_t i;
568  for (i=0; i<filters.size(); i++)
569  channelSwitch->AddDefaultRoute(*filters[i]);
570  FileSource(filename, true, channelSwitch.release());
571 
572  HexEncoder encoder(new FileSink(cout), false);
573  for (i=0; i<filters.size(); i++)
574  {
575  cout << filters[i]->AlgorithmName() << ": ";
576  filters[i]->TransferTo(encoder);
577  cout << "\n";
578  }
579 }
580 
581 void HmacFile(const char *hexKey, const char *file)
582 {
584  if (strcmp(hexKey, "selftest") == 0)
585  {
586  cerr << "Computing HMAC/SHA1 value for self test.\n";
587  mac.reset(NewIntegrityCheckingMAC());
588  }
589  else
590  {
591  std::string decodedKey;
592  StringSource(hexKey, true, new HexDecoder(new StringSink(decodedKey)));
593  mac.reset(new HMAC<SHA1>((const byte *)decodedKey.data(), decodedKey.size()));
594  }
595  FileSource(file, true, new HashFilter(*mac, new HexEncoder(new FileSink(cout))));
596 }
597 
598 void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile)
599 {
600  SecByteBlock key = HexDecodeString(hexKey);
601  SecByteBlock iv = HexDecodeString(hexIV);
602  CTR_Mode<AES>::Encryption aes(key, key.size(), iv);
603  FileSource(infile, true, new StreamTransformationFilter(aes, new FileSink(outfile)));
604 }
605 
606 string EncryptString(const char *instr, const char *passPhrase)
607 {
608  string outstr;
609 
610  DefaultEncryptorWithMAC encryptor(passPhrase, new HexEncoder(new StringSink(outstr)));
611  encryptor.Put((byte *)instr, strlen(instr));
612  encryptor.MessageEnd();
613 
614  return outstr;
615 }
616 
617 string DecryptString(const char *instr, const char *passPhrase)
618 {
619  string outstr;
620 
621  HexDecoder decryptor(new DefaultDecryptorWithMAC(passPhrase, new StringSink(outstr)));
622  decryptor.Put((byte *)instr, strlen(instr));
623  decryptor.MessageEnd();
624 
625  return outstr;
626 }
627 
628 void EncryptFile(const char *in, const char *out, const char *passPhrase)
629 {
630  FileSource f(in, true, new DefaultEncryptorWithMAC(passPhrase, new FileSink(out)));
631 }
632 
633 void DecryptFile(const char *in, const char *out, const char *passPhrase)
634 {
635  FileSource f(in, true, new DefaultDecryptorWithMAC(passPhrase, new FileSink(out)));
636 }
637 
638 void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed)
639 {
640  assert(nShares >= 1 && nShares<=1000);
641  if (nShares < 1 || nShares > 1000)
642  throw InvalidArgument("SecretShareFile: " + IntToString(nShares) + " is not in range [1, 1000]");
643 
644  RandomPool rng;
645  rng.IncorporateEntropy((byte *)seed, strlen(seed));
646 
647  ChannelSwitch *channelSwitch;
648  FileSource source(filename, false, new SecretSharing(rng, threshold, nShares, channelSwitch = new ChannelSwitch));
649 
650  vector_member_ptrs<FileSink> fileSinks(nShares);
651  string channel;
652  for (int i=0; i<nShares; i++)
653  {
654  char extension[5] = ".000";
655  extension[1]='0'+byte(i/100);
656  extension[2]='0'+byte((i/10)%10);
657  extension[3]='0'+byte(i%10);
658  fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
659 
660  channel = WordToString<word32>(i);
661  fileSinks[i]->Put((const byte *)channel.data(), 4);
662  channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
663  }
664 
665  source.PumpAll();
666 }
667 
668 void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
669 {
670  assert(threshold >= 1 && threshold <=1000);
671  if (threshold < 1 || threshold > 1000)
672  throw InvalidArgument("SecretRecoverFile: " + IntToString(threshold) + " is not in range [1, 1000]");
673 
674  SecretRecovery recovery(threshold, new FileSink(outFilename));
675 
676  vector_member_ptrs<FileSource> fileSources(threshold);
677  SecByteBlock channel(4);
678  int i;
679  for (i=0; i<threshold; i++)
680  {
681  fileSources[i].reset(new FileSource(inFilenames[i], false));
682  fileSources[i]->Pump(4);
683  fileSources[i]->Get(channel, 4);
684  fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
685  }
686 
687  while (fileSources[0]->Pump(256))
688  for (i=1; i<threshold; i++)
689  fileSources[i]->Pump(256);
690 
691  for (i=0; i<threshold; i++)
692  fileSources[i]->PumpAll();
693 }
694 
695 void InformationDisperseFile(int threshold, int nShares, const char *filename)
696 {
697  assert(threshold >= 1 && threshold <=1000);
698  if (threshold < 1 || threshold > 1000)
699  throw InvalidArgument("InformationDisperseFile: " + IntToString(nShares) + " is not in range [1, 1000]");
700 
701  ChannelSwitch *channelSwitch;
702  FileSource source(filename, false, new InformationDispersal(threshold, nShares, channelSwitch = new ChannelSwitch));
703 
704  vector_member_ptrs<FileSink> fileSinks(nShares);
705  string channel;
706  for (int i=0; i<nShares; i++)
707  {
708  char extension[5] = ".000";
709  extension[1]='0'+byte(i/100);
710  extension[2]='0'+byte((i/10)%10);
711  extension[3]='0'+byte(i%10);
712  fileSinks[i].reset(new FileSink((string(filename)+extension).c_str()));
713 
714  channel = WordToString<word32>(i);
715  fileSinks[i]->Put((const byte *)channel.data(), 4);
716  channelSwitch->AddRoute(channel, *fileSinks[i], DEFAULT_CHANNEL);
717  }
718 
719  source.PumpAll();
720 }
721 
722 void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
723 {
724  assert(threshold<=1000);
725  if (threshold < 1 || threshold > 1000)
726  throw InvalidArgument("InformationRecoverFile: " + IntToString(threshold) + " is not in range [1, 1000]");
727 
728  InformationRecovery recovery(threshold, new FileSink(outFilename));
729 
730  vector_member_ptrs<FileSource> fileSources(threshold);
731  SecByteBlock channel(4);
732  int i;
733  for (i=0; i<threshold; i++)
734  {
735  fileSources[i].reset(new FileSource(inFilenames[i], false));
736  fileSources[i]->Pump(4);
737  fileSources[i]->Get(channel, 4);
738  fileSources[i]->Attach(new ChannelSwitch(recovery, string((char *)channel.begin(), 4)));
739  }
740 
741  while (fileSources[0]->Pump(256))
742  for (i=1; i<threshold; i++)
743  fileSources[i]->Pump(256);
744 
745  for (i=0; i<threshold; i++)
746  fileSources[i]->PumpAll();
747 }
748 
749 void GzipFile(const char *in, const char *out, int deflate_level)
750 {
751 // FileSource(in, true, new Gzip(new FileSink(out), deflate_level));
752 
753  // use a filter graph to compare decompressed data with original
754  //
755  // Source ----> Gzip ------> Sink
756  // \ |
757  // \ Gunzip
758  // \ |
759  // \ v
760  // > ComparisonFilter
761 
762  EqualityComparisonFilter comparison;
763 
764  Gunzip gunzip(new ChannelSwitch(comparison, "0"));
765  gunzip.SetAutoSignalPropagation(0);
766 
767  FileSink sink(out);
768 
769  ChannelSwitch *cs;
770  Gzip gzip(cs = new ChannelSwitch(sink), deflate_level);
771  cs->AddDefaultRoute(gunzip);
772 
773  cs = new ChannelSwitch(gzip);
774  cs->AddDefaultRoute(comparison, "1");
775  FileSource source(in, true, cs);
776 
777  comparison.ChannelMessageSeriesEnd("0");
778  comparison.ChannelMessageSeriesEnd("1");
779 }
780 
781 void GunzipFile(const char *in, const char *out)
782 {
783  FileSource(in, true, new Gunzip(new FileSink(out)));
784 }
785 
786 void Base64Encode(const char *in, const char *out)
787 {
788  FileSource(in, true, new Base64Encoder(new FileSink(out)));
789 }
790 
791 void Base64Decode(const char *in, const char *out)
792 {
793  FileSource(in, true, new Base64Decoder(new FileSink(out)));
794 }
795 
796 void HexEncode(const char *in, const char *out)
797 {
798  FileSource(in, true, new HexEncoder(new FileSink(out)));
799 }
800 
801 void HexDecode(const char *in, const char *out)
802 {
803  FileSource(in, true, new HexDecoder(new FileSink(out)));
804 }
805 
806 void ForwardTcpPort(const char *sourcePortName, const char *destinationHost, const char *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
An invalid argument was detected.
Definition: cryptlib.h:182
container of wait objects
Definition: wait.h:154
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:447
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:523
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:730
Route input to different and/or multiple channels based on channel ID.
Definition: channels.h:92
Pointer that overloads operator→
Definition: smartptr.h:39
Base64 encodes data.
Definition: base64.h:17
Copy input to a memory buffer.
Definition: filters.h:1000
GZIP compression and decompression (RFC 1952)
Filter wrapper for HashTransformation.
Definition: filters.h:508
RNG-based implementation of Source interface.
Definition: filters.h:1081
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:41
RSAES>::Decryptor typedef
Definition: rsa.h:206
signed long ConvertToLong() const
Convert the Integer to Long.
Definition: integer.cpp:2865
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:927
MessageAuthenticationCode * NewIntegrityCheckingMAC()
Class object that calculates the MAC on the module.
Definition: fipstest.cpp:254
Password-Based encryptor using TripleDES and HMAC/SHA-1.
Definition: default.h:121
Miscellaneous classes for RNGs.
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:912
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:460
Measure how many bytes and messages pass through the filter.
Definition: filters.h:220
OCB_Final block cipher final implementation.
Definition: ocb.h:95
Password-Based decryptor using TripleDES and HMAC/SHA-1.
Definition: default.h:159
A filter that checks messages on two channels for equality.
Definition: mqueue.h:71
OCB block cipher mode of operation.
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
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:242