📄 test.cpp
字号:
// test.cpp - written and placed in the public domain by Wei Dai
#define CRYPTOPP_DEFAULT_NO_DLL
#include "dll.h"
#include "md5.h"
#include "ripemd.h"
#include "rng.h"
#include "gzip.h"
#include "default.h"
#include "randpool.h"
#include "ida.h"
#include "base64.h"
#include "socketft.h"
#include "wait.h"
#include "factory.h"
#include "validate.h"
#include "bench.h"
#include <iostream>
#include <time.h>
#ifdef CRYPTOPP_WIN32_AVAILABLE
#include <windows.h>
#endif
#if defined(USE_BERKELEY_STYLE_SOCKETS) && !defined(macintosh)
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
#if (_MSC_VER >= 1000)
#include <crtdbg.h> // for the debug heap
#endif
#if defined(__MWERKS__) && defined(macintosh)
#include <console.h>
#endif
USING_NAMESPACE(CryptoPP)
USING_NAMESPACE(std)
const int MAX_PHRASE_LENGTH=250;
void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed);
string RSAEncryptString(const char *pubFilename, const char *seed, const char *message);
string RSADecryptString(const char *privFilename, const char *ciphertext);
void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename);
bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename);
void DigestFile(const char *file);
void HmacFile(const char *hexKey, const char *file);
void AES_CTR_Encrypt(const char *hexKey, const char *hexIV, const char *infile, const char *outfile);
string EncryptString(const char *plaintext, const char *passPhrase);
string DecryptString(const char *ciphertext, const char *passPhrase);
void EncryptFile(const char *in, const char *out, const char *passPhrase);
void DecryptFile(const char *in, const char *out, const char *passPhrase);
void SecretShareFile(int threshold, int nShares, const char *filename, const char *seed);
void SecretRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
void InformationDisperseFile(int threshold, int nShares, const char *filename);
void InformationRecoverFile(int threshold, const char *outFilename, char *const *inFilenames);
void GzipFile(const char *in, const char *out, int deflate_level);
void GunzipFile(const char *in, const char *out);
void Base64Encode(const char *infile, const char *outfile);
void Base64Decode(const char *infile, const char *outfile);
void HexEncode(const char *infile, const char *outfile);
void HexDecode(const char *infile, const char *outfile);
void ForwardTcpPort(const char *sourcePort, const char *destinationHost, const char *destinationPort);
void FIPS140_SampleApplication();
void FIPS140_GenerateRandomFiles();
bool Validate(int, bool, const char *);
int (*AdhocTest)(int argc, char *argv[]) = NULL;
#ifdef __BCPLUSPLUS__
int cmain(int argc, char *argv[])
#else
int CRYPTOPP_CDECL main(int argc, char *argv[])
#endif
{
#ifdef _CRTDBG_LEAK_CHECK_DF
// Turn on leak-checking
int tempflag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG );
tempflag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag( tempflag );
#endif
#if defined(__MWERKS__) && defined(macintosh)
argc = ccommand(&argv);
#endif
try
{
std::string command, executableName, macFilename;
if (argc < 2)
command = 'h';
else
command = argv[1];
if (command == "g")
{
char seed[1024], privFilename[128], pubFilename[128];
unsigned int keyLength;
cout << "Key length in bits: ";
cin >> keyLength;
cout << "\nSave private key to file: ";
cin >> privFilename;
cout << "\nSave public key to file: ";
cin >> pubFilename;
cout << "\nRandom Seed: ";
ws(cin);
cin.getline(seed, 1024);
GenerateRSAKey(keyLength, privFilename, pubFilename, seed);
}
else if (command == "rs")
RSASignFile(argv[2], argv[3], argv[4]);
else if (command == "rv")
{
bool verified = RSAVerifyFile(argv[2], argv[3], argv[4]);
cout << (verified ? "valid signature" : "invalid signature") << endl;
}
else if (command == "r")
{
char privFilename[128], pubFilename[128];
char seed[1024], message[1024];
cout << "Private key file: ";
cin >> privFilename;
cout << "\nPublic key file: ";
cin >> pubFilename;
cout << "\nRandom Seed: ";
ws(cin);
cin.getline(seed, 1024);
cout << "\nMessage: ";
cin.getline(message, 1024);
string ciphertext = RSAEncryptString(pubFilename, seed, message);
cout << "\nCiphertext: " << ciphertext << endl;
string decrypted = RSADecryptString(privFilename, ciphertext.c_str());
cout << "\nDecrypted: " << decrypted << endl;
}
else if (command == "mt")
{
MaurerRandomnessTest mt;
FileStore fs(argv[2]);
fs.TransferAllTo(mt);
cout << "Maurer Test Value: " << mt.GetTestValue() << endl;
}
#ifdef CRYPTOPP_WIN32_AVAILABLE
else if (command == "mac_dll")
{
HMODULE hModule = LoadLibrary(argv[2]);
PGetPowerUpSelfTestStatus pGetPowerUpSelfTestStatus = (PGetPowerUpSelfTestStatus)GetProcAddress(hModule, "?GetPowerUpSelfTestStatus@CryptoPP@@YG?AW4PowerUpSelfTestStatus@1@XZ");
PGetActualMacAndLocation pGetActualMacAndLocation = (PGetActualMacAndLocation)GetProcAddress(hModule, "?GetActualMacAndLocation@CryptoPP@@YGPBEAAI0@Z");
PowerUpSelfTestStatus status = pGetPowerUpSelfTestStatus();
if (status == POWER_UP_SELF_TEST_PASSED)
{
cout << "Crypto++ DLL MAC is valid. Nothing to do.\n";
return 0;
}
unsigned int macSize, macFileLocation;
const byte *pMac = pGetActualMacAndLocation(macSize, macFileLocation);
if (macFileLocation == 0)
{
cerr << "Could not find MAC location in Crypto++ DLL.\n";
return 1;
}
else
{
SecByteBlock mac(pMac, macSize); // copy MAC before freeing the DLL
BOOL r = FreeLibrary(hModule);
cout << "Placing MAC in file " << argv[2] << ", location " << macFileLocation << ".\n";
std::ofstream dllFile(argv[2], ios::in | ios::out | ios::binary);
dllFile.seekp(macFileLocation);
dllFile.write((const char *)mac.data(), macSize);
if (!dllFile.good())
{
cerr << "Error writing file.\n";
return 1;
}
}
}
#endif
else if (command == "m")
DigestFile(argv[2]);
else if (command == "tv")
return !RunTestDataFile(argv[2]);
else if (command == "t")
{
// VC60 workaround: use char array instead of std::string to workaround MSVC's getline bug
char passPhrase[MAX_PHRASE_LENGTH], plaintext[1024];
cout << "Passphrase: ";
cin.getline(passPhrase, MAX_PHRASE_LENGTH);
cout << "\nPlaintext: ";
cin.getline(plaintext, 1024);
string ciphertext = EncryptString(plaintext, passPhrase);
cout << "\nCiphertext: " << ciphertext << endl;
string decrypted = DecryptString(ciphertext.c_str(), passPhrase);
cout << "\nDecrypted: " << decrypted << endl;
return 0;
}
else if (command == "e64")
Base64Encode(argv[2], argv[3]);
else if (command == "d64")
Base64Decode(argv[2], argv[3]);
else if (command == "e16")
HexEncode(argv[2], argv[3]);
else if (command == "d16")
HexDecode(argv[2], argv[3]);
else if (command == "e" || command == "d")
{
char passPhrase[MAX_PHRASE_LENGTH];
cout << "Passphrase: ";
cin.getline(passPhrase, MAX_PHRASE_LENGTH);
if (command == "e")
EncryptFile(argv[2], argv[3], passPhrase);
else
DecryptFile(argv[2], argv[3], passPhrase);
}
else if (command == "ss")
{
char seed[1024];
cout << "\nRandom Seed: ";
ws(cin);
cin.getline(seed, 1024);
SecretShareFile(atoi(argv[2]), atoi(argv[3]), argv[4], seed);
}
else if (command == "sr")
SecretRecoverFile(argc-3, argv[2], argv+3);
else if (command == "id")
InformationDisperseFile(atoi(argv[2]), atoi(argv[3]), argv[4]);
else if (command == "ir")
InformationRecoverFile(argc-3, argv[2], argv+3);
else if (command == "v")
return !Validate(argc>2 ? atoi(argv[2]) : 0, argv[1][1] == 'v', argc>3 ? argv[3] : NULL);
else if (command == "b")
BenchmarkAll(argc<3 ? 1 : atof(argv[2]));
else if (command == "b2")
BenchmarkAll2(argc<3 ? 1 : atof(argv[2]));
else if (command == "z")
GzipFile(argv[3], argv[4], argv[2][0]-'0');
else if (command == "u")
GunzipFile(argv[2], argv[3]);
else if (command == "fips")
FIPS140_SampleApplication();
else if (command == "fips-rand")
FIPS140_GenerateRandomFiles();
else if (command == "ft")
ForwardTcpPort(argv[2], argv[3], argv[4]);
else if (command == "a")
{
if (AdhocTest)
return (*AdhocTest)(argc, argv);
else
{
cerr << "AdhocTest not defined.\n";
return 1;
}
}
else if (command == "hmac")
HmacFile(argv[2], argv[3]);
else if (command == "ae")
AES_CTR_Encrypt(argv[2], argv[3], argv[4], argv[5]);
else if (command == "h")
{
FileSource usage("usage.dat", true, new FileSink(cout));
return 1;
}
else
{
cerr << "Unrecognized command. Run \"cryptest h\" to obtain usage information.\n";
return 1;
}
return 0;
}
catch(CryptoPP::Exception &e)
{
cout << "\nCryptoPP::Exception caught: " << e.what() << endl;
return -1;
}
catch(std::exception &e)
{
cout << "\nstd::exception caught: " << e.what() << endl;
return -2;
}
}
void FIPS140_GenerateRandomFiles()
{
#ifdef OS_RNG_AVAILABLE
AutoSeededX917RNG<DES_EDE3> rng;
RandomNumberStore store(rng, ULONG_MAX);
for (unsigned int i=0; i<100000; i++)
store.TransferTo(FileSink((IntToString(i) + ".rnd").c_str()).Ref(), 20000);
#else
cout << "OS provided RNG not available.\n";
exit(-1);
#endif
}
SecByteBlock HexDecodeString(const char *hex)
{
StringSource ss(hex, true, new HexDecoder);
SecByteBlock result(ss.MaxRetrievable());
ss.Get(result, result.size());
return result;
}
RandomPool & GlobalRNG()
{
static RandomPool randomPool;
return randomPool;
}
void GenerateRSAKey(unsigned int keyLength, const char *privFilename, const char *pubFilename, const char *seed)
{
RandomPool randPool;
randPool.Put((byte *)seed, strlen(seed));
RSAES_OAEP_SHA_Decryptor priv(randPool, keyLength);
HexEncoder privFile(new FileSink(privFilename));
priv.DEREncode(privFile);
privFile.MessageEnd();
RSAES_OAEP_SHA_Encryptor pub(priv);
HexEncoder pubFile(new FileSink(pubFilename));
pub.DEREncode(pubFile);
pubFile.MessageEnd();
}
string RSAEncryptString(const char *pubFilename, const char *seed, const char *message)
{
FileSource pubFile(pubFilename, true, new HexDecoder);
RSAES_OAEP_SHA_Encryptor pub(pubFile);
RandomPool randPool;
randPool.Put((byte *)seed, strlen(seed));
string result;
StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new HexEncoder(new StringSink(result))));
return result;
}
string RSADecryptString(const char *privFilename, const char *ciphertext)
{
FileSource privFile(privFilename, true, new HexDecoder);
RSAES_OAEP_SHA_Decryptor priv(privFile);
string result;
StringSource(ciphertext, true, new HexDecoder(new PK_DecryptorFilter(GlobalRNG(), priv, new StringSink(result))));
return result;
}
void RSASignFile(const char *privFilename, const char *messageFilename, const char *signatureFilename)
{
FileSource privFile(privFilename, true, new HexDecoder);
RSASSA_PKCS1v15_SHA_Signer priv(privFile);
FileSource f(messageFilename, true, new SignerFilter(GlobalRNG(), priv, new HexEncoder(new FileSink(signatureFilename))));
}
bool RSAVerifyFile(const char *pubFilename, const char *messageFilename, const char *signatureFilename)
{
FileSource pubFile(pubFilename, true, new HexDecoder);
RSASSA_PKCS1v15_SHA_Verifier pub(pubFile);
FileSource signatureFile(signatureFilename, true, new HexDecoder);
if (signatureFile.MaxRetrievable() != pub.SignatureLength())
return false;
SecByteBlock signature(pub.SignatureLength());
signatureFile.Get(signature, signature.size());
VerifierFilter *verifierFilter = new VerifierFilter(pub);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -