示例#1
0
	void VolumeHeader::EncryptNew (const BufferPtr &newHeaderBuffer, const ConstBufferPtr &newSalt, const ConstBufferPtr &newHeaderKey, shared_ptr <Pkcs5Kdf> newPkcs5Kdf)
	{
		if (newHeaderBuffer.Size() != HeaderSize || newSalt.Size() != SaltSize)
			throw ParameterIncorrect (SRC_POS);

		shared_ptr <EncryptionMode> mode = EA->GetMode()->GetNew();
		shared_ptr <EncryptionAlgorithm> ea = EA->GetNew();

		if (typeid (*mode) == typeid (EncryptionModeXTS))
		{
			mode->SetKey (newHeaderKey.GetRange (EA->GetKeySize(), EA->GetKeySize()));
			ea->SetKey (newHeaderKey.GetRange (0, ea->GetKeySize()));
		}
		else
		{
			mode->SetKey (newHeaderKey.GetRange (0, mode->GetKeySize()));
			ea->SetKey (newHeaderKey.GetRange (LegacyEncryptionModeKeyAreaSize, ea->GetKeySize()));
		}

		ea->SetMode (mode);

		newHeaderBuffer.CopyFrom (newSalt);

		BufferPtr headerData = newHeaderBuffer.GetRange (EncryptedHeaderDataOffset, EncryptedHeaderDataSize);
		Serialize (headerData);
		ea->Encrypt (headerData);

		if (newPkcs5Kdf)
			Pkcs5 = newPkcs5Kdf;
	}
示例#2
0
	T VolumeHeader::DeserializeEntryAt (const ConstBufferPtr &header, const size_t &offset) const
	{
		if (offset > header.Size())
			throw ParameterIncorrect (SRC_POS);

		return Endian::Big (*reinterpret_cast<const T *> (header.Get() + offset));
	}
示例#3
0
bool
Block::fromBuffer(const ConstBufferPtr& wire, size_t offset, Block& block)
{
  Buffer::const_iterator tempBegin = wire->begin() + offset;

  uint32_t type;
  bool isOk = Tlv::readType(tempBegin, wire->end(), type);
  if (!isOk)
    return false;

  uint64_t length;
  isOk = Tlv::readVarNumber(tempBegin, wire->end(), length);
  if (!isOk)
    return false;

  if (length > static_cast<uint64_t>(wire->end() - tempBegin))
    {
      return false;
    }

  block = Block(wire, type,
                wire->begin() + offset, tempBegin + length,
                tempBegin, tempBegin + length);

  return true;
}
示例#4
0
	void BufferPtr::CopyFrom (const ConstBufferPtr &bufferPtr) const
	{
		if (bufferPtr.Size() > DataSize)
			throw ParameterTooLarge (SRC_POS);

		Memory::Copy (DataPtr, bufferPtr.Get(), bufferPtr.Size());
	}
