Пример #1
0
void RawIDA::IsolatedInitialize(const NameValuePairs &parameters)
{
	if (!parameters.GetIntValue("RecoveryThreshold", m_threshold))
		throw InvalidArgument("RawIDA: missing RecoveryThreshold argument");

	CRYPTOPP_ASSERT(m_threshold > 0);
	if (m_threshold <= 0)
		throw InvalidArgument("RawIDA: RecoveryThreshold must be greater than 0");

	m_lastMapPosition = m_inputChannelMap.end();
	m_channelsReady = 0;
	m_channelsFinished = 0;
	m_w.New(m_threshold);
	m_y.New(m_threshold);
	m_inputQueues.reserve(m_threshold);

	m_outputChannelIds.clear();
	m_outputChannelIdStrings.clear();
	m_outputQueues.clear();

	word32 outputChannelID;
	if (parameters.GetValue("OutputChannelID", outputChannelID))
		AddOutputChannel(outputChannelID);
	else
	{
		int nShares = parameters.GetIntValueWithDefault("NumberOfShares", m_threshold);
		CRYPTOPP_ASSERT(nShares > 0);
		if (nShares <= 0) {nShares = m_threshold;}
		for (unsigned int i=0; i< (unsigned int)(nShares); i++)
			AddOutputChannel(i);
	}
}
Пример #2
0
inline SharkProcessAndXorBlock(const word64 *roundKeys, unsigned int rounds, const byte *inBlock, const byte *xorBlock, byte *outBlock)
{
	CRYPTOPP_ASSERT(IsAlignedOn(inBlock,GetAlignmentOf<word64>()));
	word64 tmp = *(word64 *)(void *)inBlock ^ roundKeys[0];

	ByteOrder order = GetNativeByteOrder();
	tmp = cbox[0][GetByte(order, tmp, 0)] ^ cbox[1][GetByte(order, tmp, 1)]
		^ cbox[2][GetByte(order, tmp, 2)] ^ cbox[3][GetByte(order, tmp, 3)]
		^ cbox[4][GetByte(order, tmp, 4)] ^ cbox[5][GetByte(order, tmp, 5)]
		^ cbox[6][GetByte(order, tmp, 6)] ^ cbox[7][GetByte(order, tmp, 7)]
		^ roundKeys[1];

	for(unsigned int i=2; i<rounds; i++)
	{
		tmp = cbox[0][GETBYTE(tmp, 7)] ^ cbox[1][GETBYTE(tmp, 6)]
			^ cbox[2][GETBYTE(tmp, 5)] ^ cbox[3][GETBYTE(tmp, 4)]
			^ cbox[4][GETBYTE(tmp, 3)] ^ cbox[5][GETBYTE(tmp, 2)]
			^ cbox[6][GETBYTE(tmp, 1)] ^ cbox[7][GETBYTE(tmp, 0)]
			^ roundKeys[i];
	}

	PutBlock<byte, BigEndian>(xorBlock, outBlock)
		(sbox[GETBYTE(tmp, 7)])
		(sbox[GETBYTE(tmp, 6)])
		(sbox[GETBYTE(tmp, 5)])
		(sbox[GETBYTE(tmp, 4)])
		(sbox[GETBYTE(tmp, 3)])
		(sbox[GETBYTE(tmp, 2)])
		(sbox[GETBYTE(tmp, 1)])
		(sbox[GETBYTE(tmp, 0)]);

	CRYPTOPP_ASSERT(IsAlignedOn(outBlock,GetAlignmentOf<word64>()));
	*(word64 *)(void *)outBlock ^= roundKeys[rounds];
}};
Пример #3
0
static int ALL_RSI_GenerateBlock(byte *output, size_t size, unsigned int safety)
{
	CRYPTOPP_ASSERT((output && size) || !(output || size));
#if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32
	word32 val;
#else
	word64 val;
#endif

	while (size >= sizeof(val))
	{
#if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32
		if (_rdseed32_step((word32*)output))
#else
		// Cast due to GCC, http://github.com/weidai11/cryptopp/issues/236
		if (_rdseed64_step(reinterpret_cast<unsigned long long*>(output)))
#endif
		{
			output += sizeof(val);
			size -= sizeof(val);
		}
		else
		{
			if (!safety--)
			{
				CRYPTOPP_ASSERT(0);
				return 0;
			}
		}
	}

	if (size)
	{
#if CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32
		if (_rdseed32_step(&val))
#else
		// Cast due to GCC, http://github.com/weidai11/cryptopp/issues/236
		if (_rdseed64_step(reinterpret_cast<unsigned long long*>(&val)))
#endif
		{
			memcpy(output, &val, size);
			size = 0;
		}
		else
		{
			if (!safety--)
			{
				CRYPTOPP_ASSERT(0);
				return 0;
			}
		}
	}

	SecureWipeBuffer(&val, 1);

	return int(size == 0);
}
Пример #4
0
static int GCC_RSA_GenerateBlock(byte *output, size_t size, unsigned int safety)
{
	CRYPTOPP_ASSERT((output && size) || !(output || size));
#if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32
	word64 val;
#else
	word32 val;
#endif
	char rc;
	while (size)
	{
		__asm__ volatile(
#if CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32
			".byte 0x48, 0x0f, 0xc7, 0xf8;\n"  // rdseed rax
#else
			".byte 0x0f, 0xc7, 0xf8;\n"        // rdseed eax
#endif
			"setc %1; "
			: "=a" (val), "=qm" (rc)
			:
			: "cc"
		);

		if (rc)
		{
			if (size >= sizeof(val))
			{
#if defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS) && (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X32)
				*((word64*)(void *)output) = val;
#elif defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS) && (CRYPTOPP_BOOL_X86)
				*((word32*)(void *)output) = val;
#else
				memcpy(output, &val, sizeof(val));
#endif
				output += sizeof(val);
				size -= sizeof(val);
			}
			else
			{
				memcpy(output, &val, size);
				size = 0;
			}
		}
		else
		{
			if (!safety--)
			{
				CRYPTOPP_ASSERT(0);
				return 0;
			}
		}
	}

	SecureWipeBuffer(&val, 1);

	return int(size == 0);
}
Пример #5
0
size_t NetworkSink::Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
{
	if (m_eofState == EOF_DONE)
	{
		if (length || messageEnd)
			throw Exception(Exception::OTHER_ERROR, "NetworkSink::Put2() being called after EOF had been sent");

		return 0;
	}

	if (m_eofState > EOF_NONE)
		goto EofSite;

	{
		if (m_skipBytes)
		{
			CRYPTOPP_ASSERT(length >= m_skipBytes);
			inString += m_skipBytes;
			length -= m_skipBytes;
		}

		m_buffer.Put(inString, length);

		if (!blocking || m_buffer.CurrentSize() > m_autoFlushBound)
			TimedFlush(0, 0);

		size_t targetSize = messageEnd ? 0 : m_maxBufferSize;
		if (blocking)
			TimedFlush(INFINITE_TIME, targetSize);

		if (m_buffer.CurrentSize() > targetSize)
		{
			CRYPTOPP_ASSERT(!blocking);
			m_wasBlocked = true;
			m_skipBytes += length;
			size_t blockedBytes = UnsignedMin(length, m_buffer.CurrentSize() - targetSize);
			return STDMAX<size_t>(blockedBytes, 1);
		}

		m_wasBlocked = false;
		m_skipBytes = 0;
	}

	if (messageEnd)
	{
		m_eofState = EOF_PENDING_SEND;

	EofSite:
		TimedFlush(blocking ? INFINITE_TIME : 0, 0);
		if (m_eofState != EOF_DONE)
			return 1;
	}

	return 0;
}
Пример #6
0
void CFB_CipherTemplate<BASE>::ProcessData(byte *outString, const byte *inString, size_t length)
{
	CRYPTOPP_ASSERT(length % this->MandatoryBlockSize() == 0);

	PolicyInterface &policy = this->AccessPolicy();
	unsigned int bytesPerIteration = policy.GetBytesPerIteration();
	unsigned int alignment = policy.GetAlignment();
	byte *reg = policy.GetRegisterBegin();

	if (m_leftOver)
	{
		size_t len = STDMIN(m_leftOver, length);
		CombineMessageAndShiftRegister(outString, reg + bytesPerIteration - m_leftOver, inString, len);
		m_leftOver -= len;
		length -= len;
		inString += len;
		outString += len;
	}

	if (!length)
		return;

	CRYPTOPP_ASSERT(m_leftOver == 0);

	if (policy.CanIterate() && length >= bytesPerIteration && IsAlignedOn(outString, alignment))
	{
		if (IsAlignedOn(inString, alignment))
			policy.Iterate(outString, inString, GetCipherDir(*this), length / bytesPerIteration);
		else
		{
			memcpy(outString, inString, length);
			policy.Iterate(outString, outString, GetCipherDir(*this), length / bytesPerIteration);
		}
		inString += length - length % bytesPerIteration;
		outString += length - length % bytesPerIteration;
		length %= bytesPerIteration;
	}

	while (length >= bytesPerIteration)
	{
		policy.TransformRegister();
		CombineMessageAndShiftRegister(outString, reg, inString, bytesPerIteration);
		length -= bytesPerIteration;
		inString += bytesPerIteration;
		outString += bytesPerIteration;
	}

	if (length > 0)
	{
		policy.TransformRegister();
		CombineMessageAndShiftRegister(outString, reg, inString, length);
		m_leftOver = bytesPerIteration - length;
	}
}
Пример #7
0
bool RSAFunction::Validate(RandomNumberGenerator& rng, unsigned int level) const
{
	CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(level);

	bool pass = true;
	pass = pass && m_n > Integer::One() && m_n.IsOdd();
	CRYPTOPP_ASSERT(pass);
	pass = pass && m_e > Integer::One() && m_e.IsOdd() && m_e < m_n;
	CRYPTOPP_ASSERT(pass);
	return pass;
}
Пример #8
0
bool EC2N::DecodePoint(EC2N::Point &P, BufferedTransformation &bt, size_t encodedPointLen) const
{
	byte type;
	if (encodedPointLen < 1 || !bt.Get(type))
		return false;

	switch (type)
	{
	case 0:
		P.identity = true;
		return true;
	case 2:
	case 3:
	{
		if (encodedPointLen != EncodedPointSize(true))
			return false;

		P.identity = false;
		P.x.Decode(bt, m_field->MaxElementByteLength()); 

		if (P.x.IsZero())
		{
			P.y = m_field->SquareRoot(m_b);
			return true;
		}

		FieldElement z = m_field->Square(P.x);
		CRYPTOPP_ASSERT(P.x == m_field->SquareRoot(z));
		P.y = m_field->Divide(m_field->Add(m_field->Multiply(z, m_field->Add(P.x, m_a)), m_b), z);
		CRYPTOPP_ASSERT(P.x == m_field->Subtract(m_field->Divide(m_field->Subtract(m_field->Multiply(P.y, z), m_b), z), m_a));
		z = m_field->SolveQuadraticEquation(P.y);
		CRYPTOPP_ASSERT(m_field->Add(m_field->Square(z), z) == P.y);
		z.SetCoefficient(0, type & 1);

		P.y = m_field->Multiply(z, P.x);
		return true;
	}
	case 4:
	{
		if (encodedPointLen != EncodedPointSize(false))
			return false;

		unsigned int len = m_field->MaxElementByteLength();
		P.identity = false;
		P.x.Decode(bt, len);
		P.y.Decode(bt, len);
		return true;
	}
	default:
		return false;
	}
}
Пример #9
0
size_t BlockTransformation::AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const
{
	CRYPTOPP_ASSERT(inBlocks);
	CRYPTOPP_ASSERT(outBlocks);
	CRYPTOPP_ASSERT(length);

	size_t blockSize = BlockSize();
	size_t inIncrement = (flags & (BT_InBlockIsCounter|BT_DontIncrementInOutPointers)) ? 0 : blockSize;
	size_t xorIncrement = xorBlocks ? blockSize : 0;
	size_t outIncrement = (flags & BT_DontIncrementInOutPointers) ? 0 : blockSize;

	if (flags & BT_ReverseDirection)
	{
		CRYPTOPP_ASSERT(length % blockSize == 0);
		inBlocks += length - blockSize;
		xorBlocks += length - blockSize;
		outBlocks += length - blockSize;
		inIncrement = 0-inIncrement;
		xorIncrement = 0-xorIncrement;
		outIncrement = 0-outIncrement;
	}

	while (length >= blockSize)
	{
		if (flags & BT_XorInput)
		{
			// Coverity finding. However, xorBlocks is never NULL if BT_XorInput.
			CRYPTOPP_ASSERT(xorBlocks);
#if defined(__COVERITY__)
			if (xorBlocks)
#endif
			xorbuf(outBlocks, xorBlocks, inBlocks, blockSize);
			ProcessBlock(outBlocks);
		}
		else
		{
			// xorBlocks can be NULL. See, for example, ECB_OneWay::ProcessData.
			ProcessAndXorBlock(inBlocks, xorBlocks, outBlocks);
		}

		if (flags & BT_InBlockIsCounter)
			const_cast<byte *>(inBlocks)[blockSize-1]++;
		inBlocks += inIncrement;
		outBlocks += outIncrement;
		xorBlocks += xorIncrement;
		length -= blockSize;
	}

	return length;
}
Пример #10
0
ThreadLocalStorage::ThreadLocalStorage()
{
#ifdef HAS_WINTHREADS
	m_index = TlsAlloc();
	CRYPTOPP_ASSERT(m_index != TLS_OUT_OF_INDEXES);
	if (m_index == TLS_OUT_OF_INDEXES)
		throw Err("TlsAlloc", GetLastError());
#else
	m_index = 0;
	int error = pthread_key_create(&m_index, NULL);
	CRYPTOPP_ASSERT(!error);
	if (error)
		throw Err("pthread_key_create", error);
#endif
}
Пример #11
0
template <class T> void DL_FixedBasePrecomputationImpl<T>::Precompute(const DL_GroupPrecomputation<Element> &group, unsigned int maxExpBits, unsigned int storage)
{
	CRYPTOPP_ASSERT(m_bases.size() > 0);
	CRYPTOPP_ASSERT(storage <= maxExpBits);

	if (storage > 1)
	{
		m_windowSize = (maxExpBits+storage-1)/storage;
		m_exponentBase = Integer::Power2(m_windowSize);
	}

	m_bases.resize(storage);
	for (unsigned i=1; i<storage; i++)
		m_bases[i] = group.GetGroup().ScalarMultiply(m_bases[i-1], m_exponentBase);
}
Пример #12
0
void XTR_FindPrimesAndGenerator(RandomNumberGenerator &rng, Integer &p, Integer &q, GFP2Element &g, unsigned int pbits, unsigned int qbits)
{
	CRYPTOPP_ASSERT(qbits > 9);	// no primes exist for pbits = 10, qbits = 9
	CRYPTOPP_ASSERT(pbits > qbits);

	const Integer minQ = Integer::Power2(qbits - 1);
	const Integer maxQ = Integer::Power2(qbits) - 1;
	const Integer minP = Integer::Power2(pbits - 1);
	const Integer maxP = Integer::Power2(pbits) - 1;

top:

	Integer r1, r2;
	do
	{
		(void)q.Randomize(rng, minQ, maxQ, Integer::PRIME, 7, 12);
		// Solution always exists because q === 7 mod 12.
		(void)SolveModularQuadraticEquation(r1, r2, 1, -1, 1, q);
		// I believe k_i, r1 and r2 are being used slightly different than the
		// paper's algorithm. I believe it is leading to the failed asserts.
		// Just make the assert part of the condition.
		if(!p.Randomize(rng, minP, maxP, Integer::PRIME, CRT(rng.GenerateBit() ?
			r1 : r2, q, 2, 3, EuclideanMultiplicativeInverse(p, 3)), 3 * q)) { continue; }
	} while (((p % 3U) != 2) || (((p.Squared() - p + 1) % q).NotZero()));

	// CRYPTOPP_ASSERT((p % 3U) == 2);
	// CRYPTOPP_ASSERT(((p.Squared() - p + 1) % q).IsZero());

	GFP2_ONB<ModularArithmetic> gfp2(p);
	GFP2Element three = gfp2.ConvertIn(3), t;

	while (true)
	{
		g.c1.Randomize(rng, Integer::Zero(), p-1);
		g.c2.Randomize(rng, Integer::Zero(), p-1);
		t = XTR_Exponentiate(g, p+1, p);
		if (t.c1 == t.c2)
			continue;
		g = XTR_Exponentiate(g, (p.Squared()-p+1)/q, p);
		if (g != three)
			break;
	}

	if (XTR_Exponentiate(g, q, p) != three)
		goto top;

	// CRYPTOPP_ASSERT(XTR_Exponentiate(g, q, p) == three);
}
Пример #13
0
void HMAC_Base::KeyInnerHash()
{
	CRYPTOPP_ASSERT(!m_innerHashKeyed);
	HashTransformation &hash = AccessHash();
	hash.Update(AccessIpad(), hash.BlockSize());
	m_innerHashKeyed = true;
}
Пример #14
0
void OFB_ModePolicy::CipherResynchronize(byte *keystreamBuffer, const byte *iv, size_t length)
{
	CRYPTOPP_UNUSED(keystreamBuffer), CRYPTOPP_UNUSED(length);
	CRYPTOPP_ASSERT(length == BlockSize());

	CopyOrZero(m_register, iv, length);
}
Пример #15
0
bool SocketReceiver::Receive(byte* buf, size_t bufLen)
{
	CRYPTOPP_ASSERT(!m_resultPending && !m_eofReceived);

	DWORD flags = 0;
	// don't queue too much at once, or we might use up non-paged memory
	WSABUF wsabuf = {UnsignedMin((u_long)128*1024, bufLen), (char *)buf};
	if (WSARecv(m_s, &wsabuf, 1, &m_lastResult, &flags, &m_overlapped, NULL) == 0)
	{
		if (m_lastResult == 0)
			m_eofReceived = true;
	}
	else
	{
		switch (WSAGetLastError())
		{
		default:
			m_s.CheckAndHandleError_int("WSARecv", SOCKET_ERROR);
		case WSAEDISCON:
			m_lastResult = 0;
			m_eofReceived = true;
			break;
		case WSA_IO_PENDING:
			m_resultPending = true;
		}
	}
	return !m_resultPending;
}
Пример #16
0
void RawIDA::PrepareInterpolation()
{
	CRYPTOPP_ASSERT(m_inputChannelIds.size() == size_t(m_threshold));
	PrepareBulkPolynomialInterpolation(field, m_w.begin(), &(m_inputChannelIds[0]), (unsigned int)(m_threshold));
	for (unsigned int i=0; i<m_outputChannelIds.size(); i++)
		ComputeV(i);
}
Пример #17
0
void PKCS1v15_SignatureMessageEncodingMethod::ComputeMessageRepresentative(RandomNumberGenerator &rng,
	const byte *recoverableMessage, size_t recoverableMessageLength,
	HashTransformation &hash, HashIdentifier hashIdentifier, bool messageEmpty,
	byte *representative, size_t representativeBitLength) const
{
	CRYPTOPP_UNUSED(rng), CRYPTOPP_UNUSED(recoverableMessage), CRYPTOPP_UNUSED(recoverableMessageLength);
	CRYPTOPP_UNUSED(messageEmpty), CRYPTOPP_UNUSED(hashIdentifier);
	CRYPTOPP_ASSERT(representativeBitLength >= MinRepresentativeBitLength(hashIdentifier.second, hash.DigestSize()));

	size_t pkcsBlockLen = representativeBitLength;
	// convert from bit length to byte length
	if (pkcsBlockLen % 8 != 0)
	{
		representative[0] = 0;
		representative++;
	}
	pkcsBlockLen /= 8;

	representative[0] = 1;   // block type 1

	unsigned int digestSize = hash.DigestSize();
	byte *pPadding = representative + 1;
	byte *pDigest = representative + pkcsBlockLen - digestSize;
	byte *pHashId = pDigest - hashIdentifier.second;
	byte *pSeparator = pHashId - 1;

	// pad with 0xff
	memset(pPadding, 0xff, pSeparator-pPadding);
	*pSeparator = 0;
	memcpy(pHashId, hashIdentifier.first, hashIdentifier.second);
	hash.Final(pDigest);
}
Пример #18
0
bool WindowsPipeReceiver::Receive(byte* buf, size_t bufLen)
{
	CRYPTOPP_ASSERT(!m_resultPending && !m_eofReceived);

	HANDLE h = GetHandle();
	// don't queue too much at once, or we might use up non-paged memory
	if (ReadFile(h, buf, UnsignedMin((DWORD)128*1024, bufLen), &m_lastResult, &m_overlapped))
	{
		if (m_lastResult == 0)
			m_eofReceived = true;
	}
	else
	{
		switch (GetLastError())
		{
		default:
			CheckAndHandleError("ReadFile", false);
		case ERROR_BROKEN_PIPE:
		case ERROR_HANDLE_EOF:
			m_lastResult = 0;
			m_eofReceived = true;
			break;
		case ERROR_IO_PENDING:
			m_resultPending = true;
		}
	}
	return !m_resultPending;
}
Пример #19
0
void RDSEED::GenerateBlock(byte *output, size_t size)
{
	CRYPTOPP_UNUSED(output), CRYPTOPP_UNUSED(size);
	CRYPTOPP_ASSERT((output && size) || !(output || size));

	if(!HasRDSEED())
		throw NotImplemented("RDSEED: rdseed is not available on this platform");

	int rc; CRYPTOPP_UNUSED(rc);
#if MASM_RDSEED_ASM_AVAILABLE
	rc = MASM_RSA_GenerateBlock(output, size, m_retries);
	if (!rc) { throw RDSEED_Err("MASM_RSA_GenerateBlock"); }
#elif NASM_RDSEED_ASM_AVAILABLE
	rc = NASM_RSA_GenerateBlock(output, size, m_retries);
	if (!rc) { throw RDRAND_Err("NASM_RSA_GenerateBlock"); }
#elif ALL_RDSEED_INTRIN_AVAILABLE
	rc = ALL_RSI_GenerateBlock(output, size, m_retries);
	if (!rc) { throw RDSEED_Err("ALL_RSI_GenerateBlock"); }
#elif GCC_RDSEED_ASM_AVAILABLE
	rc = GCC_RSA_GenerateBlock(output, size, m_retries);
	if (!rc) { throw RDSEED_Err("GCC_RSA_GenerateBlock"); }
#else
	// RDSEED not detected at compile time, and no suitable compiler found
	throw NotImplemented("RDSEED: failed to find a suitable implementation???");
#endif
}
Пример #20
0
unsigned int Socket::Receive(byte* buf, size_t bufLen, int flags)
{
	CRYPTOPP_ASSERT(m_s != INVALID_SOCKET);
	int result = recv(m_s, (char *)buf, UnsignedMin(INT_MAX, bufLen), flags);
	CheckAndHandleError_int("recv", result);
	return result;
}
Пример #21
0
void AuthenticatedSymmetricCipherBase::Update(const byte *input, size_t length)
{
	if (length == 0)
		return;

	switch (m_state)
	{
	case State_Start:
	case State_KeySet:
		throw BadState(AlgorithmName(), "Update", "setting key and IV");
	case State_IVSet:
		AuthenticateData(input, length);
		m_totalHeaderLength += length;
		break;
	case State_AuthUntransformed:
	case State_AuthTransformed:
		AuthenticateLastConfidentialBlock();
		m_bufferedDataLength = 0;
		m_state = State_AuthFooter;
		// fall through
	case State_AuthFooter:
		AuthenticateData(input, length);
		m_totalFooterLength += length;
		break;
	default:
		CRYPTOPP_ASSERT(false);
	}
}
Пример #22
0
void HMAC_Base::UncheckedSetKey(const byte *userKey, unsigned int keylength, const NameValuePairs &)
{
	AssertValidKeyLength(keylength);

	Restart();

	HashTransformation &hash = AccessHash();
	unsigned int blockSize = hash.BlockSize();

	if (!blockSize)
		throw InvalidArgument("HMAC: can only be used with a block-based hash function");

	m_buf.resize(2*AccessHash().BlockSize() + AccessHash().DigestSize());

	if (keylength <= blockSize)
		memcpy(AccessIpad(), userKey, keylength);
	else
	{
		AccessHash().CalculateDigest(AccessIpad(), userKey, keylength);
		keylength = hash.DigestSize();
	}

	CRYPTOPP_ASSERT(keylength <= blockSize);
	memset(AccessIpad()+keylength, 0, blockSize-keylength);

	for (unsigned int i=0; i<blockSize; i++)
	{
		AccessOpad()[i] = AccessIpad()[i] ^ 0x5c;
		AccessIpad()[i] ^= 0x36;
	}
}
Пример #23
0
inline unsigned int HuffmanDecoder::Decode(code_t code, /* out */ value_t &value) const
{
	CRYPTOPP_ASSERT(m_codeToValue.size() > 0);
	LookupEntry &entry = m_cache[code & m_cacheMask];

	code_t normalizedCode = 0;
	if (entry.type != 1)
		normalizedCode = BitReverse(code);

	if (entry.type == 0)
		FillCacheEntry(entry, normalizedCode);

	if (entry.type == 1)
	{
		value = entry.value;
		return entry.len;
	}
	else
	{
		const CodeInfo &codeInfo = (entry.type == 2)
			? entry.begin[(normalizedCode << m_cacheBits) >> (MAX_CODE_BITS - (entry.len - m_cacheBits))]
			: *(std::upper_bound(entry.begin, entry.end, normalizedCode, CodeLessThan())-1);
		value = codeInfo.value;
		return codeInfo.len;
	}
}
Пример #24
0
DecodingResult PKCS_EncryptionPaddingScheme::Unpad(const byte *pkcsBlock, size_t pkcsBlockLen, byte *output, const NameValuePairs& parameters) const
{
	CRYPTOPP_UNUSED(parameters);
	bool invalid = false;
	size_t maxOutputLen = MaxUnpaddedLength(pkcsBlockLen);

	// convert from bit length to byte length
	if (pkcsBlockLen % 8 != 0)
	{
		invalid = (pkcsBlock[0] != 0) || invalid;
		pkcsBlock++;
	}
	pkcsBlockLen /= 8;

	// Require block type 2.
	invalid = (pkcsBlock[0] != 2) || invalid;

	// skip past the padding until we find the separator
	size_t i=1;
	while (i<pkcsBlockLen && pkcsBlock[i++]) { // null body
		}
	CRYPTOPP_ASSERT(i==pkcsBlockLen || pkcsBlock[i-1]==0);

	size_t outputLen = pkcsBlockLen - i;
	invalid = (outputLen > maxOutputLen) || invalid;

	if (invalid)
		return DecodingResult();

	memcpy (output, pkcsBlock+i, outputLen);
	return DecodingResult(outputLen);
}
Пример #25
0
void AuthenticatedSymmetricCipherBase::ProcessData(byte *outString, const byte *inString, size_t length)
{
	m_totalMessageLength += length;
	if (m_state >= State_IVSet && m_totalMessageLength > MaxMessageLength())
		throw InvalidArgument(AlgorithmName() + ": message length exceeds maximum");

reswitch:
	switch (m_state)
	{
	case State_Start:
	case State_KeySet:
		throw BadState(AlgorithmName(), "ProcessData", "setting key and IV");
	case State_AuthFooter:
		throw BadState(AlgorithmName(), "ProcessData was called after footer input has started");
	case State_IVSet:
		AuthenticateLastHeaderBlock();
		m_bufferedDataLength = 0;
		m_state = AuthenticationIsOnPlaintext()==IsForwardTransformation() ? State_AuthUntransformed : State_AuthTransformed;
		goto reswitch;
	case State_AuthUntransformed:
		AuthenticateData(inString, length);
		AccessSymmetricCipher().ProcessData(outString, inString, length);
		break;
	case State_AuthTransformed:
		AccessSymmetricCipher().ProcessData(outString, inString, length);
		AuthenticateData(outString, length);
		break;
	default:
		CRYPTOPP_ASSERT(false);
	}
}
Пример #26
0
size_t BufferedTransformation::TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel, bool blocking)
{
	if (AttachedTransformation())
		return AttachedTransformation()->TransferMessagesTo2(target, messageCount, channel, blocking);
	else
	{
		unsigned int maxMessages = messageCount;
		for (messageCount=0; messageCount < maxMessages && AnyMessages(); messageCount++)
		{
			size_t blockedBytes;
			lword transferredBytes;

			while (AnyRetrievable())
			{
				transferredBytes = LWORD_MAX;
				blockedBytes = TransferTo2(target, transferredBytes, channel, blocking);
				if (blockedBytes > 0)
					return blockedBytes;
			}

			if (target.ChannelMessageEnd(channel, GetAutoSignalPropagation(), blocking))
				return 1;

			bool result = GetNextMessage();
			CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result);
		}
		return 0;
	}
}
Пример #27
0
bool Socket::Connect(const char *addr, unsigned int port)
{
	CRYPTOPP_ASSERT(addr != NULL);

	sockaddr_in sa;
	memset(&sa, 0, sizeof(sa));
	sa.sin_family = AF_INET;
	sa.sin_addr.s_addr = inet_addr(addr);

	if (sa.sin_addr.s_addr == static_cast<unsigned int>(-1))	// Solaris doesn't have INADDR_NONE
	{
		hostent *lphost = gethostbyname(addr);
		if (lphost == NULL)
		{
			SetLastError(SOCKET_EINVAL);
			CheckAndHandleError_int("gethostbyname", SOCKET_ERROR);
		}

		sa.sin_addr.s_addr = ((in_addr *)lphost->h_addr)->s_addr;
	}

	sa.sin_port = htons((u_short)port);

	return Connect((const sockaddr *)&sa, sizeof(sa));
}
Пример #28
0
unsigned int Socket::Send(const byte* buf, size_t bufLen, int flags)
{
	CRYPTOPP_ASSERT(m_s != INVALID_SOCKET);
	int result = send(m_s, (const char *)buf, UnsignedMin(INT_MAX, bufLen), flags);
	CheckAndHandleError_int("send", result);
	return result;
}
Пример #29
0
size_t BufferedTransformation::TransferAllTo2(BufferedTransformation &target, const std::string &channel, bool blocking)
{
	if (AttachedTransformation())
		return AttachedTransformation()->TransferAllTo2(target, channel, blocking);
	else
	{
		CRYPTOPP_ASSERT(!NumberOfMessageSeries());

		unsigned int messageCount;
		do
		{
			messageCount = UINT_MAX;
			size_t blockedBytes = TransferMessagesTo2(target, messageCount, channel, blocking);
			if (blockedBytes)
				return blockedBytes;
		}
		while (messageCount != 0);

		lword byteCount;
		do
		{
			byteCount = ULONG_MAX;
			size_t blockedBytes = TransferTo2(target, byteCount, channel, blocking);
			if (blockedBytes)
				return blockedBytes;
		}
		while (byteCount != 0);

		return 0;
	}
}
Пример #30
0
OldRandomPool::OldRandomPool(unsigned int poolSize)
        : pool(poolSize), key(OldRandomPoolCipher::DEFAULT_KEYLENGTH), addPos(0), getPos(poolSize)
{
	CRYPTOPP_ASSERT(poolSize > key.size());
	::memset(pool, 0, poolSize);
	::memset(key, 0, key.size());
}