DatagramEncryptor::DatagramEncryptor(const bytes &encryptionKey, const bytes &IV, const bytes &macKey) :
		aesCtr(&IV[0], IV.size(), &encryptionKey[0], encryptionKey.size()),
		hmac(sha1, macKey)
	{
		if (macKey.size() < sha1.outputLen()) throw DsrpException("DatagramEncryptor::DatagramEncryptor: macKey not long enough");
		
	}
std::tuple<QList<QObject*>, QQMLMap*> DebuggingStateWrapper::getHumanReadableCode(const bytes& _code, QObject* _objUsedAsParent)
{
	QList<QObject*> codeStr;
	QMap<int, int> codeMapping;
	for (unsigned i = 0; i <= _code.size(); ++i)
	{
		byte b = i < _code.size() ? _code[i] : 0;
		try
		{
			QString s = QString::fromStdString(instructionInfo((Instruction)b).name);
			std::ostringstream out;
			out << std::hex << std::setw(4) << std::setfill('0') << i;
			codeMapping[i] = codeStr.size();
			int line = i;
			if (b >= (byte)Instruction::PUSH1 && b <= (byte)Instruction::PUSH32)
			{
				unsigned bc = getPushNumber((Instruction)b);
				s = "PUSH 0x" + QString::fromStdString(toHex(bytesConstRef(&_code[i + 1], bc)));
				i += bc;
			}
			HumanReadableCode* humanCode = new HumanReadableCode(QString::fromStdString(out.str()) + "  "  + s, line, _objUsedAsParent);
			codeStr.append(humanCode);
		}
		catch (...)
		{
			qDebug() << QString("Unhandled exception!") << endl <<
					 QString::fromStdString(boost::current_exception_diagnostic_information());
			break;	// probably hit data segment
		}
	}
	return std::make_tuple(codeStr, new QQMLMap(codeMapping, _objUsedAsParent));
}
Example #3
0
bytes Secp256k1PP::eciesKDF(Secret const& _z, bytes _s1, unsigned kdByteLen)
{
	auto reps = ((kdByteLen + 7) * 8) / (CryptoPP::SHA256::BLOCKSIZE * 8);
	// SEC/ISO/Shoup specify counter size SHOULD be equivalent
	// to size of hash output, however, it also notes that
	// the 4 bytes is okay. NIST specifies 4 bytes.
	bytes ctr({0, 0, 0, 1});
	bytes k;
	CryptoPP::SHA256 ctx;
	for (unsigned i = 0; i <= reps; i++)
	{
		ctx.Update(ctr.data(), ctr.size());
		ctx.Update(_z.data(), Secret::size);
		ctx.Update(_s1.data(), _s1.size());
		// append hash to k
		bytes digest(32);
		ctx.Final(digest.data());
		ctx.Restart();
		
		k.reserve(k.size() + h256::size);
		move(digest.begin(), digest.end(), back_inserter(k));
		
		if (++ctr[3] || ++ctr[2] || ++ctr[1] || ++ctr[0])
			continue;
	}
	
	k.resize(kdByteLen);
	return k;
}
Example #4
0
void Packet::parse(bytes data) {
    memcpy(&head[0], &data[0], HEADER_LEN);
    body.resize(data.size() - HEADER_LEN);
    memcpy(&body[0], &data[HEADER_LEN], data.size() - HEADER_LEN);
    int i = 0;
    short checkLen = 0x0;
    pull(head, i, version);
    pull(head, i, opCode);
    pull(head, i, switchMac);
    pull(head, i, hostMac);
    pull(head, i, sequenceId);
    pull(head, i, errorCode);
    pull(head, i, checkLen);
    pull(head, i, fragmentOffset);
    pull(head, i, flag);
    pull(head, i, tokenId);
    pull(head, i, checkSum);
    if (this->getLength() != checkLen) {
        printf("Packet Length doesn't match: %lu != %hd\n", data.size(),
                checkLen);
    }
    i = 0;
    dataset d;
    payload = {};
    while (i < (int) body.size() - 4) {
        pull(body, i, d.type);
        pull(body, i, d.len);
        pull(body, i, d.value, d.len);
        payload.push_back(d);
    }
}
Example #5
0
bytes ecies::kdf(Secret const& _z, bytes const& _s1, unsigned kdByteLen)
{
    auto reps = ((kdByteLen + 7) * 8) / 512;
    // SEC/ISO/Shoup specify counter size SHOULD be equivalent
    // to size of hash output, however, it also notes that
    // the 4 bytes is okay. NIST specifies 4 bytes.
    std::array<byte, 4> ctr{{0, 0, 0, 1}};
    bytes k;
    secp256k1_sha256_t ctx;
    for (unsigned i = 0; i <= reps; i++)
    {
        secp256k1_sha256_initialize(&ctx);
        secp256k1_sha256_write(&ctx, ctr.data(), ctr.size());
        secp256k1_sha256_write(&ctx, _z.data(), Secret::size);
        secp256k1_sha256_write(&ctx, _s1.data(), _s1.size());
        // append hash to k
        std::array<byte, 32> digest;
        secp256k1_sha256_finalize(&ctx, digest.data());

        k.reserve(k.size() + h256::size);
        move(digest.begin(), digest.end(), back_inserter(k));

        if (++ctr[3] || ++ctr[2] || ++ctr[1] || ++ctr[0])
            continue;
    }

    k.resize(kdByteLen);
    return k;
}
void Secp256k1PP::encrypt(Public const& _k, bytes& io_cipher)
{
	auto& ctx = Secp256k1PPCtx::get();

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
	CryptoPP::ECIES<CryptoPP::ECP>::Encryptor e;
#pragma GCC diagnostic pop
#pragma clang diagnostic pop

	{
		Guard l(ctx.x_params);
		e.AccessKey().Initialize(ctx.m_params, publicToPoint(_k));
	}


	size_t plen = io_cipher.size();
	bytes ciphertext;
	ciphertext.resize(e.CiphertextLength(plen));
	
	{
		Guard l(ctx.x_rng);
		e.Encrypt(ctx.m_rng, io_cipher.data(), plen, ciphertext.data());
	}
	
	memset(io_cipher.data(), 0, io_cipher.size());
	io_cipher = std::move(ciphertext);
}
Example #7
0
string dev::memDump(bytes const& _bytes, unsigned _width, bool _html)
{
	stringstream ret;
	if (_html)
		ret << "<pre style=\"font-family: Monospace,Lucida Console,Courier,Courier New,sans-serif; font-size: small\">";
	for (unsigned i = 0; i < _bytes.size(); i += _width)
	{
		ret << hex << setw(4) << setfill('0') << i << " ";
		for (unsigned j = i; j < i + _width; ++j)
			if (j < _bytes.size())
				if (_bytes[j] >= 32 && _bytes[j] < 127)
					if ((char)_bytes[j] == '<' && _html)
						ret << "&lt;";
					else if ((char)_bytes[j] == '&' && _html)
						ret << "&amp;";
					else
						ret << (char)_bytes[j];
				else
					ret << '?';
			else
				ret << ' ';
		ret << " ";
		for (unsigned j = i; j < i + _width && j < _bytes.size(); ++j)
			ret << setfill('0') << setw(2) << hex << (unsigned)_bytes[j] << " ";
		ret << "\n";
	}
	if (_html)
		ret << "</pre>";
	return ret.str();
}
Example #8
0
void Secp256k1PP::encryptECIES(Public const& _k, bytesConstRef _sharedMacData, bytes& io_cipher)
{
	// interop w/go ecies implementation
	auto r = KeyPair::create();
	Secret z;
	ecdh::agree(r.sec(), _k, z);
	auto key = eciesKDF(z, bytes(), 32);
	bytesConstRef eKey = bytesConstRef(&key).cropped(0, 16);
	bytesRef mKeyMaterial = bytesRef(&key).cropped(16, 16);
	CryptoPP::SHA256 ctx;
	ctx.Update(mKeyMaterial.data(), mKeyMaterial.size());
	bytes mKey(32);
	ctx.Final(mKey.data());
	
	bytes cipherText = encryptSymNoAuth(SecureFixedHash<16>(eKey), h128(), bytesConstRef(&io_cipher));
	if (cipherText.empty())
		return;

	bytes msg(1 + Public::size + h128::size + cipherText.size() + 32);
	msg[0] = 0x04;
	r.pub().ref().copyTo(bytesRef(&msg).cropped(1, Public::size));
	bytesRef msgCipherRef = bytesRef(&msg).cropped(1 + Public::size + h128::size, cipherText.size());
	bytesConstRef(&cipherText).copyTo(msgCipherRef);
	
	// tag message
	CryptoPP::HMAC<SHA256> hmacctx(mKey.data(), mKey.size());
	bytesConstRef cipherWithIV = bytesRef(&msg).cropped(1 + Public::size, h128::size + cipherText.size());
	hmacctx.Update(cipherWithIV.data(), cipherWithIV.size());
	hmacctx.Update(_sharedMacData.data(), _sharedMacData.size());
	hmacctx.Final(msg.data() + 1 + Public::size + cipherWithIV.size());
	
	io_cipher.resize(msg.size());
	io_cipher.swap(msg);
}
Example #9
0
static void pushLocation(bytes& o_code, uint32_t _locationValue)
{
	o_code.push_back((byte)Instruction::PUSH4);
	o_code.resize(o_code.size() + 4);
	bytesRef r(&o_code[o_code.size() - 4], 4);
	toBigEndian(_locationValue, r);
}
Example #10
0
void Packet::push(bytes &arr, int &index, byte data) {
    if (arr.size() > (unsigned) index) {
        arr[index++] = data;
    } else {
        arr.push_back(data);
        index++;
    }
}
Example #11
0
static unsigned pushLiteral(bytes& o_code, u256 _literalValue)
{
	unsigned br = max<unsigned>(1, bytesRequired(_literalValue));
	o_code.push_back((byte)Instruction::PUSH1 + br - 1);
	o_code.resize(o_code.size() + br);
	for (unsigned i = 0; i < br; ++i)
	{
		o_code[o_code.size() - 1 - i] = (byte)(_literalValue & 0xff);
		_literalValue >>= 8;
	}
	return br + 1;
}
Example #12
0
    bytes unpadLeft(bytes _b)
    {
        unsigned int i = 0;
        if (_b.size() == 0)
            return _b;

        while (i < _b.size() && _b[i] == byte(0))
            i++;

        if (i != 0)
            _b.erase(_b.begin(), _b.begin() + i);
        return _b;
    }
