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