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 SignatureVerificationFilter::InitializeDerivedAndReturnNewSizes(const NameValuePairs ¶meters, unsigned int &firstSize, unsigned int &blockSize, unsigned int &lastSize) { m_flags = parameters.GetValueWithDefault(Name::SignatureVerificationFilterFlags(), (word32)DEFAULT_FLAGS); m_messageAccumulator.reset(m_verifier.NewVerificationAccumulator()); unsigned int size = m_verifier.SignatureLength(); assert(size != 0); // TODO: handle recoverable signature scheme m_verified = false; firstSize = m_flags & SIGNATURE_AT_BEGIN ? size : 0; blockSize = 1; lastSize = m_flags & SIGNATURE_AT_BEGIN ? 0 : size; }
void FileStore::StoreInitialize(const NameValuePairs ¶meters) { m_waiting = false; m_stream = NULL; m_file.release(); const char *fileName = NULL; #if defined(CRYPTOPP_UNIX_AVAILABLE) || _MSC_VER >= 1400 const wchar_t *fileNameWide = NULL; if (!parameters.GetValue(Name::InputFileNameWide(), fileNameWide)) #endif if (!parameters.GetValue(Name::InputFileName(), fileName)) { parameters.GetValue(Name::InputStreamPointer(), m_stream); return; } std::ios::openmode binary = parameters.GetValueWithDefault(Name::InputBinaryMode(), true) ? std::ios::binary : std::ios::openmode(0); m_file.reset(new std::ifstream); #ifdef CRYPTOPP_UNIX_AVAILABLE std::string narrowed; if (fileNameWide) fileName = (narrowed = StringNarrow(fileNameWide)).c_str(); #endif #if _MSC_VER >= 1400 if (fileNameWide) { m_file->open(fileNameWide, std::ios::in | binary); if (!*m_file) throw OpenErr(StringNarrow(fileNameWide, false)); } #endif if (fileName) { m_file->open(fileName, std::ios::in | binary); if (!*m_file) throw OpenErr(fileName); } m_stream = m_file.get(); }
// generate a random private key void InvertibleRabinFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg) { int modulusSize = 2048; alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize); if (modulusSize < 16) throw InvalidArgument("InvertibleRabinFunction: specified modulus size is too small"); // VC70 workaround: putting these after primeParam causes overlapped stack allocation bool rFound=false, sFound=false; Integer t=2; const NameValuePairs &primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize) ("EquivalentTo", 3)("Mod", 4); m_p.GenerateRandom(rng, primeParam); m_q.GenerateRandom(rng, primeParam); while (!(rFound && sFound)) { int jp = Jacobi(t, m_p); int jq = Jacobi(t, m_q); if (!rFound && jp==1 && jq==-1) { m_r = t; rFound = true; } if (!sFound && jp==-1 && jq==1) { m_s = t; sFound = true; } ++t; } m_n = m_p * m_q; m_u = m_q.InverseMod(m_p); }
void InvertibleRSAFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg) { int modulusSize = 2048; alg.GetIntValue(Name::ModulusSize(), modulusSize) || alg.GetIntValue(Name::KeySize(), modulusSize); assert(modulusSize >= 16); if (modulusSize < 16) throw InvalidArgument("InvertibleRSAFunction: specified modulus size is too small"); m_e = alg.GetValueWithDefault(Name::PublicExponent(), Integer(17)); assert(m_e >= 3); assert(!m_e.IsEven()); if (m_e < 3 || m_e.IsEven()) throw InvalidArgument("InvertibleRSAFunction: invalid public exponent"); RSAPrimeSelector selector(m_e); AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize) (Name::PointerToPrimeSelector(), selector.GetSelectorPointer()); m_p.GenerateRandom(rng, primeParam); m_q.GenerateRandom(rng, primeParam); m_d = m_e.InverseMod(LCM(m_p-1, m_q-1)); assert(m_d.IsPositive()); m_dp = m_d % (m_p-1); m_dq = m_d % (m_q-1); m_n = m_p * m_q; m_u = m_q.InverseMod(m_p); if (FIPS_140_2_ComplianceEnabled()) { RSASS<PKCS1v15, SHA>::Signer signer(*this); RSASS<PKCS1v15, SHA>::Verifier verifier(signer); SignaturePairwiseConsistencyTest_FIPS_140_Only(signer, verifier); RSAES<OAEP<SHA> >::Decryptor decryptor(*this); RSAES<OAEP<SHA> >::Encryptor encryptor(decryptor); EncryptionPairwiseConsistencyTest_FIPS_140_Only(encryptor, decryptor); } }
DecodingResult OAEP_Base::Unpad(const byte *oaepBlock, size_t oaepBlockLen, byte *output, const NameValuePairs ¶meters) const { bool invalid = false; #if defined(CRYPTOPP_CXX11) std::unique_ptr<HashTransformation> pHash(NewHash()); #else std::auto_ptr<HashTransformation> pHash(NewHash()); #endif // convert from bit length to byte length if (oaepBlockLen % 8 != 0) { invalid = (oaepBlock[0] != 0) || invalid; oaepBlock++; } oaepBlockLen /= 8; const size_t hLen = pHash->DigestSize(); const size_t seedLen = hLen, dbLen = oaepBlockLen-seedLen; invalid = (oaepBlockLen < 2*hLen+1) || invalid; SecByteBlock t(oaepBlock, oaepBlockLen); byte *const maskedSeed = t; byte *const maskedDB = t+seedLen; #if defined(CRYPTOPP_CXX11) std::unique_ptr<MaskGeneratingFunction> pMGF(NewMGF()); #else std::auto_ptr<MaskGeneratingFunction> pMGF(NewMGF()); #endif pMGF->GenerateAndMask(*pHash, maskedSeed, seedLen, maskedDB, dbLen); pMGF->GenerateAndMask(*pHash, maskedDB, dbLen, maskedSeed, seedLen); ConstByteArrayParameter encodingParameters; parameters.GetValue(Name::EncodingParameters(), encodingParameters); // DB = pHash' || 00 ... || 01 || M byte *M = std::find(maskedDB+hLen, maskedDB+dbLen, 0x01); invalid = (M == maskedDB+dbLen) || invalid; invalid = (std::find_if(maskedDB+hLen, M, std::bind2nd(std::not_equal_to<byte>(), byte(0))) != M) || invalid; invalid = !pHash->VerifyDigest(maskedDB, encodingParameters.begin(), encodingParameters.size()) || invalid; if (invalid) return DecodingResult(); M++; memcpy(output, M, maskedDB+dbLen-M); return DecodingResult(maskedDB+dbLen-M); }
void InvertibleLUCFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg) { int modulusSize = 2048; alg.GetIntValue("ModulusSize", modulusSize) || alg.GetIntValue("KeySize", modulusSize); if (modulusSize < 16) throw InvalidArgument("InvertibleLUCFunction: specified modulus size is too small"); m_e = alg.GetValueWithDefault("PublicExponent", Integer(17)); if (m_e < 5 || m_e.IsEven()) throw InvalidArgument("InvertibleLUCFunction: invalid public exponent"); LUCPrimeSelector selector(m_e); AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize) ("PointerToPrimeSelector", selector.GetSelectorPointer()); m_p.GenerateRandom(rng, primeParam); m_q.GenerateRandom(rng, primeParam); m_n = m_p * m_q; m_u = m_q.InverseMod(m_p); }
void RageFileStore::StoreInitialize(const NameValuePairs ¶meters) { const char *fileName; if (parameters.GetValue("InputFileName", fileName)) { if( !m_file.Open(fileName, RageFile::READ) ) throw OpenErr(fileName); } else { ASSERT(0); } m_waiting = false; }
void CCM_Base::SetKeyWithoutResync(const byte *userKey, size_t keylength, const NameValuePairs ¶ms) { BlockCipher &blockCipher = AccessBlockCipher(); blockCipher.SetKey(userKey, keylength, params); if (blockCipher.BlockSize() != REQUIRED_BLOCKSIZE) throw InvalidArgument(AlgorithmName() + ": block size of underlying block cipher is not 16"); m_digestSize = params.GetIntValueWithDefault(Name::DigestSize(), DefaultDigestSize()); if (m_digestSize % 2 > 0 || m_digestSize < 4 || m_digestSize > 16) throw InvalidArgument(AlgorithmName() + ": DigestSize must be 4, 6, 8, 10, 12, 14, or 16"); m_buffer.Grow(2*REQUIRED_BLOCKSIZE); m_L = 8; }
void StreamTransformationFilter::InitializeDerivedAndReturnNewSizes(const NameValuePairs ¶meters, size_t &firstSize, size_t &blockSize, size_t &lastSize) { BlockPaddingScheme padding = parameters.GetValueWithDefault(Name::BlockPaddingScheme(), DEFAULT_PADDING); bool isBlockCipher = (m_cipher.MandatoryBlockSize() > 1 && m_cipher.MinLastBlockSize() == 0); if (padding == DEFAULT_PADDING) m_padding = isBlockCipher ? PKCS_PADDING : NO_PADDING; else m_padding = padding; if (!isBlockCipher && (m_padding == PKCS_PADDING || m_padding == ONE_AND_ZEROS_PADDING)) throw InvalidArgument("StreamTransformationFilter: PKCS_PADDING and ONE_AND_ZEROS_PADDING cannot be used with " + m_cipher.AlgorithmName()); firstSize = 0; blockSize = m_cipher.MandatoryBlockSize(); lastSize = LastBlockSize(m_cipher, m_padding); }
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))); }
void SAFER::Base::UncheckedSetKey(const byte *userkey_1, unsigned int length, const NameValuePairs ¶ms) { bool strengthened = Strengthened(); unsigned int nof_rounds = params.GetIntValueWithDefault(Name::Rounds(), length == 8 ? (strengthened ? 8 : 6) : 10); const byte *userkey_2 = length == 8 ? userkey_1 : userkey_1 + 8; keySchedule.New(1 + BLOCKSIZE * (1 + 2 * nof_rounds)); unsigned int i, j; byte *key = keySchedule; SecByteBlock ka(BLOCKSIZE + 1), kb(BLOCKSIZE + 1); if (MAX_ROUNDS < nof_rounds) nof_rounds = MAX_ROUNDS; *key++ = (unsigned char)nof_rounds; ka[BLOCKSIZE] = 0; kb[BLOCKSIZE] = 0; for (j = 0; j < BLOCKSIZE; j++) { ka[BLOCKSIZE] ^= ka[j] = rotlFixed(userkey_1[j], 5U); kb[BLOCKSIZE] ^= kb[j] = *key++ = userkey_2[j]; } for (i = 1; i <= nof_rounds; i++) { for (j = 0; j < BLOCKSIZE + 1; j++) { ka[j] = rotlFixed(ka[j], 6U); kb[j] = rotlFixed(kb[j], 6U); } for (j = 0; j < BLOCKSIZE; j++) if (strengthened) *key++ = (ka[(j + 2 * i - 1) % (BLOCKSIZE + 1)] + exp_tab[exp_tab[18 * i + j + 1]]) & 0xFF; else *key++ = (ka[j] + exp_tab[exp_tab[18 * i + j + 1]]) & 0xFF; for (j = 0; j < BLOCKSIZE; j++) if (strengthened) *key++ = (kb[(j + 2 * i) % (BLOCKSIZE + 1)] + exp_tab[exp_tab[18 * i + j + 10]]) & 0xFF; else *key++ = (kb[j] + exp_tab[exp_tab[18 * i + j + 10]]) & 0xFF; } }
void RC2::Base::UncheckedSetKey(const byte *key, unsigned int keyLen, const NameValuePairs ¶ms) { AssertValidKeyLength(keyLen); int effectiveLen = params.GetIntValueWithDefault(Name::EffectiveKeyLength(), DEFAULT_EFFECTIVE_KEYLENGTH); if (effectiveLen > MAX_EFFECTIVE_KEYLENGTH) throw InvalidArgument("RC2: effective key length parameter exceeds maximum"); static const unsigned char PITABLE[256] = { 217,120,249,196, 25,221,181,237, 40,233,253,121, 74,160,216,157, 198,126, 55,131, 43,118, 83,142, 98, 76,100,136, 68,139,251,162, 23,154, 89,245,135,179, 79, 19, 97, 69,109,141, 9,129,125, 50, 189,143, 64,235,134,183,123, 11,240,149, 33, 34, 92,107, 78,130, 84,214,101,147,206, 96,178, 28,115, 86,192, 20,167,140,241,220, 18,117,202, 31, 59,190,228,209, 66, 61,212, 48,163, 60,182, 38, 111,191, 14,218, 70,105, 7, 87, 39,242, 29,155,188,148, 67, 3, 248, 17,199,246,144,239, 62,231, 6,195,213, 47,200,102, 30,215, 8,232,234,222,128, 82,238,247,132,170,114,172, 53, 77,106, 42, 150, 26,210,113, 90, 21, 73,116, 75,159,208, 94, 4, 24,164,236, 194,224, 65,110, 15, 81,203,204, 36,145,175, 80,161,244,112, 57, 153,124, 58,133, 35,184,180,122,252, 2, 54, 91, 37, 85,151, 49, 45, 93,250,152,227,138,146,174, 5,223, 41, 16,103,108,186,201, 211, 0,230,207,225,158,168, 44, 99, 22, 1, 63, 88,226,137,169, 13, 56, 52, 27,171, 51,255,176,187, 72, 12, 95,185,177,205, 46, 197,243,219, 71,229,165,156,119, 10,166, 32,104,254,127,193,173}; SecByteBlock L(128); memcpy(L, key, keyLen); int i; for (i=keyLen; i<128; i++) L[i] = PITABLE[(L[i-1] + L[i-keyLen]) & 255]; unsigned int T8 = (effectiveLen+7) / 8; byte TM = byte((int)255 >> ((8-(effectiveLen%8))%8)); L[128-T8] = PITABLE[L[128-T8] & TM]; for (i=127-T8; i>=0; i--) L[i] = PITABLE[L[i+1] ^ L[i+T8]]; for (i=0; i<64; i++) K[i] = L[2*i] + (L[2*i+1] << 8); }
void OAEP_Base::Pad(RandomNumberGenerator &rng, const byte *input, size_t inputLength, byte *oaepBlock, size_t oaepBlockLen, const NameValuePairs ¶meters) const { CRYPTOPP_ASSERT (inputLength <= MaxUnpaddedLength(oaepBlockLen)); #if defined(CRYPTOPP_CXX11) std::unique_ptr<HashTransformation> pHash(NewHash()); #else std::auto_ptr<HashTransformation> pHash(NewHash()); #endif // convert from bit length to byte length if (oaepBlockLen % 8 != 0) { oaepBlock[0] = 0; oaepBlock++; } oaepBlockLen /= 8; const size_t hLen = pHash->DigestSize(); const size_t seedLen = hLen, dbLen = oaepBlockLen-seedLen; byte *const maskedSeed = oaepBlock; byte *const maskedDB = oaepBlock+seedLen; ConstByteArrayParameter encodingParameters; parameters.GetValue(Name::EncodingParameters(), encodingParameters); // DB = pHash || 00 ... || 01 || M pHash->CalculateDigest(maskedDB, encodingParameters.begin(), encodingParameters.size()); memset(maskedDB+hLen, 0, dbLen-hLen-inputLength-1); maskedDB[dbLen-inputLength-1] = 0x01; memcpy(maskedDB+dbLen-inputLength, input, inputLength); #if defined(CRYPTOPP_CXX11) std::unique_ptr<MaskGeneratingFunction> pMGF(NewMGF()); #else std::auto_ptr<MaskGeneratingFunction> pMGF(NewMGF()); #endif rng.GenerateBlock(maskedSeed, seedLen); pMGF->GenerateAndMask(*pHash, maskedDB, dbLen, maskedSeed, seedLen); pMGF->GenerateAndMask(*pHash, maskedSeed, seedLen, maskedDB, dbLen); }
void OutputNameValuePairs(const NameValuePairs &v) { std::string names = v.GetValueNames(); string::size_type i = 0; while (i < names.size()) { string::size_type j = names.find_first_of (';', i); if (j == string::npos) return; else { std::string name = names.substr(i, j-i); if (name.find(':') == string::npos) OutputPair(v, name.c_str()); } i = j + 1; } }
void SEAL_Policy<B>::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length) { m_insideCounter = m_outsideCounter = m_startCount = 0; unsigned int L = params.GetIntValueWithDefault("NumberOfOutputBitsPerPositionIndex", 32*1024); m_iterationsPerCount = L / 8192; SEAL_Gamma gamma(key); unsigned int i; for (i=0; i<512; i++) m_T[i] = gamma.Apply(i); for (i=0; i<256; i++) m_S[i] = gamma.Apply(0x1000+i); m_R.New(4*(L/8192)); for (i=0; i<m_R.size(); i++) m_R[i] = gamma.Apply(0x2000+i); }
void ChaCha_Policy::CipherSetKey(const NameValuePairs ¶ms, const byte *key, size_t length) { CRYPTOPP_UNUSED(params); CRYPTOPP_ASSERT(length == 16 || length == 32); m_rounds = params.GetIntValueWithDefault(Name::Rounds(), 20); if (!(m_rounds == 8 || m_rounds == 12 || m_rounds == 20)) throw InvalidRounds(ChaCha::StaticAlgorithmName(), m_rounds); // "expand 16-byte k" or "expand 32-byte k" m_state[0] = 0x61707865; m_state[1] = (length == 16) ? 0x3120646e : 0x3320646e; m_state[2] = (length == 16) ? 0x79622d36 : 0x79622d32; m_state[3] = 0x6b206574; GetBlock<word32, LittleEndian> get1(key); get1(m_state[4])(m_state[5])(m_state[6])(m_state[7]); GetBlock<word32, LittleEndian> get2(key + ((length == 32) ? 16 : 0)); get2(m_state[8])(m_state[9])(m_state[10])(m_state[11]); }
void InformationRecovery::IsolatedInitialize(const NameValuePairs ¶meters) { m_pad = parameters.GetValueWithDefault("RemovePadding", true); RawIDA::IsolatedInitialize(parameters); }
void HashFilter::IsolatedInitialize(const NameValuePairs ¶meters) { m_putMessage = parameters.GetValueWithDefault(Name::PutMessage(), false); m_hashModule.Restart(); }
void RandomNumberStore::StoreInitialize(const NameValuePairs ¶meters) { parameters.GetRequiredParameter("RandomNumberStore", "RandomNumberGeneratorPointer", m_rng); parameters.GetRequiredIntParameter("RandomNumberStore", "RandomNumberStoreSize", m_length); }
void ByteQueue::IsolatedInitialize(const NameValuePairs ¶meters) { m_nodeSize = parameters.GetIntValueWithDefault("NodeSize", 256); Clear(); }
void SignerFilter::IsolatedInitialize(const NameValuePairs ¶meters) { m_putMessage = parameters.GetValueWithDefault(Name::PutMessage(), false); m_messageAccumulator.reset(m_signer.NewSignatureAccumulator(m_rng)); }
void HashFilter::IsolatedInitialize(const NameValuePairs ¶meters) { m_putMessage = parameters.GetValueWithDefault(Name::PutMessage(), false); int s = parameters.GetIntValueWithDefault(Name::TruncatedDigestSize(), -1); m_digestSize = s < 0 ? m_hashModule.DigestSize() : s; }
void RubyIOSink::IsolatedInitialize(const NameValuePairs& parameters) { m_stream = NULL; parameters.GetValue(Name::OutputStreamPointer(), m_stream); }
void RandomNumberSink::IsolatedInitialize(const NameValuePairs ¶meters) { parameters.GetRequiredParameter("RandomNumberSink", "RandomNumberGeneratorPointer", m_rng); }
void RubyIOStore::StoreInitialize(const NameValuePairs& parameters) { m_stream = NULL; parameters.GetValue(Name::InputStreamPointer(), m_stream); m_waiting = false; }
void SecretSharing::IsolatedInitialize(const NameValuePairs ¶meters) { m_pad = parameters.GetValueWithDefault("AddPadding", true); m_ida.IsolatedInitialize(parameters); }
void SecretRecovery::IsolatedInitialize(const NameValuePairs ¶meters) { m_pad = parameters.GetValueWithDefault("RemovePadding", true); RawIDA::IsolatedInitialize(CombinedNameValuePairs(parameters, MakeParameters("OutputChannelID", (word32)0xffffffff))); }
void InformationDispersal::IsolatedInitialize(const NameValuePairs ¶meters) { m_nextChannel = 0; m_pad = parameters.GetValueWithDefault("AddPadding", true); m_ida.IsolatedInitialize(parameters); }