Example #13
0
 bytes public_key::decrypt( const bytes& in )const
 {
    FC_ASSERT( my && my->rsa );
    bytes out( RSA_size(my->rsa) );//, char(0) );
    int rtn = RSA_public_decrypt( in.size(),
                                   (unsigned char*)in.data(),
                                   (unsigned char*)out.data(),
                                   my->rsa, RSA_PKCS1_OAEP_PADDING );
    if( rtn >= 0 ) {
       out.resize(rtn);
       return out;
    }
    FC_THROW_EXCEPTION( exception, "openssl: ${message}", ("message",fc::string(ERR_error_string( ERR_get_error(),NULL))) );
 }
Example #14
0
    public_key::public_key( const bytes& d )
    :my( std::make_shared<detail::pke_impl>() )
    {
       string pem = "-----BEGIN RSA PUBLIC KEY-----\n";
       auto b64 = fc::base64_encode( (const unsigned char*)d.data(), d.size() );
       for( size_t i = 0; i < b64.size(); i += 64 )
           pem += b64.substr( i, 64 ) + "\n";
       pem += "-----END RSA PUBLIC KEY-----\n";
    //   fc::cerr<<pem;

       BIO* mem = (BIO*)BIO_new_mem_buf( (void*)pem.c_str(), pem.size() );
       my->rsa = PEM_read_bio_RSAPublicKey(mem, NULL, NULL, NULL );
       BIO_free(mem);
    }