Digest<Hash>&
Digest<Hash>::operator<<(Digest<Hash>& src)
{
  ConstBufferPtr buffer = src.computeDigest();
  update(buffer->get(), buffer->size());

  return *this;
}
示例#6
0
void File::WriteAt (const ConstBufferPtr &buffer, uint64 position) const
{
    if_debug (ValidateState());

#ifdef TC_TRACE_FILE_OPERATIONS
    TraceFileOperation (FileHandle, Path, true, buffer.Size(), position);
#endif
    throw_sys_sub_if (pwrite (FileHandle, buffer, buffer.Size(), position) != (ssize_t) buffer.Size(), wstring (Path));
}
bool VolumeHeader::Decrypt (const ConstBufferPtr &encryptedData, const VolumePassword &password, const Pkcs5KdfList &keyDerivationFunctions, const EncryptionAlgorithmList &encryptionAlgorithms, const EncryptionModeList &encryptionModes)
{
    if (password.Size() < 1)
        throw PasswordEmpty (SRC_POS);

    ConstBufferPtr salt (encryptedData.GetRange (SaltOffset, SaltSize));
    SecureBuffer header (EncryptedHeaderDataSize);
    SecureBuffer headerKey (GetLargestSerializedKeySize());

    foreach (shared_ptr <Pkcs5Kdf> pkcs5, keyDerivationFunctions)
    {
        pkcs5->DeriveKey (headerKey, password, salt);

        foreach (shared_ptr <EncryptionMode> mode, encryptionModes)
        {
            if (typeid (*mode) != typeid (EncryptionModeXTS))
                mode->SetKey (headerKey.GetRange (0, mode->GetKeySize()));

            foreach (shared_ptr <EncryptionAlgorithm> ea, encryptionAlgorithms)
            {
                if (!ea->IsModeSupported (mode))
                    continue;

                /*
                printf("trying %ls, %ls, %ls\n", pkcs5->GetName().c_str(),
                							mode->GetName().c_str(),
                							ea->GetName().c_str()
                							);
                							*/


                if (typeid (*mode) == typeid (EncryptionModeXTS))
                {
                    ea->SetKey (headerKey.GetRange (0, ea->GetKeySize()));

                    mode = mode->GetNew();
                    mode->SetKey (headerKey.GetRange (ea->GetKeySize(), ea->GetKeySize()));
                }
                else
                {
                    ea->SetKey (headerKey.GetRange (LegacyEncryptionModeKeyAreaSize, ea->GetKeySize()));
                }

                ea->SetMode (mode);

                header.CopyFrom (encryptedData.GetRange (EncryptedHeaderDataOffset, EncryptedHeaderDataSize));
                ea->Decrypt (header);

                if (Deserialize (header, ea, mode))
                {
                    EA = ea;
                    Pkcs5 = pkcs5;
                    return true;
                }
            }
        }
    }
示例#8
0
	void Buffer::CopyFrom (const ConstBufferPtr &bufferPtr)
	{
		if (!IsAllocated ())
			Allocate (bufferPtr.Size());
		else if (bufferPtr.Size() > DataSize)
			throw ParameterTooLarge (SRC_POS);

		Memory::Copy (DataPtr, bufferPtr.Get(), bufferPtr.Size());
	}
std::ostream&
operator<<(std::ostream& os, Digest<Hash>& digest)
{
  using namespace CryptoPP;

  std::string output;
  ConstBufferPtr buffer = digest.computeDigest();
  StringSource(buffer->buf(), buffer->size(), true, new HexEncoder(new FileSink(os)));

  return os;
}
	void EncryptionAlgorithm::SetKey (const ConstBufferPtr &key)
	{
		if (Ciphers.size() < 1)
			throw NotInitialized (SRC_POS);

		if (GetKeySize() != key.Size())
			throw ParameterIncorrect (SRC_POS);

		size_t keyOffset = 0;
		foreach_ref (Cipher &c, Ciphers)
		{
			c.SetKey (key.GetRange (keyOffset, c.GetKeySize()));
			keyOffset += c.GetKeySize();
		}
	uint64 MemoryStream::Read (const BufferPtr &buffer)
	{
		if (Data.size() == 0)
			throw ParameterIncorrect (SRC_POS);

		ConstBufferPtr streamBuf (*this);
		size_t len = buffer.Size();
		if (streamBuf.Size() - ReadPosition < len)
			len = streamBuf.Size() - ReadPosition;

		BufferPtr(buffer).CopyFrom (streamBuf.GetRange (ReadPosition, len));
		ReadPosition += len;
		return len;
	}
示例#12
0
std::ostream& operator << ( std::ostream& os, const ICommand& command )
{
    ConstBufferPtr buffer = command.getBuffer();
    if( buffer )
        os << lunchbox::disableFlush << "command< type "
           << uint32_t( command.getType( )) << " cmd " << command.getCommand()
           << " size " << command.getSize() << '/' << buffer->getSize() << '/'
           << buffer->getMaxSize() << " from " << command.getNode() << " to "
           << command.getLocalNode() << " >" << lunchbox::enableFlush;
    else
        os << "command< empty >";

    if( command._impl->func.isValid( ))
        os << ' ' << command._impl->func << std::endl;
    return os;
}
示例#13
0
	void EncryptionModeLRW::SetKey (const ConstBufferPtr &key)
	{
		if (key.Size() != 16)
			throw ParameterIncorrect (SRC_POS);

		if (!KeySet)
			GfContext.Allocate (sizeof (GfCtx));

		if (!Gf64TabInit ((unsigned char *) key.Get(), (GfCtx *) (GfContext.Ptr())))
			throw bad_alloc();

		if (!Gf128Tab64Init ((unsigned char *) key.Get(), (GfCtx *) (GfContext.Ptr())))
			throw bad_alloc();

		Key.CopyFrom (key);
		KeySet = true;
	}
示例#14
0
文件: block.hpp 项目: ltr120/ndn-cpp
inline void
Block::reset()
{
  m_buffer.reset(); // reset of the shared_ptr
  m_subBlocks.clear(); // remove all parsed subelements

  m_type = std::numeric_limits<uint32_t>::max();
  m_begin = m_end = m_value_begin = m_value_end = Buffer::const_iterator(); // not really necessary, but for safety
}
示例#15
0
Component
Component::fromImplicitSha256Digest(const ConstBufferPtr& digest)
{
    if (digest->size() != crypto::SHA256_DIGEST_SIZE)
        BOOST_THROW_EXCEPTION(Error("Cannot create ImplicitSha256DigestComponent (input digest must be " +
                                    to_string(crypto::SHA256_DIGEST_SIZE) + " octets)"));

    return Block(tlv::ImplicitSha256DigestComponent, digest);
}
示例#16
0
	void Serializer::Serialize (const string &name, const ConstBufferPtr &data)
	{
		SerializeString (name);

		uint64 size = data.Size();
		Serialize (size);

		DataStream->Write (data);
	}
示例#17
0
void
MulticastDiscovery::registerHubDiscoveryPrefix(const ConstBufferPtr& buffer)
{
  std::vector<uint64_t> multicastFaces;

  size_t offset = 0;
  while (offset < buffer->size()) {
    bool isOk = false;
    Block block;
    std::tie(isOk, block) = Block::fromBuffer(buffer, offset);
    if (!isOk) {
      std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl;
      break;
    }

    offset += block.size();

    nfd::FaceStatus faceStatus(block);

    ndn::util::FaceUri uri(faceStatus.getRemoteUri());
    if (uri.getScheme() == "udp4") {
      namespace ip = boost::asio::ip;
      boost::system::error_code ec;
      ip::address address = ip::address::from_string(uri.getHost(), ec);

      if (!ec && address.is_multicast()) {
        multicastFaces.push_back(faceStatus.getFaceId());
      }
      else
        continue;
    }
  }

  if (multicastFaces.empty()) {
    m_nextStageOnFailure("No multicast faces available, skipping multicast discovery stage");
  }
  else {
    nfd::ControlParameters parameters;
    parameters
      .setName(LOCALHOP_HUB_DISCOVERY_PREFIX)
      .setCost(1)
      .setExpirationPeriod(time::seconds(30));

    nRequestedRegs = multicastFaces.size();
    nFinishedRegs = 0;

    for (const auto& face : multicastFaces) {
      parameters.setFaceId(face);
      m_controller.start<nfd::RibRegisterCommand>(parameters,
                                                  bind(&MulticastDiscovery::onRegisterSuccess,
                                                       this),
                                                  bind(&MulticastDiscovery::onRegisterFailure,
                                                       this, _1, _2));
    }
  }
}
示例#18
0
	shared_ptr <Buffer> FuseService::GetVolumeInfo ()
	{
		shared_ptr <Stream> stream (new MemoryStream);

		{
			ScopeLock lock (OpenVolumeInfoMutex);

			OpenVolumeInfo.Set (*MountedVolume);
			OpenVolumeInfo.SlotNumber = SlotNumber;

			OpenVolumeInfo.Serialize (stream);
		}

		ConstBufferPtr infoBuf = dynamic_cast <MemoryStream&> (*stream);
		shared_ptr <Buffer> outBuf (new Buffer (infoBuf.Size()));
		outBuf->CopyFrom (infoBuf);

		return outBuf;
	}
示例#19
0
	void Cipher::SetKey (const ConstBufferPtr &key)
	{
		if (key.Size() != GetKeySize ())
			throw ParameterIncorrect (SRC_POS);

		if (!Initialized)
			ScheduledKey.Allocate (GetScheduledKeySize ());

		SetCipherKey (key);
		Key.CopyFrom (key);
		Initialized = true;
	}
示例#20
0
std::tuple<bool, Block>
Block::fromBuffer(ConstBufferPtr buffer, size_t offset)
{
  Buffer::const_iterator tempBegin = buffer->begin() + offset;

  uint32_t type;
  bool isOk = tlv::readType(tempBegin, buffer->end(), type);
  if (!isOk)
    return std::make_tuple(false, Block());

  uint64_t length;
  isOk = tlv::readVarNumber(tempBegin, buffer->end(), length);
  if (!isOk)
    return std::make_tuple(false, Block());

  if (length > static_cast<uint64_t>(buffer->end() - tempBegin))
    return std::make_tuple(false, Block());

  return std::make_tuple(true, Block(buffer, type,
                                     buffer->begin() + offset, tempBegin + length,
                                     tempBegin, tempBegin + length));
}
示例#21
0
bool
Validator::verifySignature(const uint8_t* buf, const size_t size, const DigestSha256& sig)
{
  try {
    ConstBufferPtr buffer = crypto::computeSha256Digest(buf, size);
    const Block& sigValue = sig.getValue();

    if (buffer != nullptr &&
        buffer->size() == sigValue.value_size() &&
        buffer->size() == crypto::SHA256_DIGEST_SIZE) {
      const uint8_t* p1 = buffer->buf();
      const uint8_t* p2 = sigValue.value();

      return 0 == memcmp(p1, p2, crypto::SHA256_DIGEST_SIZE);
    }
    else
      return false;
  }
  catch (const CryptoPP::Exception& e) {
    return false;
  }
}
	void RandomPoolEnrichmentDialog::ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer)
	{
		wxString str;

		for (size_t i = 0; i < buffer.Size(); ++i)
		{
			str += wxString::Format (L"%02X", buffer[i]);
		}

		str += L"..";

		textCtrl->SetLabel (str.c_str());

		for (size_t i = 0; i < str.size(); ++i)
		{
			str[i] = L'X';
		}
	}
	void KeyfileGeneratorDialog::ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer, bool appendDots)
	{
		wxString str;

		for (size_t i = 0; i < buffer.Size(); ++i)
		{
			str += wxString::Format (L"%02X", buffer[i]);
		}

		if (appendDots)
			str += L"..";

		textCtrl->SetLabel (str.c_str());

		for (size_t i = 0; i < str.size(); ++i)
		{
			str[i] = L'X';
		}
	}
	void VolumeCreationProgressWizardPage::ShowBytes (wxStaticText *textCtrl, const ConstBufferPtr &buffer, bool appendDots)
	{
		wxString str;

		for (size_t i = 0; i < MaxDisplayedKeyBytes && i < buffer.Size(); ++i)
		{
			str += wxString::Format (L"%02X", buffer[i]);
		}

		if (appendDots)
			str += L"..";

		textCtrl->SetLabel (str.c_str());

		for (size_t i = 0; i < str.size(); ++i)
		{
			str[i] = L'X';
		}
	}
