3 #define CRYPTOPP_DEFAULT_NO_DLL 4 #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 37 #ifdef CRYPTOPP_WIN32_AVAILABLE 38 #define WIN32_LEAN_AND_MEAN 42 #if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh) 43 #include <netinet/in.h> 44 #include <netinet/tcp.h> 47 #if (_MSC_VER >= 1000) 51 #if defined(__MWERKS__) && defined(macintosh) 60 #pragma comment(lib, "cryptlib_bds.lib") 61 #pragma comment(lib, "ws2_32.lib") 65 #if (CRYPTOPP_MSC_VERSION >= 1410) 66 # pragma strict_gs_check (on) 69 #if CRYPTOPP_GCC_DIAGNOSTIC_AVAILABLE 70 # pragma GCC diagnostic ignored "-Wdeprecated-declarations" 81 void GenerateRSAKey(
unsigned int keyLength, const
char *privFilename, const
char *pubFilename, const
char *seed);
82 string RSAEncryptString(const
char *pubFilename, const
char *seed, const
char *message);
84 void RSASignFile(const
char *privFilename, const
char *messageFilename, const
char *signatureFilename);
85 bool RSAVerifyFile(const
char *pubFilename, const
char *messageFilename, const
char *signatureFilename);
88 void HmacFile(const
char *hexKey, const
char *file);
90 void AES_CTR_Encrypt(const
char *hexKey, const
char *hexIV, const
char *infile, const
char *outfile);
92 string EncryptString(const
char *plaintext, const
char *passPhrase);
93 string DecryptString(const
char *ciphertext, const
char *passPhrase);
95 void EncryptFile(const
char *in, const
char *out, const
char *passPhrase);
96 void DecryptFile(const
char *in, const
char *out, const
char *passPhrase);
98 void SecretShareFile(
int threshold,
int nShares, const
char *filename, const
char *seed);
99 void SecretRecoverFile(
int threshold, const
char *outFilename,
char *const *inFilenames);
104 void GzipFile(const
char *in, const
char *out,
int deflate_level);
105 void GunzipFile(const
char *in, const
char *out);
107 void Base64Encode(const
char *infile, const
char *outfile);
108 void Base64Decode(const
char *infile, const
char *outfile);
109 void HexEncode(const
char *infile, const
char *outfile);
110 void HexDecode(const
char *infile, const
char *outfile);
112 void ForwardTcpPort(const
char *sourcePort, const
char *destinationHost, const
char *destinationPort);
117 bool Validate(
int,
bool, const
char *);
129 #if defined(CRYPTOPP_DEBUG) && defined(UNIX_SIGNALS_AVAILABLE) 130 static const SignalHandler<SIGTRAP, false> s_dummyHandler;
136 #ifdef _CRTDBG_LEAK_CHECK_DF 138 int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
139 tempflag |= _CRTDBG_LEAK_CHECK_DF;
140 _CrtSetDbgFlag( tempflag );
143 #if defined(__MWERKS__) && defined(macintosh) 144 argc = ccommand(&argv);
153 seed.resize(16,
' ');
157 aesg.SetKeyWithIV((
byte *)seed.data(), 16, (
byte *)seed.data());
159 std::string command, executableName, macFilename;
168 char thisSeed[1024], privFilename[128], pubFilename[128];
169 unsigned int keyLength;
171 cout <<
"Key length in bits: ";
174 cout <<
"\nSave private key to file: ";
177 cout <<
"\nSave public key to file: ";
180 cout <<
"\nRandom Seed: ";
182 cin.getline(thisSeed, 1024);
186 else if (command ==
"rs")
188 else if (command ==
"rv")
191 cout << (verified ?
"valid signature" :
"invalid signature") << endl;
193 else if (command ==
"r")
195 char privFilename[128], pubFilename[128];
196 char thisSeed[1024], message[1024];
198 cout <<
"Private key file: ";
201 cout <<
"\nPublic key file: ";
204 cout <<
"\nRandom Seed: ";
206 cin.getline(thisSeed, 1024);
208 cout <<
"\nMessage: ";
209 cin.getline(message, 1024);
212 cout <<
"\nCiphertext: " << ciphertext << endl;
215 cout <<
"\nDecrypted: " << decrypted << endl;
217 else if (command ==
"mt")
222 cout <<
"Maurer Test Value: " << mt.
GetTestValue() << endl;
224 else if (command ==
"mac_dll")
226 std::string fname(argv[2] ? argv[2] :
"");
229 std::fstream dllFile(fname.c_str(), ios::in | ios::out | ios::binary);
232 cerr <<
"Failed to open file \"" << fname <<
"\"\n";
236 std::ifstream::pos_type fileEnd = dllFile.seekg(0, std::ios_base::end).tellg();
237 if (fileEnd > 20*1000*1000)
239 cerr <<
"Input file " << fname <<
" is too large";
240 cerr <<
"(size is " << fileEnd <<
").\n";
245 unsigned int fileSize = (
unsigned int)fileEnd;
247 dllFile.seekg(0, std::ios_base::beg);
248 dllFile.read((
char *)buf.
begin(), fileSize);
252 word32 optionalHeaderPos = coffPos + 24;
253 word16 optionalHeaderMagic = *(
word16 *)(
void *)(buf+optionalHeaderPos);
254 if (optionalHeaderMagic != 0x10b && optionalHeaderMagic != 0x20b)
256 cerr <<
"Target file is not a PE32 or PE32+ image.\n";
259 word32 checksumPos = optionalHeaderPos + 64;
260 word32 certificateTableDirectoryPos = optionalHeaderPos + (optionalHeaderMagic == 0x10b ? 128 : 144);
261 word32 certificateTablePos = *(
word32 *)(
void *)(buf+certificateTableDirectoryPos);
262 word32 certificateTableSize = *(
word32 *)(
void *)(buf+certificateTableDirectoryPos+4);
263 if (certificateTableSize != 0)
264 cerr <<
"Warning: certificate table (IMAGE_DIRECTORY_ENTRY_SECURITY) of target image is not empty.\n";
268 byte *found = std::search(buf.
begin(), buf.
end(), mac+0, mac+
sizeof(mac));
269 if (found == buf.
end())
271 cerr <<
"MAC placeholder not found. The MAC may already be placed.\n";
291 encoder.
Get(reinterpret_cast<byte*>(&hexMac[0]), hexMac.size());
294 std::cout <<
"Placing MAC " << hexMac <<
" in " << fname <<
" at file offset " << macPos;
295 std::cout <<
" (0x" << std::hex << macPos << std::dec <<
").\n";
298 dllFile.seekg(macPos, std::ios_base::beg);
299 dllFile.write((
char *)mac,
sizeof(mac));
301 else if (command ==
"m")
303 else if (command ==
"tv")
306 std::string fname = (argv[2] ? argv[2] :
"all");
307 if (fname.find(
".txt") == std::string::npos)
308 fname =
"TestVectors/" + fname +
".txt";
313 else if (command ==
"t")
318 cout <<
"Passphrase: ";
321 cout <<
"\nPlaintext: ";
322 cin.getline(plaintext, 1024);
325 cout <<
"\nCiphertext: " << ciphertext << endl;
327 string decrypted =
DecryptString(ciphertext.c_str(), passPhrase);
328 cout <<
"\nDecrypted: " << decrypted << endl;
332 else if (command ==
"e64")
334 else if (command ==
"d64")
336 else if (command ==
"e16")
338 else if (command ==
"d16")
340 else if (command ==
"e" || command ==
"d")
343 cout <<
"Passphrase: ";
350 else if (command ==
"ss")
353 cout <<
"\nRandom Seed: ";
355 cin.getline(thisSeed, 1024);
358 else if (command ==
"sr")
360 else if (command ==
"id")
362 else if (command ==
"ir")
364 else if (command ==
"v" || command ==
"vv")
366 else if (command ==
"b")
367 BenchmarkAll(argc<3 ? 1 : StringToValue<float, true>(argv[2]), argc<4 ? 0.0
f : StringToValue<float, true>(argv[3])*1e9);
368 else if (command ==
"b2")
369 BenchmarkAll2(argc<3 ? 1 : StringToValue<float, true>(argv[2]), argc<4 ? 0.0
f : StringToValue<float, true>(argv[3])*1e9);
370 else if (command ==
"z")
371 GzipFile(argv[3], argv[4], argv[2][0]-
'0');
372 else if (command ==
"u")
374 else if (command ==
"fips")
376 else if (command ==
"fips-rand")
378 else if (command ==
"ft")
380 else if (command ==
"a")
386 cerr <<
"AdhocTest not defined.\n";
390 else if (command ==
"hmac")
392 else if (command ==
"ae")
394 else if (command ==
"h")
399 else if (command ==
"V")
405 cerr <<
"Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";
410 catch(
const CryptoPP::Exception &
e)
412 cout <<
"\nCryptoPP::Exception caught: " << e.what() << endl;
415 catch(
const std::exception &e)
417 cout <<
"\nstd::exception caught: " << e.what() << endl;
424 #ifdef OS_RNG_AVAILABLE 425 DefaultAutoSeededRNG rng;
428 for (
unsigned int i=0; i<100000; i++)
431 cout <<
"OS provided RNG not available.\n";
436 template <
class T,
bool NON_NEGATIVE>
438 std::istringstream iss(str);
441 if(iss.str().length() > 25)
445 iss >> std::noskipws >> value;
448 if (iss.fail() || !iss.eof())
451 if (NON_NEGATIVE && value < 0)
465 throw InvalidArgument(
"cryptest.exe: '" + str +
"' is not an integer value");
472 cout <<
"Using seed: " << seed << endl;
478 tc = omp_get_num_threads();
481 std::cout <<
"Using " << tc <<
" OMP " << (tc == 1 ?
"thread" :
"threads") << std::endl;
489 ss.
Get(result, result.size());
493 void GenerateRSAKey(
unsigned int keyLength,
const char *privFilename,
const char *pubFilename,
const char *seed)
498 RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);
500 priv.DEREncode(privFile);
503 RSAES_OAEP_SHA_Encryptor pub(priv);
505 pub.DEREncode(pubFile);
512 RSAES_OAEP_SHA_Encryptor pub(pubFile);
525 RSAES_OAEP_SHA_Decryptor priv(privFile);
532 void RSASignFile(
const char *privFilename,
const char *messageFilename,
const char *signatureFilename)
539 bool RSAVerifyFile(
const char *pubFilename,
const char *messageFilename,
const char *signatureFilename)
548 signatureFile.
Get(signature, signature.size());
551 verifierFilter->
Put(signature, pub.SignatureLength());
552 FileSource f(messageFilename,
true, verifierFilter);
575 for (i=0; i<filters.
size(); i++)
580 for (i=0; i<filters.
size(); i++)
582 cout << filters[i]->AlgorithmName() <<
": ";
583 filters[i]->TransferTo(encoder);
588 void HmacFile(
const char *hexKey,
const char *file)
591 if (strcmp(hexKey,
"selftest") == 0)
593 cerr <<
"Computing HMAC/SHA1 value for self test.\n";
598 std::string decodedKey;
605 void AES_CTR_Encrypt(
const char *hexKey,
const char *hexIV,
const char *infile,
const char *outfile)
618 encryptor.
Put((
byte *)instr, strlen(instr));
629 decryptor.
Put((
byte *)instr, strlen(instr));
635 void EncryptFile(
const char *in,
const char *out,
const char *passPhrase)
640 void DecryptFile(
const char *in,
const char *out,
const char *passPhrase)
645 void SecretShareFile(
int threshold,
int nShares,
const char *filename,
const char *seed)
648 if (nShares < 1 || nShares > 1000)
659 for (
int i=0; i<nShares; i++)
661 char extension[5] =
".000";
662 extension[1]=
'0'+
byte(i/100);
663 extension[2]=
'0'+
byte((i/10)%10);
664 extension[3]=
'0'+
byte(i%10);
665 fileSinks[i].reset(
new FileSink((
string(filename)+extension).c_str()));
667 channel = WordToString<word32>(i);
668 fileSinks[i]->Put((
const byte *)channel.data(), 4);
678 if (threshold < 1 || threshold > 1000)
686 for (i=0; i<threshold; i++)
688 fileSources[i].reset(
new FileSource(inFilenames[i],
false));
689 fileSources[i]->Pump(4);
690 fileSources[i]->Get(channel, 4);
691 fileSources[i]->Attach(
new ChannelSwitch(recovery,
string((
char *)channel.
begin(), 4)));
694 while (fileSources[0]->Pump(256))
695 for (i=1; i<threshold; i++)
696 fileSources[i]->Pump(256);
698 for (i=0; i<threshold; i++)
699 fileSources[i]->PumpAll();
705 if (threshold < 1 || threshold > 1000)
713 for (
int i=0; i<nShares; i++)
715 char extension[5] =
".000";
716 extension[1]=
'0'+
byte(i/100);
717 extension[2]=
'0'+
byte((i/10)%10);
718 extension[3]=
'0'+
byte(i%10);
719 fileSinks[i].reset(
new FileSink((
string(filename)+extension).c_str()));
721 channel = WordToString<word32>(i);
722 fileSinks[i]->Put((
const byte *)channel.data(), 4);
732 if (threshold < 1 || threshold > 1000)
740 for (i=0; i<threshold; i++)
742 fileSources[i].reset(
new FileSource(inFilenames[i],
false));
743 fileSources[i]->Pump(4);
744 fileSources[i]->Get(channel, 4);
745 fileSources[i]->Attach(
new ChannelSwitch(recovery,
string((
char *)channel.
begin(), 4)));
748 while (fileSources[0]->Pump(256))
749 for (i=1; i<threshold; i++)
750 fileSources[i]->Pump(256);
752 for (i=0; i<threshold; i++)
753 fileSources[i]->PumpAll();
756 void GzipFile(
const char *in,
const char *out,
int deflate_level)
813 void ForwardTcpPort(
const char *sourcePortName,
const char *destinationHost,
const char *destinationPortName)
818 #ifdef SOCKETS_AVAILABLE 819 SocketsInitializer sockInit;
821 Socket sockListen, sockSource, sockDestination;
823 int sourcePort = Socket::PortNameToNumber(sourcePortName);
824 int destinationPort = Socket::PortNameToNumber(destinationPortName);
827 sockListen.Bind(sourcePort);
830 int err = setsockopt(sockListen, IPPROTO_TCP, TCP_NODELAY, (
char*)&flag,
sizeof(
int));
833 throw Socket::Err(sockListen,
"setsockopt", sockListen.GetLastError());
835 cout <<
"Listing on port " << sourcePort <<
".\n";
838 sockListen.Accept(sockSource);
839 cout <<
"Connection accepted on port " << sourcePort <<
".\n";
840 sockListen.CloseSocket();
842 cout <<
"Making connection to " << destinationHost <<
", port " << destinationPort <<
".\n";
843 sockDestination.Create();
844 sockDestination.Connect(destinationHost, destinationPort);
846 cout <<
"Connection made to " << destinationHost <<
", starting to forward.\n";
848 SocketSource out(sockSource,
false,
new SocketSink(sockDestination));
849 SocketSource in(sockDestination,
false,
new SocketSink(sockSource));
853 while (!(in.SourceExhausted() && out.SourceExhausted()))
857 out.GetWaitObjects(waitObjects,
CallStack(
"ForwardTcpPort - out", NULL));
858 in.GetWaitObjects(waitObjects,
CallStack(
"ForwardTcpPort - in", NULL));
862 if (!out.SourceExhausted())
864 cout <<
"o" << flush;
866 if (out.SourceExhausted())
867 cout <<
"EOF received on source socket.\n";
870 if (!in.SourceExhausted())
872 cout <<
"i" << flush;
874 if (in.SourceExhausted())
875 cout <<
"EOF received on destination socket.\n";
879 cout <<
"Socket support was not enabled at compile time.\n";
884 bool Validate(
int alg,
bool thorough,
const char *seedInput)
890 std::string seed = (seedInput ? seedInput :
IntToString(time(NULL)));
891 seed.resize(16,
' ');
894 prng.SetKeyWithIV((
byte *)seed.data(), 16, (
byte *)seed.data());
978 #if defined(CRYPTOPP_DEBUG) && !defined(CRYPTOPP_IMPORTS) 980 case 9999: result = TestSecBlock();
break;
982 case 9998: result = TestPolynomialMod2();
break;
984 case 9997: result = TestIntegerBitops();
break;
986 case 9996: result = TestHuffmanCodes();
break;
988 case 9995: result = TestASN1Parse();
break;
991 default:
return false;
995 #if (CRYPTOPP_MSC_VERSION >= 1400) 1000 const time_t endTime = time(NULL);
1001 err = localtime_s(&localTime, &endTime);
1003 err = asctime_s(timeBuf,
sizeof(timeBuf), &localTime);
1006 cout <<
"\nTest ended at " << timeBuf;
1008 const time_t endTime = time(NULL);
1009 cout <<
"\nTest ended at " << asctime(localtime(&endTime));
1012 cout <<
"Seed used was: " << seed << endl;
void IncorporateEntropy(const byte *input, size_t length)
Update RNG state with additional unpredictable values.
Append input to a string object.
iterator end()
Provides an iterator pointing beyond the last element in the memory block.
CRYPTOPP_DLL MessageAuthenticationCode *CRYPTOPP_API NewIntegrityCheckingMAC()
Class object that calculates the MAC on the module.
An invalid argument was detected.
void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename)
void HexDecode(const char *infile, const char *outfile)
void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
void AddRangeToSkip(unsigned int message, lword position, lword size, bool sortNow=true)
Adds a range to skip during processing.
Randomness Pool based on AES-256.
Filter wrapper for PK_Verifier.
void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames)
bool SafeConvert(T1 from, T2 &to)
Tests whether a conversion from -> to is safe to perform.
void BenchmarkAll(double t, double hertz)
bool ValidateCipherModes()
Classes for RIPEMD message digest.
Class file for Randomness Pool.
void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort)
const int MAX_PHRASE_LENGTH
bool ValidateDSA(bool thorough)
Implementation of Store interface.
Converts given data to base 16.
int CRYPTOPP_API main(int argc, char *argv[])
GZIP Decompression (RFC 1952)
void PumpAll()
Pump all data to attached transformation.
SecByteBlock HexDecodeString(const char *hex)
Decode base 16 data back to bytes.
Abstract base classes that provide a uniform interface to this library.
RIPEMD-160 message digest.
void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed)
void AddDefaultRoute(BufferedTransformation &destination)
size_type size() const
Provides the count of elements in the SecBlock.
RandomNumberGenerator & GlobalRNG()
void FIPS140_SampleApplication()
Classes for automatic resource management.
Filter wrapper for PK_Signer.
Classes for DefaultEncryptor, DefaultDecryptor, DefaultEncryptorWithMAC and DefaultDecryptorWithMAC.
std::hash for asio::adress
Interface for random number generators.
string RSAEncryptString(const char *pubFilename, const char *seed, const char *message)
DataEncryptorWithMAC< DefaultBlockCipher, DefaultHashModule, DefaultMAC, DefaultParametersInfo > DefaultEncryptorWithMAC
void Base64Encode(const char *infile, const char *outfile)
Route input to different and/or multiple channels based on channel ID.
Pointer that overloads operator ->
const std::string DEFAULT_CHANNEL
Default channel for BufferedTransformation.
Copy input to a memory buffer.
T StringToValue(const std::string &str)
void GzipFile(const char *in, const char *out, int deflate_level)
GZIP compression and decompression (RFC 1952)
void SetAutoSignalPropagation(int propagation)
void BenchmarkAll2(double t, double hertz)
Filter wrapper for HashTransformation.
Password-based encryptor with MAC.
RNG-based implementation of Source interface.
Block cipher mode of operation aggregate.
int(* AdhocTest)(int argc, char *argv[])
Utility class for trapping OS signals.
string EncryptString(const char *plaintext, const char *passPhrase)
signed long ConvertToLong() const
Convert the Integer to Long.
string DecryptString(const char *ciphertext, const char *passPhrase)
bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true)
Marks the end of a series of messages on a channel.
void HexEncode(const char *infile, const char *outfile)
Maurer's Universal Statistical Test for Random Bit Generators.
Class file for the AES cipher (Rijndael)
bool ValidateAll(bool thorough)
void InformationDisperseFile(int threshold, int nShares, const char *filename)
Manages resources for an array of objects.
bool Validate(int, bool, const char *)
Multiple precision integer with arithmetic operations.
bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename)
Filter wrapper for PK_Decryptor.
void GunzipFile(const char *in, const char *out)
Classes and functions for registering and locating library objects.
Miscellaneous classes for RNGs.
void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile)
DataDecryptorWithMAC< DefaultBlockCipher, DefaultHashModule, DefaultMAC, DefaultParametersInfo > DefaultDecryptorWithMAC
void FIPS140_GenerateRandomFiles()
#define CRYPTOPP_ASSERT(exp)
void PrintSeedAndThreads(const std::string &seed)
const unsigned long INFINITE_TIME
Represents infinite time.
bool GetLastResult() const
Retrieves the result of the last verification.
iterator begin()
Provides an iterator pointing to the first element in the memory block.
void DecryptFile(const char *in, const char *out, const char *passPhrase)
Implementation of BufferedTransformation's attachment interface.
Implementation of Store interface.
int StringToValue< int, true >(const std::string &str)
#define USING_NAMESPACE(x)
Filter wrapper for PK_Encryptor.
Classes for the Base64Encoder, Base64Decoder, Base64URLEncoder and Base64URLDecoder.
#define CRYPTOPP_DUMMY_DLL_MAC
The placeholder used prior to embedding the actual MAC in the module.
Internal SHA-512 implementation.
#define CRYPTOPP_UNUSED(x)
h256 sha256(bytesConstRef _input)
Debugging and diagnostic assertions.
void Base64Decode(const char *infile, const char *outfile)
SignatureVerificationFilter VerifierFilter
std::string IntToString(T value, unsigned int base=10)
Converts a value to a string.
Measure how many bytes and messages pass through the filter.
string RSADecryptString(const char *privFilename, const char *ciphertext)
A filter that checks messages on two channels for equality.
bool RunTestDataFile(const char *filename, const NameValuePairs &overrideParameters, bool thorough)
GZIP Compression (RFC 1952)
double GetTestValue() const
Shamir's Secret Sharing Algorithm.
void EncryptFile(const char *in, const char *out, const char *passPhrase)
Implementation of Store interface.
Functions and definitions required for building the FIPS-140 DLL on Windows.
void HmacFile(const char *hexKey, const char *file)
#define CRYPTOPP_DATA_DIR
Shamir's Secret Sharing Algorithm.
void DigestFile(const char *file)
Classes for Rabin's Information Dispersal and Shamir's Secret Sharing algorithms. ...
void AddRoute(const std::string &inChannel, BufferedTransformation &destination, const std::string &outChannel)
void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed)
Template implementing constructors for public key algorithm classes.