Example #15
0
 bytes private_key::decrypt( const bytes& in )const
 {
    if( !my ) FC_THROW_EXCEPTION( assert_exception, "!null" );
    bytes out;
    out.resize( RSA_size(my->rsa) );
    int rtn = RSA_private_decrypt( in.size(),
                                   (unsigned char*)in.data(),
                                   (unsigned char*)out.data(),
                                   my->rsa, RSA_PKCS1_OAEP_PADDING );
    if( rtn >= 0 ) {
       out.resize(rtn);
       return out;
    }
    FC_THROW_EXCEPTION( exception, "decrypt failed" );
 }
Example #16
0
bytesSec dev::pbkdf2(string const& _pass, bytes const& _salt, unsigned _iterations, unsigned _dkLen)
{
	bytesSec ret(_dkLen);
	if (PKCS5_PBKDF2_HMAC<SHA256>().DeriveKey(
		ret.writable().data(),
		_dkLen,
		0,
		reinterpret_cast<byte const*>(_pass.data()),
		_pass.size(),
		_salt.data(),
		_salt.size(),
		_iterations
	) != _iterations)
		BOOST_THROW_EXCEPTION(CryptoException() << errinfo_comment("Key derivation failed."));
	return ret;
}
	bytes SrpClientAuthenticator::getSessionKey(bytes M2_from_server)
	{
		if (M2_from_server.size() == 0) throw DsrpException("SrpClientAuthenticator::getSessionKey: M2_from_server.size() == 0");
		if (M2_calculated.size() == 0) throw DsrpException("SrpClientAuthenticator::getSessionKey: M2_calculated.size() == 0");
		if (M2_from_server != M2_calculated) throw DsrpException("Authentification failed, bad password");
		return K;
	}