示例#25
0
文件: Hash.cpp 项目: AB9IL/VeraCrypt
	void Ripemd160::ProcessData (const ConstBufferPtr &data)
	{
		if_debug (ValidateDataParameters (data));
		RMD160Update ((RMD160_CTX *) Context.Ptr(), data.Get(), (int) data.Size());
	}
示例#26
0
	bool VolumeHeader::Deserialize (const ConstBufferPtr &header, shared_ptr <EncryptionAlgorithm> &ea, shared_ptr <EncryptionMode> &mode, bool truecryptMode)
	{
		if (header.Size() != EncryptedHeaderDataSize)
			throw ParameterIncorrect (SRC_POS);

		if (truecryptMode && (header[0] != 'T' ||
			header[1] != 'R' ||
			header[2] != 'U' ||
			header[3] != 'E'))
			return false;

		if (!truecryptMode && (header[0] != 'V' ||
			header[1] != 'E' ||
			header[2] != 'R' ||
			header[3] != 'A'))
			return false;

		size_t offset = 4;
		HeaderVersion =	DeserializeEntry <uint16> (header, offset);

		if (HeaderVersion < MinAllowedHeaderVersion)
			return false;

		if (HeaderVersion > CurrentHeaderVersion)
			throw HigherVersionRequired (SRC_POS);

		if (HeaderVersion >= 4
			&& Crc32::ProcessBuffer (header.GetRange (0, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC))
			!= DeserializeEntryAt <uint32> (header, TC_HEADER_OFFSET_HEADER_CRC - TC_HEADER_OFFSET_MAGIC))
		{
			return false;
		}

		RequiredMinProgramVersion = DeserializeEntry <uint16> (header, offset);
		
		if (!truecryptMode && (RequiredMinProgramVersion > Version::Number()))
			throw HigherVersionRequired (SRC_POS);

		if (truecryptMode)
		{
			if (RequiredMinProgramVersion < 0x600 || RequiredMinProgramVersion > 0x71a)
				throw UnsupportedTrueCryptFormat (SRC_POS);
			RequiredMinProgramVersion = CurrentRequiredMinProgramVersion;
		}

		VolumeKeyAreaCrc32 = DeserializeEntry <uint32> (header, offset);
		VolumeCreationTime = DeserializeEntry <uint64> (header, offset);
		HeaderCreationTime = DeserializeEntry <uint64> (header, offset);
		HiddenVolumeDataSize = DeserializeEntry <uint64> (header, offset);
		mVolumeType = (HiddenVolumeDataSize != 0 ? VolumeType::Hidden : VolumeType::Normal);
		VolumeDataSize = DeserializeEntry <uint64> (header, offset);
		EncryptedAreaStart = DeserializeEntry <uint64> (header, offset);
		EncryptedAreaLength = DeserializeEntry <uint64> (header, offset);
		Flags = DeserializeEntry <uint32> (header, offset);

		SectorSize = DeserializeEntry <uint32> (header, offset);
		if (HeaderVersion < 5)
			SectorSize = TC_SECTOR_SIZE_LEGACY;

		if (SectorSize < TC_MIN_VOLUME_SECTOR_SIZE
			|| SectorSize > TC_MAX_VOLUME_SECTOR_SIZE
			|| SectorSize % ENCRYPTION_DATA_UNIT_SIZE != 0)
		{
			throw ParameterIncorrect (SRC_POS);
		}

#if !(defined (TC_WINDOWS) || defined (TC_LINUX) || defined (TC_MACOSX))
		if (SectorSize != TC_SECTOR_SIZE_LEGACY)
			throw UnsupportedSectorSize (SRC_POS);
#endif

		offset = DataAreaKeyOffset;

		if (VolumeKeyAreaCrc32 != Crc32::ProcessBuffer (header.GetRange (offset, DataKeyAreaMaxSize)))
			return false;

		DataAreaKey.CopyFrom (header.GetRange (offset, DataKeyAreaMaxSize));
		
		ea = ea->GetNew();
		mode = mode->GetNew();
		
		if (typeid (*mode) == typeid (EncryptionModeXTS))
		{
			ea->SetKey (header.GetRange (offset, ea->GetKeySize()));
			mode->SetKey (header.GetRange (offset + ea->GetKeySize(), ea->GetKeySize()));
		}
		else
		{
			mode->SetKey (header.GetRange (offset, mode->GetKeySize()));
			ea->SetKey (header.GetRange (offset + LegacyEncryptionModeKeyAreaSize, ea->GetKeySize()));
		}

		ea->SetMode (mode);

		return true;
	}
