bool ValidateGCM() { std::cout << "\nAES/GCM validation suite running...\n"; std::cout << "\n2K tables:"; bool pass = RunTestDataFile("TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)2048)); std::cout << "\n64K tables:"; return RunTestDataFile("TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)64*1024)) && pass; }
void BenchMarkByName2(const char *factoryName, size_t keyLength = 0, const char *displayName=NULL, const NameValuePairs ¶ms = g_nullNameValuePairs, T_FactoryOutput *x=NULL, T_Interface *y=NULL) { std::string name = factoryName; if (displayName) name = displayName; else if (keyLength) name += " (" + IntToString(keyLength * 8) + "-bit key)"; std::auto_ptr<T_FactoryOutput> obj(ObjectFactoryRegistry<T_FactoryOutput>::Registry().CreateObject(factoryName)); if (!keyLength) keyLength = obj->DefaultKeyLength(); obj->SetKey(key, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(key, obj->IVSize()), false))); BenchMark(name.c_str(), *static_cast<T_Interface *>(obj.get()), g_allocatedTime); BenchMarkKeying(*obj, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(key, obj->IVSize()), false))); }
// generate a random private key void InvertibleRWFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg) { int modulusSize = 2048; alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize); if (modulusSize < 16) throw InvalidArgument("InvertibleRWFunction: specified modulus length is too small"); AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize); m_p.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 3)("Mod", 8))); m_q.GenerateRandom(rng, CombinedNameValuePairs(primeParam, MakeParameters("EquivalentTo", 7)("Mod", 8))); m_n = m_p * m_q; m_u = m_q.InverseMod(m_p); }
void DL_GroupParameters_DSA::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg) { Integer p, q, g; if (alg.GetValue("Modulus", p) && alg.GetValue("SubgroupGenerator", g)) { q = alg.GetValueWithDefault("SubgroupOrder", ComputeGroupOrder(p)/2); Initialize(p, q, g); } else { int modulusSize = 1024, defaultSubgroupOrderSize; alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize); switch (modulusSize) { case 1024: defaultSubgroupOrderSize = 160; break; case 2048: defaultSubgroupOrderSize = 224; break; case 3072: defaultSubgroupOrderSize = 256; break; default: throw InvalidArgument("DSA: not a valid prime length"); } DL_GroupParameters_GFP::GenerateRandom(rng, CombinedNameValuePairs(alg, MakeParameters(Name::SubgroupOrderSize(), defaultSubgroupOrderSize, false))); } }
void HexEncoder::IsolatedInitialize(const NameValuePairs ¶meters) { bool uppercase = parameters.GetValueWithDefault(Name::Uppercase(), true); m_filter->Initialize(CombinedNameValuePairs( parameters, MakeParameters(Name::EncodingLookupArray(), uppercase ? &s_vecUpper[0] : &s_vecLower[0], false)(Name::Log2Base(), 4, true))); }
AuthenticatedDecryptionFilter::AuthenticatedDecryptionFilter(AuthenticatedSymmetricCipher &c, BufferedTransformation *attachment, word32 flags, int truncatedDigestSize, BlockPaddingScheme padding) : FilterWithBufferedInput(attachment) , m_hashVerifier(c, new OutputProxy(*this, false)) , m_streamFilter(c, new OutputProxy(*this, false), padding, true) { assert(!c.IsForwardTransformation() || c.IsSelfInverting()); IsolatedInitialize(MakeParameters(Name::BlockPaddingScheme(), padding)(Name::AuthenticatedDecryptionFilterFlags(), flags)(Name::TruncatedDigestSize(), truncatedDigestSize)); }
void BenchMarkByName2(const char *factoryName, size_t keyLength = 0, const char *displayName=NULLPTR, const NameValuePairs ¶ms = g_nullNameValuePairs) { std::string name(factoryName ? factoryName : ""); member_ptr<T_FactoryOutput> obj(ObjectFactoryRegistry<T_FactoryOutput>::Registry().CreateObject(name.c_str())); if (!keyLength) keyLength = obj->DefaultKeyLength(); if (displayName) name = displayName; else if (keyLength) name += " (" + IntToString(keyLength * 8) + "-bit key)"; const int blockSize = params.GetIntValueWithDefault(Name::BlockSize(), 0); obj->SetKey(defaultKey, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(defaultKey, blockSize ? blockSize : obj->IVSize()), false))); BenchMark(name.c_str(), *static_cast<T_Interface *>(obj.get()), g_allocatedTime); BenchMarkKeying(*obj, keyLength, CombinedNameValuePairs(params, MakeParameters(Name::IV(), ConstByteArrayParameter(defaultKey, blockSize ? blockSize : obj->IVSize()), false))); }
StreamTransformationFilter::StreamTransformationFilter(StreamTransformation &c, BufferedTransformation *attachment, BlockPaddingScheme padding, bool allowAuthenticatedSymmetricCipher) : FilterWithBufferedInput(attachment) , m_cipher(c), m_padding(DEFAULT_PADDING), m_optimalBufferSize(0) { assert(c.MinLastBlockSize() == 0 || c.MinLastBlockSize() > c.MandatoryBlockSize()); if (!allowAuthenticatedSymmetricCipher && dynamic_cast<AuthenticatedSymmetricCipher *>(&c) != 0) throw InvalidArgument("StreamTransformationFilter: please use AuthenticatedEncryptionFilter and AuthenticatedDecryptionFilter for AuthenticatedSymmetricCipher"); IsolatedInitialize(MakeParameters(Name::BlockPaddingScheme(), padding)); }
void AuthenticatedDecryptionFilter::InitializeDerivedAndReturnNewSizes(const NameValuePairs ¶meters, size_t &firstSize, size_t &blockSize, size_t &lastSize) { word32 flags = parameters.GetValueWithDefault(Name::AuthenticatedDecryptionFilterFlags(), (word32)DEFAULT_FLAGS); m_hashVerifier.Initialize(CombinedNameValuePairs(parameters, MakeParameters(Name::HashVerificationFilterFlags(), flags))); m_streamFilter.Initialize(parameters); firstSize = m_hashVerifier.m_firstSize; blockSize = 1; lastSize = m_hashVerifier.m_lastSize; }
void Base64Encoder::IsolatedInitialize(const NameValuePairs ¶meters) { bool insertLineBreaks = parameters.GetValueWithDefault(Name::InsertLineBreaks(), true); int maxLineLength = parameters.GetIntValueWithDefault(Name::MaxLineLength(), 72); const char *lineBreak = insertLineBreaks ? "\n" : ""; m_filter->Initialize(CombinedNameValuePairs( parameters, MakeParameters(Name::EncodingLookupArray(), &s_vec[0], false) (Name::PaddingByte(), s_padding) (Name::GroupSize(), insertLineBreaks ? maxLineLength : 0) (Name::Separator(), ConstByteArrayParameter(lineBreak)) (Name::Terminator(), ConstByteArrayParameter(lineBreak)) (Name::Log2Base(), 6, true))); }
AlgorithmParameters<AlgorithmParameters<AlgorithmParameters<NullNameValuePairs, Integer::RandomNumberType>, Integer>, Integer> MakeParametersForTwoPrimesOfEqualSize(unsigned int productBitLength) { if (productBitLength < 16) throw InvalidArgument("invalid bit length"); Integer minP, maxP; if (productBitLength%2==0) { minP = Integer(182) << (productBitLength/2-8); maxP = Integer::Power2(productBitLength/2)-1; } else { minP = Integer::Power2((productBitLength-1)/2); maxP = Integer(181) << ((productBitLength+1)/2-8); } return MakeParameters("RandomNumberType", Integer::PRIME)("Min", minP)("Max", maxP); }
bool ValidateESIGN() { cout << "\nESIGN validation suite running...\n\n"; bool pass = true, fail; static const char plain[] = "test"; static const byte signature[] = "\xA3\xE3\x20\x65\xDE\xDA\xE7\xEC\x05\xC1\xBF\xCD\x25\x79\x7D\x99\xCD\xD5\x73\x9D\x9D\xF3\xA4\xAA\x9A\xA4\x5A\xC8\x23\x3D\x0D\x37\xFE\xBC\x76\x3F\xF1\x84\xF6\x59" "\x14\x91\x4F\x0C\x34\x1B\xAE\x9A\x5C\x2E\x2E\x38\x08\x78\x77\xCB\xDC\x3C\x7E\xA0\x34\x44\x5B\x0F\x67\xD9\x35\x2A\x79\x47\x1A\x52\x37\x71\xDB\x12\x67\xC1\xB6\xC6" "\x66\x73\xB3\x40\x2E\xD6\xF2\x1A\x84\x0A\xB6\x7B\x0F\xEB\x8B\x88\xAB\x33\xDD\xE4\x83\x21\x90\x63\x2D\x51\x2A\xB1\x6F\xAB\xA7\x5C\xFD\x77\x99\xF2\xE1\xEF\x67\x1A" "\x74\x02\x37\x0E\xED\x0A\x06\xAD\xF4\x15\x65\xB8\xE1\xD1\x45\xAE\x39\x19\xB4\xFF\x5D\xF1\x45\x7B\xE0\xFE\x72\xED\x11\x92\x8F\x61\x41\x4F\x02\x00\xF2\x76\x6F\x7C" "\x79\xA2\xE5\x52\x20\x5D\x97\x5E\xFE\x39\xAE\x21\x10\xFB\x35\xF4\x80\x81\x41\x13\xDD\xE8\x5F\xCA\x1E\x4F\xF8\x9B\xB2\x68\xFB\x28"; FileSource keys("TestData/esig1536.dat", true, new HexDecoder); ESIGN<SHA>::Signer signer(keys); ESIGN<SHA>::Verifier verifier(signer); fail = !SignatureValidate(signer, verifier); pass = pass && !fail; fail = !verifier.VerifyMessage((byte *)plain, strlen(plain), signature, verifier.SignatureLength()); pass = pass && !fail; cout << (fail ? "FAILED " : "passed "); cout << "verification check against test vector\n"; cout << "Generating signature key from seed..." << endl; signer.AccessKey().GenerateRandom(GlobalRNG(), MakeParameters("Seed", ConstByteArrayParameter((const byte *)"test", 4))("KeySize", 3*512)); verifier = signer; fail = !SignatureValidate(signer, verifier); pass = pass && !fail; return pass; }
HashVerificationFilter::HashVerificationFilter(HashTransformation &hm, BufferedTransformation *attachment, word32 flags, int truncatedDigestSize) : FilterWithBufferedInput(attachment) , m_hashModule(hm), m_flags(0), m_digestSize(0), m_verified(false) { IsolatedInitialize(MakeParameters(Name::HashVerificationFilterFlags(), flags)(Name::TruncatedDigestSize(), truncatedDigestSize)); }
void BenchMarkKeyedVariable(const char *name, double timeTotal, unsigned int keyLength, T *x=NULL) { T c; c.SetKey(key, keyLength, MakeParameters(Name::IV(), key, false)); BenchMark(name, c, timeTotal); }
void Benchmark2(double t, double hertz) { g_allocatedTime = t; g_hertz = hertz; const char *cpb, *cpk; if (g_hertz > 1.0f) { cpb = "<TH>Cycles Per Byte"; cpk = "<TH>Cycles to<BR>Setup Key and IV"; } else { cpb = cpk = ""; } std::cout << "\n<TABLE>"; std::cout << "\n<COLGROUP><COL style=\"text-align: left;\"><COL style=\"text-align: right;\"><COL style="; std::cout << "\"text-align: right;\"><COL style=\"text-align: right;\"><COL style=\"text-align: right;\">"; std::cout << "\n<THEAD style=\"background: #F0F0F0\">"; std::cout << "\n<TR><TH>Algorithm<TH>MiB/Second" << cpb; std::cout << "<TH>Microseconds to<BR>Setup Key and IV" << cpk; std::cout << "\n<TBODY style=\"background: white;\">"; { #if CRYPTOPP_AESNI_AVAILABLE if (HasCLMUL()) BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES)"); else #elif CRYPTOPP_ARM_PMULL_AVAILABLE if (HasPMULL()) BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES)"); else #endif { BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES) (2K tables)", MakeParameters(Name::TableSize(), 2048)); BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES) (64K tables)", MakeParameters(Name::TableSize(), 64 * 1024)); } BenchMarkByName<MessageAuthenticationCode>("VMAC(AES)-64"); BenchMarkByName<MessageAuthenticationCode>("VMAC(AES)-128"); BenchMarkByName<MessageAuthenticationCode>("HMAC(SHA-1)"); BenchMarkByName<MessageAuthenticationCode>("HMAC(SHA-256)"); BenchMarkByName<MessageAuthenticationCode>("Two-Track-MAC"); BenchMarkByName<MessageAuthenticationCode>("CMAC(AES)"); BenchMarkByName<MessageAuthenticationCode>("DMAC(AES)"); BenchMarkByName<MessageAuthenticationCode>("Poly1305(AES)"); BenchMarkByName<MessageAuthenticationCode>("BLAKE2s"); BenchMarkByName<MessageAuthenticationCode>("BLAKE2b"); BenchMarkByName<MessageAuthenticationCode>("SipHash-2-4"); BenchMarkByName<MessageAuthenticationCode>("SipHash-4-8"); } std::cout << "\n<TBODY style=\"background: yellow;\">"; { BenchMarkByName<SymmetricCipher>("Panama-LE"); BenchMarkByName<SymmetricCipher>("Panama-BE"); BenchMarkByName<SymmetricCipher>("Salsa20"); BenchMarkByName<SymmetricCipher>("Salsa20", 0, "Salsa20/12", MakeParameters(Name::Rounds(), 12)); BenchMarkByName<SymmetricCipher>("Salsa20", 0, "Salsa20/8", MakeParameters(Name::Rounds(), 8)); BenchMarkByName<SymmetricCipher>("ChaCha20"); BenchMarkByName<SymmetricCipher>("ChaCha12"); BenchMarkByName<SymmetricCipher>("ChaCha8"); BenchMarkByName<SymmetricCipher>("Sosemanuk"); BenchMarkByName<SymmetricCipher>("MARC4"); BenchMarkByName<SymmetricCipher>("SEAL-3.0-LE"); BenchMarkByName<SymmetricCipher>("WAKE-OFB-LE"); } std::cout << "\n<TBODY style=\"background: white;\">"; { BenchMarkByName<SymmetricCipher>("AES/CTR", 16); BenchMarkByName<SymmetricCipher>("AES/CTR", 24); BenchMarkByName<SymmetricCipher>("AES/CTR", 32); BenchMarkByName<SymmetricCipher>("AES/CBC", 16); BenchMarkByName<SymmetricCipher>("AES/CBC", 24); BenchMarkByName<SymmetricCipher>("AES/CBC", 32); BenchMarkByName<SymmetricCipher>("AES/OFB", 16); BenchMarkByName<SymmetricCipher>("AES/CFB", 16); BenchMarkByName<SymmetricCipher>("AES/ECB", 16); BenchMarkByName<SymmetricCipher>("ARIA/CTR", 16); BenchMarkByName<SymmetricCipher>("ARIA/CTR", 32); BenchMarkByName<SymmetricCipher>("Camellia/CTR", 16); BenchMarkByName<SymmetricCipher>("Camellia/CTR", 32); BenchMarkByName<SymmetricCipher>("Twofish/CTR"); BenchMarkByName<SymmetricCipher>("Threefish-256(256)/CTR", 32); BenchMarkByName<SymmetricCipher>("Threefish-512(512)/CTR", 64); BenchMarkByName<SymmetricCipher>("Threefish-1024(1024)/CTR", 128); BenchMarkByName<SymmetricCipher>("Serpent/CTR"); BenchMarkByName<SymmetricCipher>("CAST-128/CTR"); BenchMarkByName<SymmetricCipher>("CAST-256/CTR"); BenchMarkByName<SymmetricCipher>("RC6/CTR"); BenchMarkByName<SymmetricCipher>("MARS/CTR"); BenchMarkByName<SymmetricCipher>("SHACAL-2/CTR", 16); BenchMarkByName<SymmetricCipher>("SHACAL-2/CTR", 64); BenchMarkByName<SymmetricCipher>("DES/CTR"); BenchMarkByName<SymmetricCipher>("DES-XEX3/CTR"); BenchMarkByName<SymmetricCipher>("DES-EDE3/CTR"); BenchMarkByName<SymmetricCipher>("IDEA/CTR"); BenchMarkByName<SymmetricCipher>("RC5/CTR", 0, "RC5 (r=16)"); BenchMarkByName<SymmetricCipher>("Blowfish/CTR"); BenchMarkByName<SymmetricCipher>("TEA/CTR"); BenchMarkByName<SymmetricCipher>("XTEA/CTR"); BenchMarkByName<SymmetricCipher>("SKIPJACK/CTR"); BenchMarkByName<SymmetricCipher>("SEED/CTR", 0, "SEED/CTR (1/2 K table)"); BenchMarkByName<SymmetricCipher>("SM4/CTR"); BenchMarkByName<SymmetricCipher>("Kalyna-128/CTR", 16, "Kalyna-128(128)/CTR (128-bit key)"); BenchMarkByName<SymmetricCipher>("Kalyna-128/CTR", 32, "Kalyna-128(256)/CTR (256-bit key)"); BenchMarkByName<SymmetricCipher>("Kalyna-256/CTR", 32, "Kalyna-256(256)/CTR (256-bit key)"); BenchMarkByName<SymmetricCipher>("Kalyna-256/CTR", 64, "Kalyna-256(512)/CTR (512-bit key)"); BenchMarkByName<SymmetricCipher>("Kalyna-512/CTR", 64, "Kalyna-512(512)/CTR (512-bit key)"); BenchMarkByName<SymmetricCipher>("SIMON-64/CTR", 12, "SIMON-64(96)/CTR (96-bit key)"); BenchMarkByName<SymmetricCipher>("SIMON-64/CTR", 16, "SIMON-64(128)/CTR (128-bit key)"); BenchMarkByName<SymmetricCipher>("SIMON-128/CTR", 16, "SIMON-128(128)/CTR (128-bit key)"); BenchMarkByName<SymmetricCipher>("SIMON-128/CTR", 24, "SIMON-128(192)/CTR (192-bit key)"); BenchMarkByName<SymmetricCipher>("SIMON-128/CTR", 32, "SIMON-128(256)/CTR (256-bit key)"); BenchMarkByName<SymmetricCipher>("SPECK-64/CTR", 12, "SPECK-64(96)/CTR (96-bit key)"); BenchMarkByName<SymmetricCipher>("SPECK-64/CTR", 16, "SPECK-64(128)/CTR (128-bit key)"); BenchMarkByName<SymmetricCipher>("SPECK-128/CTR", 16, "SPECK-128(128)/CTR (128-bit key)"); BenchMarkByName<SymmetricCipher>("SPECK-128/CTR", 24, "SPECK-128(192)/CTR (192-bit key)"); BenchMarkByName<SymmetricCipher>("SPECK-128/CTR", 32, "SPECK-128(256)/CTR (256-bit key)"); } std::cout << "\n<TBODY style=\"background: yellow;\">"; { #if CRYPTOPP_AESNI_AVAILABLE if (HasCLMUL()) BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM"); else #elif CRYPTOPP_ARM_PMULL_AVAILABLE if (HasPMULL()) BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM"); else #endif { BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM (2K tables)", MakeParameters(Name::TableSize(), 2048)); BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM (64K tables)", MakeParameters(Name::TableSize(), 64 * 1024)); } BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/CCM"); BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/EAX"); } std::cout << "\n</TABLE>" << std::endl; }
void GeneratableCryptoMaterial::GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize) { GenerateRandom(rng, MakeParameters("KeySize", (int)keySize)); }
void SimpleKeyingInterface::SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength) { SetKey(key, length, MakeParameters(Name::IV(), ConstByteArrayParameter(iv, ivLength))); }
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) { std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC()); unsigned int macSize = mac->DigestSize(); SecByteBlock tempMac; SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; actualMac.resize(macSize); unsigned long tempLocation; unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; macFileLocation = 0; HashFilter verifier(*mac, new ArraySink(actualMac, actualMac.size())); // FileSink verifier("c:\\dt.tmp"); FileStore file(moduleFilename); #ifdef CRYPTOPP_WIN32_AVAILABLE // try to hash from memory first HMODULE h = GetModuleHandle(moduleFilename); const byte *memBase = (const byte *)h; IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)h; IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)((byte *)h + ph->e_lfanew); IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); DWORD nSections = phnt->FileHeader.NumberOfSections; DWORD currentFilePos = 0; while (nSections--) { switch (phs->Characteristics) { default: break; case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); const byte *sectionMemStart = memBase + phs->VirtualAddress; unsigned int sectionFileStart = phs->PointerToRawData; unsigned int subSectionStart = 0, nextSubSectionStart; do { const byte *subSectionMemStart = sectionMemStart + subSectionStart; unsigned int subSectionFileStart = sectionFileStart + subSectionStart; unsigned int subSectionSize = sectionSize - subSectionStart; nextSubSectionStart = 0; unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT}; for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++) { const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]]; const byte *entryMemStart = memBase + entry.VirtualAddress; if (subSectionMemStart <= entryMemStart && entryMemStart < subSectionMemStart + subSectionSize) { subSectionSize = entryMemStart - subSectionMemStart; nextSubSectionStart = entryMemStart - sectionMemStart + entry.Size; } } file.TransferTo(verifier, subSectionFileStart - currentFilePos); if (subSectionMemStart <= expectedModuleMac && expectedModuleMac < subSectionMemStart + subSectionSize) { // skip over the MAC verifier.Put(subSectionMemStart, expectedModuleMac - subSectionMemStart); verifier.Put(expectedModuleMac + macSize, subSectionSize - macSize - (expectedModuleMac - subSectionMemStart)); macFileLocation = subSectionFileStart + (expectedModuleMac - subSectionMemStart); } else verifier.Put(subSectionMemStart, subSectionSize); file.Skip(subSectionSize); currentFilePos = subSectionFileStart + subSectionSize; subSectionStart = nextSubSectionStart; } while (nextSubSectionStart != 0); } phs++; } #endif file.TransferAllTo(verifier); #ifdef CRYPTOPP_WIN32_AVAILABLE // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // hash from disk instead if (memcmp(expectedModuleMac, actualMac, macSize) != 0) { OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); file.Initialize(MakeParameters("InputFileName", moduleFilename)); verifier.Detach(new ArraySink(actualMac, actualMac.size())); if (macFileLocation) { file.TransferTo(verifier, macFileLocation); file.Skip(macSize); } file.TransferAllTo(verifier); } #endif if (memcmp(expectedModuleMac, actualMac, macSize) == 0) return true; #ifdef CRYPTOPP_WIN32_AVAILABLE std::string hexMac; HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); OutputDebugString((moduleFilename + (" integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); #endif return false; }
void BenchmarkAll(double t, double hertz) { #if 1 logtotal = 0; logcount = 0; g_allocatedTime = t; g_hertz = hertz; const char *cpb, *cpk; if (g_hertz) { cpb = "<TH>Cycles Per Byte"; cpk = "<TH>Cycles to<br>Setup Key and IV"; cout << "CPU frequency of the test platform is " << g_hertz << " Hz.\n"; } else { cpb = cpk = ""; cout << "CPU frequency of the test platform was not provided.\n"; } cout << "<TABLE border=1><COLGROUP><COL align=left><COL align=right><COL align=right><COL align=right><COL align=right>" << endl; cout << "<THEAD><TR><TH>Algorithm<TH>MiB/Second" << cpb << "<TH>Microseconds to<br>Setup Key and IV" << cpk << endl; cout << "\n<TBODY style=\"background: yellow\">"; #if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE if (HasCLMUL()) BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM"); else #endif { BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM (2K tables)", MakeParameters(Name::TableSize(), 2048)); BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/GCM", 0, "AES/GCM (64K tables)", MakeParameters(Name::TableSize(), 64*1024)); } BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/CCM"); BenchMarkByName2<AuthenticatedSymmetricCipher, AuthenticatedSymmetricCipher>("AES/EAX"); cout << "\n<TBODY style=\"background: white\">"; #if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE if (HasCLMUL()) BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES)"); else #endif { BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES) (2K tables)", MakeParameters(Name::TableSize(), 2048)); BenchMarkByName2<AuthenticatedSymmetricCipher, MessageAuthenticationCode>("AES/GCM", 0, "GMAC(AES) (64K tables)", MakeParameters(Name::TableSize(), 64*1024)); } BenchMarkByName<MessageAuthenticationCode>("VMAC(AES)-64"); BenchMarkByName<MessageAuthenticationCode>("VMAC(AES)-128"); BenchMarkByName<MessageAuthenticationCode>("HMAC(SHA-1)"); BenchMarkByName<MessageAuthenticationCode>("Two-Track-MAC"); BenchMarkByName<MessageAuthenticationCode>("CMAC(AES)"); BenchMarkByName<MessageAuthenticationCode>("DMAC(AES)"); cout << "\n<TBODY style=\"background: yellow\">"; BenchMarkByNameKeyLess<HashTransformation>("CRC32"); BenchMarkByNameKeyLess<HashTransformation>("Adler32"); BenchMarkByNameKeyLess<HashTransformation>("MD5"); BenchMarkByNameKeyLess<HashTransformation>("SHA-1"); BenchMarkByNameKeyLess<HashTransformation>("SHA-256"); BenchMarkByNameKeyLess<HashTransformation>("SHA-512"); BenchMarkByNameKeyLess<HashTransformation>("SHA-3-224"); BenchMarkByNameKeyLess<HashTransformation>("SHA-3-256"); BenchMarkByNameKeyLess<HashTransformation>("SHA-3-384"); BenchMarkByNameKeyLess<HashTransformation>("SHA-3-512"); BenchMarkByNameKeyLess<HashTransformation>("Tiger"); BenchMarkByNameKeyLess<HashTransformation>("Whirlpool"); BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-160"); BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-320"); BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-128"); BenchMarkByNameKeyLess<HashTransformation>("RIPEMD-256"); cout << "\n<TBODY style=\"background: white\">"; BenchMarkByName<SymmetricCipher>("Panama-LE"); BenchMarkByName<SymmetricCipher>("Panama-BE"); BenchMarkByName<SymmetricCipher>("Salsa20"); BenchMarkByName<SymmetricCipher>("Salsa20", 0, "Salsa20/12", MakeParameters(Name::Rounds(), 12)); BenchMarkByName<SymmetricCipher>("Salsa20", 0, "Salsa20/8", MakeParameters(Name::Rounds(), 8)); BenchMarkByName<SymmetricCipher>("Sosemanuk"); BenchMarkByName<SymmetricCipher>("MARC4"); BenchMarkByName<SymmetricCipher>("SEAL-3.0-LE"); BenchMarkByName<SymmetricCipher>("WAKE-OFB-LE"); cout << "\n<TBODY style=\"background: yellow\">"; BenchMarkByName<SymmetricCipher>("AES/CTR", 16); BenchMarkByName<SymmetricCipher>("AES/CTR", 24); BenchMarkByName<SymmetricCipher>("AES/CTR", 32); BenchMarkByName<SymmetricCipher>("AES/CBC", 16); BenchMarkByName<SymmetricCipher>("AES/CBC", 24); BenchMarkByName<SymmetricCipher>("AES/CBC", 32); BenchMarkByName<SymmetricCipher>("AES/OFB", 16); BenchMarkByName<SymmetricCipher>("AES/CFB", 16); BenchMarkByName<SymmetricCipher>("AES/ECB", 16); BenchMarkByName<SymmetricCipher>("Camellia/CTR", 16); BenchMarkByName<SymmetricCipher>("Camellia/CTR", 32); BenchMarkByName<SymmetricCipher>("Twofish/CTR"); BenchMarkByName<SymmetricCipher>("Serpent/CTR"); BenchMarkByName<SymmetricCipher>("CAST-256/CTR"); BenchMarkByName<SymmetricCipher>("RC6/CTR"); BenchMarkByName<SymmetricCipher>("MARS/CTR"); BenchMarkByName<SymmetricCipher>("SHACAL-2/CTR", 16); BenchMarkByName<SymmetricCipher>("SHACAL-2/CTR", 64); BenchMarkByName<SymmetricCipher>("DES/CTR"); BenchMarkByName<SymmetricCipher>("DES-XEX3/CTR"); BenchMarkByName<SymmetricCipher>("DES-EDE3/CTR"); BenchMarkByName<SymmetricCipher>("IDEA/CTR"); BenchMarkByName<SymmetricCipher>("RC5/CTR", 0, "RC5 (r=16)"); BenchMarkByName<SymmetricCipher>("Blowfish/CTR"); BenchMarkByName<SymmetricCipher>("TEA/CTR"); BenchMarkByName<SymmetricCipher>("XTEA/CTR"); BenchMarkByName<SymmetricCipher>("CAST-128/CTR"); BenchMarkByName<SymmetricCipher>("SKIPJACK/CTR"); BenchMarkByName<SymmetricCipher>("SEED/CTR", 0, "SEED/CTR (1/2 K table)"); cout << "</TABLE>" << endl; BenchmarkAll2(t, hertz); cout << "Throughput Geometric Average: " << setiosflags(ios::fixed) << exp(logtotal/(logcount ? logcount : 1)) << endl; // Safer functions on Windows for C&A, https://github.com/weidai11/cryptopp/issues/55 #if (CRYPTOPP_MSC_VERSION >= 1400) tm localTime = {}; char timeBuf[64]; errno_t err; const time_t endTime = time(NULL); err = localtime_s(&localTime, &endTime); assert(err == 0); err = asctime_s(timeBuf, sizeof(timeBuf), &localTime); assert(err == 0); cout << "\nTest ended at " << timeBuf; #else const time_t endTime = time(NULL); cout << "\nTest ended at " << asctime(localtime(&endTime)); #endif #endif }
SignatureVerificationFilter::SignatureVerificationFilter(const PK_Verifier &verifier, BufferedTransformation *attachment, word32 flags) : FilterWithBufferedInput(attachment) , m_verifier(verifier), m_flags(0), m_verified(0) { IsolatedInitialize(MakeParameters(Name::SignatureVerificationFilterFlags(), flags)); }
void InvertibleLUCFunction::Initialize(RandomNumberGenerator &rng, unsigned int keybits, const Integer &e) { GenerateRandom(rng, MakeParameters("ModulusSize", (int)keybits)("PublicExponent", e)); }
void SimpleKeyingInterface::SetKeyWithRounds(const byte *key, unsigned int length, int rounds) { SetKey(key, length, MakeParameters(Name::Rounds(), rounds)); }
HashVerificationFilter::HashVerificationFilter(HashTransformation &hm, BufferedTransformation *attachment, word32 flags) : FilterWithBufferedInput(attachment) , m_hashModule(hm) { IsolatedInitialize(MakeParameters(Name::HashVerificationFilterFlags(), flags)); }
void SimpleKeyingInterface::SetKeyWithIV(const byte *key, unsigned int length, const byte *iv) { SetKey(key, length, MakeParameters(Name::IV(), iv)); }
bool IntegrityCheckModule(const char *moduleFilename, const byte *expectedModuleMac, SecByteBlock *pActualMac, unsigned long *pMacFileLocation) { std::auto_ptr<MessageAuthenticationCode> mac(NewIntegrityCheckingMAC()); unsigned int macSize = mac->DigestSize(); SecByteBlock tempMac; SecByteBlock &actualMac = pActualMac ? *pActualMac : tempMac; actualMac.resize(macSize); unsigned long tempLocation; unsigned long &macFileLocation = pMacFileLocation ? *pMacFileLocation : tempLocation; macFileLocation = 0; MeterFilter verifier(new HashFilter(*mac, new ArraySink(actualMac, actualMac.size()))); // MeterFilter verifier(new FileSink("c:\\dt.tmp")); std::ifstream moduleStream; #ifdef CRYPTOPP_WIN32_AVAILABLE HMODULE h; { char moduleFilenameBuf[MAX_PATH] = ""; if (moduleFilename == NULL) { #if (_MSC_VER >= 1400 && !defined(_STLPORT_VERSION)) // ifstream doesn't support wide filename on other compilers wchar_t wideModuleFilename[MAX_PATH]; if (GetModuleFileNameW(s_hModule, wideModuleFilename, MAX_PATH) > 0) { moduleStream.open(wideModuleFilename, std::ios::in | std::ios::binary); h = GetModuleHandleW(wideModuleFilename); } else #endif { GetModuleFileNameA(s_hModule, moduleFilenameBuf, MAX_PATH); moduleFilename = moduleFilenameBuf; } } #endif if (moduleFilename != NULL) { moduleStream.open(moduleFilename, std::ios::in | std::ios::binary); #ifdef CRYPTOPP_WIN32_AVAILABLE h = GetModuleHandleA(moduleFilename); moduleFilename = NULL; } #endif } if (!moduleStream) { #ifdef CRYPTOPP_WIN32_AVAILABLE OutputDebugString(L"Crypto++ DLL integrity check failed. Cannot open file for reading."); //OutputDebugString("Crypto++ DLL integrity check failed. Cannot open file for reading."); #endif return false; } FileStore file(moduleStream); #ifdef CRYPTOPP_WIN32_AVAILABLE // try to hash from memory first const byte *memBase = (const byte *)h; const IMAGE_DOS_HEADER *ph = (IMAGE_DOS_HEADER *)memBase; const IMAGE_NT_HEADERS *phnt = (IMAGE_NT_HEADERS *)(memBase + ph->e_lfanew); const IMAGE_SECTION_HEADER *phs = IMAGE_FIRST_SECTION(phnt); DWORD nSections = phnt->FileHeader.NumberOfSections; size_t currentFilePos = 0; size_t checksumPos = (byte *)&phnt->OptionalHeader.CheckSum - memBase; size_t checksumSize = sizeof(phnt->OptionalHeader.CheckSum); size_t certificateTableDirectoryPos = (byte *)&phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY] - memBase; size_t certificateTableDirectorySize = sizeof(phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]); size_t certificateTablePos = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].VirtualAddress; size_t certificateTableSize = phnt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY].Size; verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); while (nSections--) { switch (phs->Characteristics) { default: break; case IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ: case IMAGE_SCN_CNT_INITIALIZED_DATA | IMAGE_SCN_MEM_READ: unsigned int sectionSize = STDMIN(phs->SizeOfRawData, phs->Misc.VirtualSize); const byte *sectionMemStart = memBase + phs->VirtualAddress; unsigned int sectionFileStart = phs->PointerToRawData; size_t subSectionStart = 0, nextSubSectionStart; do { const byte *subSectionMemStart = sectionMemStart + subSectionStart; size_t subSectionFileStart = sectionFileStart + subSectionStart; size_t subSectionSize = sectionSize - subSectionStart; nextSubSectionStart = 0; unsigned int entriesToReadFromDisk[] = {IMAGE_DIRECTORY_ENTRY_IMPORT, IMAGE_DIRECTORY_ENTRY_IAT}; for (unsigned int i=0; i<sizeof(entriesToReadFromDisk)/sizeof(entriesToReadFromDisk[0]); i++) { const IMAGE_DATA_DIRECTORY &entry = phnt->OptionalHeader.DataDirectory[entriesToReadFromDisk[i]]; const byte *entryMemStart = memBase + entry.VirtualAddress; if (subSectionMemStart <= entryMemStart && entryMemStart < subSectionMemStart + subSectionSize) { subSectionSize = entryMemStart - subSectionMemStart; nextSubSectionStart = entryMemStart - sectionMemStart + entry.Size; } } #if defined(_MSC_VER) && _MSC_VER >= 1400 // first byte of _CRT_DEBUGGER_HOOK gets modified in memory by the debugger invisibly, so read it from file if (IsDebuggerPresent()) { if (subSectionMemStart <= (byte *)&_CRT_DEBUGGER_HOOK && (byte *)&_CRT_DEBUGGER_HOOK < subSectionMemStart + subSectionSize) { subSectionSize = (byte *)&_CRT_DEBUGGER_HOOK - subSectionMemStart; nextSubSectionStart = (byte *)&_CRT_DEBUGGER_HOOK - sectionMemStart + 1; } } #endif if (subSectionMemStart <= expectedModuleMac && expectedModuleMac < subSectionMemStart + subSectionSize) { // found stored MAC macFileLocation = (unsigned long)(subSectionFileStart + (expectedModuleMac - subSectionMemStart)); verifier.AddRangeToSkip(0, macFileLocation, macSize); } file.TransferTo(verifier, subSectionFileStart - currentFilePos); verifier.Put(subSectionMemStart, subSectionSize); file.Skip(subSectionSize); currentFilePos = subSectionFileStart + subSectionSize; subSectionStart = nextSubSectionStart; } while (nextSubSectionStart != 0); } phs++; } #endif file.TransferAllTo(verifier); #ifdef CRYPTOPP_WIN32_AVAILABLE // if that fails (could be caused by debug breakpoints or DLL base relocation modifying image in memory), // hash from disk instead if (!VerifyBufsEqual(expectedModuleMac, actualMac, macSize)) { OutputDebugString(L"In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); //OutputDebugString("In memory integrity check failed. This may be caused by debug breakpoints or DLL relocation.\n"); moduleStream.clear(); moduleStream.seekg(0); verifier.Initialize(MakeParameters(Name::OutputBuffer(), ByteArrayParameter(actualMac, (unsigned int)actualMac.size()))); // verifier.Initialize(MakeParameters(Name::OutputFileName(), (const char *)"c:\\dt2.tmp")); verifier.AddRangeToSkip(0, checksumPos, checksumSize); verifier.AddRangeToSkip(0, certificateTableDirectoryPos, certificateTableDirectorySize); verifier.AddRangeToSkip(0, certificateTablePos, certificateTableSize); verifier.AddRangeToSkip(0, macFileLocation, macSize); FileStore(moduleStream).TransferAllTo(verifier); } #endif if (VerifyBufsEqual(expectedModuleMac, actualMac, macSize)) return true; #ifdef CRYPTOPP_WIN32_AVAILABLE // std::string hexMac; // HexEncoder(new StringSink(hexMac)).PutMessageEnd(actualMac, actualMac.size()); // OutputDebugString((("Crypto++ DLL integrity check failed. Actual MAC is: " + hexMac) + "\n").c_str()); #endif return false; }
void InvertibleRSAFunction::Initialize(RandomNumberGenerator &rng, unsigned int keybits, const Integer &e) { GenerateRandom(rng, MakeParameters(Name::ModulusSize(), (int)keybits)(Name::PublicExponent(), e+e.IsEven())); }
void SecretRecovery::IsolatedInitialize(const NameValuePairs ¶meters) { m_pad = parameters.GetValueWithDefault("RemovePadding", true); RawIDA::IsolatedInitialize(CombinedNameValuePairs(parameters, MakeParameters("OutputChannelID", (word32)0xffffffff))); }
void HexDecoder::IsolatedInitialize(const NameValuePairs ¶meters) { BaseN_Decoder::Initialize(CombinedNameValuePairs( parameters, MakeParameters(Name::DecodingLookupArray(), GetDefaultDecodingLookupArray(), false)(Name::Log2Base(), 4, true))); }
void BenchMarkKeyed(const char *name, double timeTotal, T *x=NULL) { T c; c.SetKey(key, c.DefaultKeyLength(), MakeParameters(Name::IV(), key, false)); BenchMark(name, c, timeTotal); }