Example #18
0
static vector<bytes> zlib_decompress_context_free_data(const bytes& data) {
   if( data.size() == 0 )
      return vector<bytes>();

   bytes out = zlib_decompress(data);
   return unpack_context_free_data(out);
}
Example #19
0
bool beginsWith(Address _a, bytes const& _b)
{
	for (unsigned i = 0; i < min<unsigned>(20, _b.size()); ++i)
		if (_a[i] != _b[i])
			return false;
	return true;
}
void LmRightSpotScene::onGamecomponentEvent(bytes l_oMsg)
{

	int idGameComponent = l_oMsg.readInt();

	layerChildReceive(idGameComponent);
}
Example #21
0
void Packet::encode(bytes &data) {
    int len = data.size();
    bytes key = { 191, 155, 227, 202, 99, 162, 79, 104, 49, 18, 190, 164, 30,
            76, 189, 131, 23, 52, 86, 106, 207, 125, 126, 169, 196, 28, 172, 58,
            188, 132, 160, 3, 36, 120, 144, 168, 12, 231, 116, 44, 41, 97, 108,
            213, 42, 198, 32, 148, 218, 107, 247, 112, 204, 14, 66, 68, 91, 224,
            206, 235, 33, 130, 203, 178, 1, 134, 199, 78, 249, 123, 7, 145, 73,
            208, 209, 100, 74, 115, 72, 118, 8, 22, 243, 147, 64, 96, 5, 87, 60,
            113, 233, 152, 31, 219, 143, 174, 232, 153, 245, 158, 254, 70, 170,
            75, 77, 215, 211, 59, 71, 133, 214, 157, 151, 6, 46, 81, 94, 136,
            166, 210, 4, 43, 241, 29, 223, 176, 67, 63, 186, 137, 129, 40, 248,
            255, 55, 15, 62, 183, 222, 105, 236, 197, 127, 54, 179, 194, 229,
            185, 37, 90, 237, 184, 25, 156, 173, 26, 187, 220, 2, 225, 0, 240,
            50, 251, 212, 253, 167, 17, 193, 205, 177, 21, 181, 246, 82, 226,
            38, 101, 163, 182, 242, 92, 20, 11, 95, 13, 230, 16, 121, 124, 109,
            195, 117, 39, 98, 239, 84, 56, 139, 161, 47, 201, 51, 135, 250, 10,
            19, 150, 45, 111, 27, 24, 142, 80, 85, 83, 234, 138, 216, 57, 93,
            65, 154, 141, 122, 34, 140, 128, 238, 88, 89, 9, 146, 171, 149, 53,
            102, 61, 114, 69, 217, 175, 103, 228, 35, 180, 252, 200, 192, 165,
            159, 221, 244, 110, 119, 48 };
    bytes s = key;
    int i, j = 0;
    for (int k = 0; k < len; k++) {
        i = (k + 1) % 256;
        j = (j + s[i]) % 256;
        std::swap(s[i], s[j]);
        data[k] = data[k] ^ s[(s[i] + s[j]) % 256];
    }
}
Example #22
0
static bytes zlib_decompress(const bytes& data) {
   try {
      bytes out;
      bio::filtering_ostream decomp;
      decomp.push(bio::zlib_decompressor());
      decomp.push(read_limiter<1*1024*1024>()); // limit to 10 megs decompressed for zip bomb protections
      decomp.push(bio::back_inserter(out));
      bio::write(decomp, data.data(), data.size());
      bio::close(decomp);
      return out;
   } catch( fc::exception& er ) {
      throw;
   } catch( ... ) {
      fc::unhandled_exception er( FC_LOG_MESSAGE( warn, "internal decompression error"), std::current_exception() );
      throw er;
   }
}
Example #23
0
void Secp256k1PP::encrypt(Public const& _k, bytes& io_cipher)
{
	ECIES<ECP>::Encryptor e;
	initializeDLScheme(_k, e);

	size_t plen = io_cipher.size();
	bytes ciphertext;
	ciphertext.resize(e.CiphertextLength(plen));
	
	{
		Guard l(x_rng);
		e.Encrypt(m_rng, io_cipher.data(), plen, ciphertext.data());
	}
	
	memset(io_cipher.data(), 0, io_cipher.size());
	io_cipher = std::move(ciphertext);
}
Example #24
0
bytesSec dev::scrypt(std::string const& _pass, bytes const& _salt, uint64_t _n, uint32_t _r, uint32_t _p, unsigned _dkLen)
{
	bytesSec ret(_dkLen);
	if (libscrypt_scrypt(
		reinterpret_cast<uint8_t const*>(_pass.data()),
		_pass.size(),
		_salt.data(),
		_salt.size(),
		_n,
		_r,
		_p,
		ret.writable().data(),
		_dkLen
	) != 0)
		BOOST_THROW_EXCEPTION(CryptoException() << errinfo_comment("Key derivation failed."));
	return ret;
}
Example #25
0
void Secp256k1PP::decrypt(Secret const& _k, bytes& io_text)
{
	CryptoPP::ECIES<CryptoPP::ECP>::Decryptor d;
	initializeDLScheme(_k, d);

	if (!io_text.size())
	{
		io_text.resize(1);
		io_text[0] = 0;
	}
	
	size_t clen = io_text.size();
	bytes plain;
	plain.resize(d.MaxPlaintextLength(io_text.size()));
	
	DecodingResult r;
	{
		Guard l(x_rng);
		r = d.Decrypt(m_rng, io_text.data(), clen, plain.data());
	}
	
	if (!r.isValidCoding)
	{
		io_text.clear();
		return;
	}
	
	io_text.resize(r.messageLength);
	io_text = std::move(plain);
}
Example #26
0
bool RaftClient::submitSealed(bytes const& _block, bool _isOurs)
{
	uint64_t now = utcTime();
	uint64_t interval = now - m_last_import_time;
	m_last_import_time = now;
	LOG(TRACE) << "Client_submitSealed: _block.size() = " << _block.size() << ",_isOurs=" << _isOurs << ",interval=" << interval;

	// OPTIMISE: very inefficient to not utilise the existing OverlayDB in m_postSeal that contains all trie changes.
	return m_bq.import(&_block, _isOurs) == ImportResult::Success;
}
Example #27
0
string eth::disassemble(bytes const& _mem)
{
	stringstream ret;
	uint numerics = 0;
	for (auto it = _mem.begin(); it != _mem.end(); ++it)
	{
		byte n = *it;
		auto iit = c_instructionInfo.find((Instruction)n);
		if (numerics || iit == c_instructionInfo.end() || (byte)iit->first != n)	// not an instruction or expecting an argument...
		{
			if (numerics)
				numerics--;
			ret << "0x" << hex << (int)n << " ";
		}
		else
		{
			auto const& ii = iit->second;
			ret << ii.name << " ";
			numerics = ii.additional;
		}
	}
	return ret.str();
}
void LmRightSpotScene::onGamecomponentWellPlacedEvent(bytes l_oMsg)
{
	int l_iIdGameComponent = l_oMsg.readInt();
	bool l_bWellPlaced = l_oMsg.readBool();

	if (l_bWellPlaced)
	{

		//erase it of the elements that can be touched
		m_aDynamicGameComponents.erase(
				std::remove(m_aDynamicGameComponents.begin(),
						m_aDynamicGameComponents.end(),
						m_aIdTable.find(l_iIdGameComponent)->second),
				m_aDynamicGameComponents.end());

		m_iNumberOfHole--;

		//make disapear this element
		m_aIdTable.find(l_iIdGameComponent)->second->setVisible(false);

		//check win
		if (m_iNumberOfHole == 0)
		{
			win(true);
		}
	}
	else
	{
		//replace this element in the list
		replaceSendingAreaElementToHisOriginalPlace();

		m_pSpriteFail->setVisible(true);
	}

	m_bTouchBeganDisabled = false;

}
std::string hexPrefixEncode(bytes const& _hexVector, bool _leaf, int _begin, int _end)
{
	unsigned begin = _begin;
	unsigned end = _end < 0 ? _hexVector.size() + 1 + _end : _end;
	bool odd = ((end - begin) % 2) != 0;

	std::string ret(1, ((_leaf ? 2 : 0) | (odd ? 1 : 0)) * 16);
	if (odd)
	{
		ret[0] |= _hexVector[begin];
		++begin;
	}
	for (unsigned i = begin; i < end; i += 2)
		ret += _hexVector[i] * 16 + _hexVector[i + 1];
	return ret;
}
Example #30
0
bool Secp256k1PP::decryptECIES(Secret const& _k, bytesConstRef _sharedMacData, bytes& io_text)
{

	// interop w/go ecies implementation
	
	// io_cipher[0] must be 2, 3, or 4, else invalidpublickey
	if (io_text.empty() || io_text[0] < 2 || io_text[0] > 4)
		// invalid message: publickey
		return false;
	
	if (io_text.size() < (1 + Public::size + h128::size + 1 + h256::size))
		// invalid message: length
		return false;

	Secret z;
	if (!ecdh::agree(_k, *(Public*)(io_text.data() + 1), z))
		return false;  // Invalid pubkey or seckey.
	auto key = ecies::kdf(z, bytes(), 64);
	bytesConstRef eKey = bytesConstRef(&key).cropped(0, 16);
	bytesRef mKeyMaterial = bytesRef(&key).cropped(16, 16);
	bytes mKey(32);
	CryptoPP::SHA256 ctx;
	ctx.Update(mKeyMaterial.data(), mKeyMaterial.size());
	ctx.Final(mKey.data());
	
	bytes plain;
	size_t cipherLen = io_text.size() - 1 - Public::size - h128::size - h256::size;
	bytesConstRef cipherWithIV(io_text.data() + 1 + Public::size, h128::size + cipherLen);
	bytesConstRef cipherIV = cipherWithIV.cropped(0, h128::size);
	bytesConstRef cipherNoIV = cipherWithIV.cropped(h128::size, cipherLen);
	bytesConstRef msgMac(cipherNoIV.data() + cipherLen, h256::size);
	h128 iv(cipherIV.toBytes());
	
	// verify tag
	CryptoPP::HMAC<CryptoPP::SHA256> hmacctx(mKey.data(), mKey.size());
	hmacctx.Update(cipherWithIV.data(), cipherWithIV.size());
	hmacctx.Update(_sharedMacData.data(), _sharedMacData.size());
	h256 mac;
	hmacctx.Final(mac.data());
	for (unsigned i = 0; i < h256::size; i++)
		if (mac[i] != msgMac[i])
			return false;
	
	plain = decryptSymNoAuth(SecureFixedHash<16>(eKey), iv, cipherNoIV).makeInsecure();
	io_text.resize(plain.size());
	io_text.swap(plain);
	
	return true;
}