示例#27
0
文件: Hash.cpp 项目: AB9IL/VeraCrypt
	void Whirlpool::ProcessData (const ConstBufferPtr &data)
	{
		if_debug (ValidateDataParameters (data));
		WHIRLPOOL_add (data.Get(), (int) data.Size() * 8, (WHIRLPOOL_CTX *) Context.Ptr());
	}
    void
    afterFetchedFaceStatusInformation(const shared_ptr<OBufferStream>& buffer, const Name& remoteName)
    {
        ConstBufferPtr buf = buffer->buf();

        Block block;
        size_t offset = 0;

        std::string currentTime;
        std::tm ctime;
        std::stringstream realEpochTime;
        ndn::time::system_clock::TimePoint realCurrentTime = ndn::time::system_clock::now();
        std::string currentTimeStr = ndn::time::toString(realCurrentTime, "%Y-%m-%dT%H:%M:%S%F");

        strptime(currentTimeStr.c_str(), "%FT%T%Z", &ctime);
        std::string stime(currentTimeStr);
        std::time_t realEpochSeconds = std::mktime(&ctime);
        std::size_t pos = stime.find(".");
        std::string realEpochMilli = stime.substr(pos+1);
        realEpochTime << realEpochSeconds << "." << realEpochMilli;

        CollectorData content;

        currentTime =  realEpochTime.str();

        while (offset < buf->size())
        {
            bool ok = Block::fromBuffer(buf, offset, block);
            if (!ok)
            {
                std::cerr << "ERROR: cannot decode FaceStatus TLV" << std::endl;
                break;
            }

            offset += block.size();

            nfd::FaceStatus faceStatus(block);

            // take only udp4 and tcp4 faces at the moment
            std::string remoteUri = faceStatus.getRemoteUri();
            if(remoteUri.compare(0,4,"tcp4") != 0 &&
                    remoteUri.compare(0,4,"udp4") != 0)
                continue;

            // take the ip from uri (remove tcp4:// and everything after ':'
            std::size_t strPos = remoteUri.find_last_of(":");
            std::string remoteIp = remoteUri.substr(7,strPos - 7);

            std::unordered_set<std::string>::const_iterator got = m_remoteLinks.find(remoteIp);
            // the link is not requested by the server
            if(got == m_remoteLinks.end())
                continue;

            FaceStatus linkStatus;
            linkStatus.setTx(faceStatus.getNOutBytes());
            linkStatus.setRx(faceStatus.getNInBytes());
            linkStatus.setFaceId(faceStatus.getFaceId());
            linkStatus.setLinkIp(remoteIp);
            linkStatus.setTimestamp(currentTime);

            // remove the remoteIP from the list of links to search and add it to the data packet
            m_remoteLinks.erase(remoteIp);
            content.add(linkStatus);

            if (DEBUG)
                std::cout << "about to send back " << linkStatus.getFaceId() << ": " << linkStatus.getRx() << ", " << linkStatus.getTx() << ", " << linkStatus.getLinkIp() << std::endl;
        }

        if (content.size() != 0)
        {
            ndn::shared_ptr<ndn::Data> data = ndn::make_shared<ndn::Data>(remoteName);
            data->setContent(content.wireEncode());
            data->setFreshnessPeriod(time::seconds(0));

            m_keyChain.sign(*data);
            m_face.put(*data);
        }
    }
示例#29
0
文件: Hash.cpp 项目: AB9IL/VeraCrypt
	void Hash::ValidateDataParameters (const ConstBufferPtr &data) const
	{
		if (data.Size() < 1)
			throw ParameterIncorrect (SRC_POS);
	}
示例#30
0
文件: Hash.cpp 项目: AB9IL/VeraCrypt
	void Sha256::ProcessData (const ConstBufferPtr &data)
	{
		if_debug (ValidateDataParameters (data));
		sha256_hash (data.Get(), (int) data.Size(), (sha256_ctx *) Context.Ptr());
	}