Example #1
0
void MatrixServerTable<T>::ProcessGet(const std::vector<Blob>& data,
  std::vector<Blob>* result) {
  CHECK(data.size() == 1);
  CHECK_NOTNULL(result);

  result->push_back(data[0]); // also push the key

  size_t keys_size = data[0].size<integer_t>();
  integer_t* keys = reinterpret_cast<integer_t*>(data[0].data());

  //get all rows
  if (keys_size == 1 && keys[0] == -1){
    Blob value(sizeof(T) * storage_.size());
    T* pvalues = reinterpret_cast<T*>(value.data());
    updater_->Access(storage_.size(), storage_.data(), pvalues);
    result->push_back(value);
    result->push_back(Blob(&server_id_, sizeof(int)));
    Log::Debug("[ProcessGet] Server = %d, getting rows offset = %d, #rows = %d\n",
      server_id_, row_offset_, storage_.size() / num_col_);
    return;
  }

  integer_t row_size = sizeof(T)* num_col_;
  result->push_back(Blob(keys_size * row_size));
  T* vals = reinterpret_cast<T*>((*result)[1].data());
  integer_t offset_v = 0;
  for (auto i = 0; i < keys_size; ++i) {
    integer_t offset_s = (keys[i] - row_offset_) * num_col_;
    updater_->Access(num_col_, storage_.data(), vals + offset_v, offset_s);
    offset_v += num_col_;
    Log::Debug("[ProcessAdd] Server = %d, getting #row = %d\n",
      server_id_, keys[i]);
  }
}
Example #2
0
bool BdbReader::Read(Blob& key, Blob& value) {
LAB_AGAIN:
	while (true) {
		if (m_idx < 0)
			return false;
		if (m_idx < m_entries)
			break;
		if (!LoadNextPage(m_pgno+1))
			return false;
	}
	int keyIdx = *((UInt16*)(m_curPage.data()+26)+m_idx*2),
		valIdx = *((UInt16*)(m_curPage.data()+26)+m_idx*2+1);
	if (keyIdx+3 > m_curPage.Size || valIdx+3 > m_curPage.Size) {
		m_idx = m_entries;
		goto LAB_AGAIN;
	}
	++m_idx;
	int keyLen = *(UInt16*)(m_curPage.data()+keyIdx),
		valLen = *(UInt16*)(m_curPage.data()+valIdx);
	if (keyIdx+keyLen > m_curPage.Size || valIdx+valLen > m_curPage.Size) {
		m_idx = m_entries;
		goto LAB_AGAIN;
	}
	if (*(m_curPage.data()+keyIdx+2) != 1 || *(m_curPage.data()+valIdx+2) != 1)
		goto LAB_AGAIN;
	key = Blob(m_curPage.data()+keyIdx+3, keyLen);
	value = Blob(m_curPage.data()+valIdx+3, valLen);
	return true;
}
Example #3
0
Blob Object::toBlob() const
{
	if(isBlob())
		return Blob(*this);
	else
		return Blob();
}
void 
Sha256WithRsaSignature::set(const struct ndn_Signature& signatureStruct)
{
  digestAlgorithm_ = Blob(signatureStruct.digestAlgorithm);
  witness_ = Blob(signatureStruct.witness);
  signature_ = Blob(signatureStruct.signature);
  publisherPublicKeyDigest_.set(signatureStruct.publisherPublicKeyDigest);
  keyLocator_.set(signatureStruct.keyLocator);
}
Example #5
0
Blob IPAddress::GetAddressBytes() const {
	int size = FamilySize(AddressFamily);
	if (!size)
		Throw(ExtErr::UnknownHostAddressType);
	switch ((int)get_AddressFamily()) {
	case AF_INET:
		return Blob(&m_sin.sin_addr, 4);
	case AF_INET6:
		return Blob(&m_sin6.sin6_addr, 16);
	default:
		Throw(ExtErr::UnknownHostAddressType);
	}
}
Example #6
0
Blob Sec256Signature::Serialize() const {
	uint8_t buf[100];
	size_t size = sizeof buf;
	if (!secp256k1_ecdsa_sig_serialize(buf, &size, &m_r, &m_s))
		Throw(errc::invalid_argument);
	return Blob(buf, size);
}
Example #7
0
Blob Sec256Dsa::PrivKeyToDER(RCSpan privKey, bool bCompressed) {
	ASSERT(privKey.size() == 32);
	uint8_t ar[279];
	size_t privkeylen = sizeof ar;
	Sec256Check(::ec_privkey_export_der(g_sec256Ctx, ar, &privkeylen, privKey.data(), bCompressed));
	return Blob(ar, privkeylen);
}
Example #8
0
    /** We got some data for a ledger we are no longer acquiring
        Since we paid the price to receive it, we might as well stash it in case we need it.
        Nodes are received in wire format and must be stashed/hashed in prefix format
    */
    void gotStaleData (std::shared_ptr<protocol::TMLedgerData> packet_ptr)
    {
        const uint256 uZero;
        Serializer s;
        try
        {
            for (int i = 0; i < packet_ptr->nodes ().size (); ++i)
            {
                auto const& node = packet_ptr->nodes (i);

                if (!node.has_nodeid () || !node.has_nodedata ())
                    return;

                auto newNode = SHAMapAbstractNode::make(
                    Blob (node.nodedata().begin(), node.nodedata().end()),
                    0, snfWIRE, uZero, false);

                if (!newNode)
                    return;

                s.erase();
                newNode->addRaw(s, snfPREFIX);

                auto blob = std::make_shared<Blob> (s.begin(), s.end());

                getApp().getOPs().addFetchPack (newNode->getNodeHash(), blob);
            }
        }
        catch (...)
        {
        }
    }
Example #9
0
void
CommandInterestGenerator::generate
  (Interest& interest, KeyChain& keyChain, const Name& certificateName,
   WireFormat& wireFormat)
{
  MillisecondsSince1970 timestamp = ::round(ndn_getNowMilliseconds());
  while (timestamp <= lastTimestamp_)
    timestamp += 1.0;

  // The timestamp is encoded as a TLV nonNegativeInteger.
  TlvEncoder encoder(8);
  encoder.writeNonNegativeInteger((uint64_t)timestamp);
  interest.getName().append(Blob(encoder.finish()));

  // The random value is a TLV nonNegativeInteger too, but we know it is 8 bytes,
  //   so we don't need to call the nonNegativeInteger encoder.
  uint8_t randomBuffer[8];
  ndn_Error error;
  if ((error = CryptoLite::generateRandomBytes(randomBuffer, sizeof(randomBuffer))))
    throw runtime_error(ndn_getErrorString(error));
  interest.getName().append(randomBuffer, sizeof(randomBuffer));

  keyChain.sign(interest, certificateName, wireFormat);

  if (interest.getInterestLifetimeMilliseconds() < 0)
    // The caller has not set the interest lifetime, so set it here.
    interest.setInterestLifetimeMilliseconds(1000.0);

  // We successfully signed the interest, so update the timestamp.
  lastTimestamp_ = timestamp;
}
Example #10
0
Blob
RsaAlgorithm::encrypt
  (const Blob& keyBits, const Blob& plainData, const EncryptParams& params)
{
  RsaPublicKeyLite publicKey;
  if (publicKey.decode(keyBits) != NDN_ERROR_success)
    throw UnrecognizedKeyFormatException
      ("RsaAlgorithm: Error decoding public key");

  // TODO: use RSA_size, etc. to get the proper size of the output buffer.
  ptr_lib::shared_ptr<vector<uint8_t> > encryptedData(new vector<uint8_t>(1000));
  size_t encryptedDataLength;
  ndn_Error error;
  if ((error = publicKey.encrypt
       (plainData, params.getAlgorithmType(), &encryptedData->front(),
        encryptedDataLength))) {
    if (error == NDN_ERROR_Unsupported_algorithm_type)
      throw runtime_error("RsaAlgorithm: Unsupported padding scheme");
    else
      throw SecurityException(string("RsaAlgorithm: ") + ndn_getErrorString(error));
  }

  encryptedData->resize(encryptedDataLength);
  return Blob(encryptedData, false);
}
Example #11
0
void
Encryptor::encryptData
  (Data& data, const Blob& payload, const Name& keyName, const Blob& key,
   const EncryptParams& params)
{
  data.getName().append(getNAME_COMPONENT_FOR()).append(keyName);

  ndn_EncryptAlgorithmType algorithmType = params.getAlgorithmType();

  if (algorithmType == ndn_EncryptAlgorithmType_AesCbc ||
      algorithmType == ndn_EncryptAlgorithmType_AesEcb) {
    EncryptedContent content = encryptSymmetric(payload, key, keyName, params);
    data.setContent(content.wireEncode(*TlvWireFormat::get()));
  }
  else if (algorithmType == ndn_EncryptAlgorithmType_RsaPkcs ||
           algorithmType == ndn_EncryptAlgorithmType_RsaOaep) {
    // Openssl doesn't have an easy way to get the maximum plain text size, so
    // try to encrypt the payload first and catch the error if it is too big.
    try {
      EncryptedContent content = encryptAsymmetric(payload, key, keyName, params);
      data.setContent(content.wireEncode(*TlvWireFormat::get()));
      return;
    } catch (SecurityException&) {
      // The payload is larger than the maximum plaintext size. Continue.
    }

    // 128-bit nonce.
    ptr_lib::shared_ptr<vector<uint8_t> > nonceKeyBuffer(new vector<uint8_t>(16));
    ndn_Error error;
    if ((error = CryptoLite::generateRandomBytes
         (&nonceKeyBuffer->front(), nonceKeyBuffer->size())))
      throw runtime_error(ndn_getErrorString(error));
    Blob nonceKey(nonceKeyBuffer, false);

    Name nonceKeyName(keyName);
    nonceKeyName.append("nonce");

    EncryptParams symmetricParams
      (ndn_EncryptAlgorithmType_AesCbc, AesAlgorithm::BLOCK_SIZE);

    EncryptedContent nonceContent = encryptSymmetric
      (payload, nonceKey, nonceKeyName, symmetricParams);

    EncryptedContent payloadContent = encryptAsymmetric
      (nonceKey, key, keyName, params);

    Blob nonceContentEncoding = nonceContent.wireEncode();
    Blob payloadContentEncoding = payloadContent.wireEncode();
    ptr_lib::shared_ptr<vector<uint8_t> > content(new vector<uint8_t>
      (nonceContentEncoding.size() + payloadContentEncoding.size()));
    ndn_memcpy(&content->front(), payloadContentEncoding.buf(),
               payloadContentEncoding.size());
    ndn_memcpy(&content->front() + payloadContentEncoding.size(),
               nonceContentEncoding.buf(), nonceContentEncoding.size());

    data.setContent(Blob(content, false));
  }
  else
    throw runtime_error("Unsupported encryption method");
}
Example #12
0
Blob ConvertFromBase58(RCString s, bool bCheckHash) {
	BigInteger bi = 0;
	for (const char *p=s; *p; ++p) {
		if (const char *q = strchr(s_pszBase58, *p)) {
			bi = bi*58 + BigInteger(q-s_pszBase58);
		} else
			Throw(errc::invalid_argument);
	}
	vector<byte> v((bi.Length+7)/8);
	bi.ToBytes(&v[0], v.size());
	if (v.size()>=2 && v.end()[-1]==0 && v.end()[-1]>=0x80)
		v.resize(v.size()-1);
	vector<byte> r;
	for (const char *p=s; *p==s_pszBase58[0]; ++p)
		r.push_back(0);
	r.resize(r.size()+v.size());
	std::reverse_copy(v.begin(), v.end(), r.end()-v.size());
	if (r.size() < 4)
		Throw(E_FAIL);
	if (bCheckHash) {
		HashValue hash = HasherEng::GetCurrent()->HashForAddress(ConstBuf(&r[0], r.size()-4));
		if (memcmp(hash.data(), &r.end()[-4], 4))
			Throw(HRESULT_FROM_WIN32(ERROR_CRC));
	}
	return Blob(&r[0], r.size()-4);
}
Example #13
0
Blob ConvertFromBase58ShaSquare(RCString s) {
	BigInteger bi = 0;
	for (const char *p=s; *p; ++p) {
		if (const char *q = strchr(s_pszBase58, *p)) {
			bi = bi*58 + BigInteger(q-s_pszBase58);
		} else
			Throw(E_INVALIDARG);
	}
	vector<byte> v((bi.Length+7)/8);
	bi.ToBytes(&v[0], v.size());
	if (v.size()>=2 && v.end()[-1]==0 && v.end()[-1]>=0x80)
		v.resize(v.size()-1);
	vector<byte> r;
	for (const char *p=s; *p==s_pszBase58[0]; ++p)
		r.push_back(0);
	r.resize(r.size()+v.size());
	std::reverse_copy(v.begin(), v.end(), r.end()-v.size());
	if (r.size() < 4)
		Throw(E_FAIL);
	SHA256 sha;
	HashValue hash = HashValue(sha.ComputeHash(sha.ComputeHash(ConstBuf(&r[0], r.size()-4))));
	if (memcmp(hash.data(), &r.end()[-4], 4))
		Throw(HRESULT_FROM_WIN32(ERROR_CRC));
	return Blob(&r[0], r.size()-4);
}
Example #14
0
SecurityDescriptor::SecurityDescriptor(RCString s) {
	PSECURITY_DESCRIPTOR pSD;
	ULONG size;
	Win32Check(::ConvertStringSecurityDescriptorToSecurityDescriptor(s, SDDL_REVISION_1, &pSD, &size));
	m_blob = Blob(pSD, size);
	Win32Check(!::LocalFree(pSD));
}
Example #15
0
void Zoo::RegisterNode() {
  MessagePtr msg(new Message());
  msg->set_src(rank());
  msg->set_dst(kController);
  msg->set_type(MsgType::Control_Register);
  msg->Push(Blob(&nodes_[rank()], sizeof(Node)));
  SendTo(actor::kCommunicator, msg);

  // waif for reply
  mailbox_->Pop(msg);
  CHECK(msg->type() == MsgType::Control_Reply_Register);
  CHECK(msg->data().size() == 2);
  Blob info_blob = msg->data()[0];
  Blob count_blob = msg->data()[1];
  num_workers_ = count_blob.As<int>(0);
  num_servers_ = count_blob.As<int>(1);
  worker_id_to_rank_.resize(num_workers_);
  server_id_to_rank_.resize(num_servers_);
  CHECK(info_blob.size() == size() * sizeof(Node));
  memcpy(nodes_.data(), info_blob.data(), info_blob.size());
  for (auto node : nodes_) {
    if (node.worker_id != -1) {
      worker_id_to_rank_[node.worker_id] = node.rank;
    }
    if (node.server_id != -1) {
      server_id_to_rank_[node.server_id] = node.rank;
    }
  }
  Log::Debug("rank %d end register\n", Zoo::Get()->rank());
}
Example #16
0
 /**
  * Decode the input using a particular wire format and update this Data. If wireFormat is the default wire format, also
  * set the defaultWireEncoding field to a copy of the input. (To not copy the input, see wireDecode(Blob).)
  * @param input The input byte array to be decoded.
  * @param inputLength The length of input.
  * @param wireFormat A WireFormat object used to decode the input. If omitted, use WireFormat getDefaultWireFormat().
  */
 void
 wireDecode
   (const uint8_t* input, size_t inputLength,
    WireFormat& wireFormat = *WireFormat::getDefaultWireFormat())
 {
   wireDecode(Blob(input, inputLength), wireFormat);
 }
Example #17
0
void BlobDetector::detect()
{

    double sigmaFirst = data->getSigmaFirst();
    double sigmaStep = data->getSigmaStep();
    for (int oID = 0; oID < data->octavs.size(); oID++)
    {
        //data->octavs[oID]->genDOG();
        double sigma = sigmaFirst*(1<<oID);
        double littlesigma = 1;

        for (int layerID = 1; layerID < data->octavs[oID]->dogs.size()-1; layerID++)
        {
            unique_ptr<HarrisDetector> harrisDetector = make_unique<HarrisDetector>(data->octavs[oID]->layers[layerID].get());
            harrisDetector->configure(0.01,0.06,1);
            ImageMap* img =  data->octavs[oID]->dogs[layerID].get();
            for (int x=0;x<img->getWidth();x++)
            {
                for (int y=0;y<img->getHeight();y++)
                {
                    bool isMax = true;
                    bool isMin = true;
                    double val = img->getData(x,y);//* sigma;
                    if(val<0.031 && val>-0.031) continue;
                    //double ds =  sigma/sigmaStep;
                    //int dl = layerID;
                    for (int dl = layerID-1; dl <= layerID+1; dl++)
                    {
                        ImageMap* img1 =  data->octavs[oID]->dogs[dl].get();
                        for(int dx = x-1; dx <= x+1; dx++)
                        {
                            for(int dy = y-1; dy <= y+1; dy++)
                            {
                                double val1 = img1->getData(dx,dy);//*ds;
                                if (dx != x || dy != y || dl != layerID)
                                {
                                    isMax &= (val1 < val);
                                    isMin &= (val1 > val);
                                }

                            }
                        }
                      //  ds*=sigmaStep;
                    }
                    if (isMax || isMin)
                    {
                        Blob b = Blob(x,y,sigma,val);
                        b.scale = (oID);
                        data->blobs.push_back(b);
                        data->blobs[data->blobs.size()-1].isClone = false;
                        data->descriptors.push_back(harrisDetector->calcDescriptor(littlesigma,&(data->blobs[data->blobs.size()-1])));
                    }
               }
          }
            littlesigma*=sigmaStep;
            sigma*=sigmaStep;
       }
    }
}
Example #18
0
UTF8 JSON::generate(Error& error) const
{
	Buffer buf(0);
	HOutputStream out = NewObject(MemoryOutputStream, buf);
	generate(error, out);
	out->twrite(error,'\0');
	return UTF8(Blob(buf));
}
Example #19
0
Blobs::Blobs(int howMany) {
	total = howMany;
	blobs = (Blob*)malloc(sizeof(Blob) * howMany);
	for (int i = 0; i < howMany; i++) {
		blobs[i] = Blob();
	}
	init();
}
Example #20
0
int main(
    int argc,
    char **argv)
{
    OPEN_LOG("check_signature", LOG_USER);
    if (argc != 3)
        FATAL(MSG_USAGE);
    struct Certificate locert,
        hicert;
    struct CertificateRevocationList crl;
    Certificate(&locert, (ushort) 0);
    Certificate(&hicert, (ushort) 0);
    CertificateRevocationList(&crl, (ushort) 0);
    struct Blob blob;
    Blob(&blob, (ushort) 0);
    struct casn *tbsp,
       *sigp;
    struct AlgorithmIdentifier *algp;
    char *sfx = strchr(argv[1], (int)'.');
    int ansr;
    if (!strcmp(sfx, ".cer"))
    {
        tbsp = &locert.toBeSigned.self;
        algp = &locert.algorithm;
        sigp = &locert.signature;
        ansr = get_casn_file(&locert.self, argv[1], 0);
    }
    else if (!strcmp(sfx, ".crl"))
    {
        tbsp = &crl.toBeSigned.self;
        algp = &crl.algorithm;
        sigp = &crl.signature;
        ansr = get_casn_file(&crl.self, argv[1], 0);
    }
    else if (!strcmp(sfx, ".blb"))
    {
        tbsp = &blob.toBeSigned;
        algp = &blob.algorithm;
        sigp = &blob.signature;
        ansr = get_casn_file(&blob.self, argv[1], 0);
    }
    else
        FATAL(MSG_TYPE, argv[1]);
    if (ansr < 0)
        FATAL(MSG_GET, argv[1]);
    if (get_casn_file(&hicert.self, argv[2], 0) < 0)
        FATAL(MSG_GET, argv[2]);
    if (diff_objid(&algp->algorithm, id_sha_256WithRSAEncryption))
    {
        char oidbuf[80];
        read_objid(&algp->algorithm, oidbuf);
        FATAL(MSG_ALG, oidbuf);
    }
    if (!check_signature(tbsp, &hicert, sigp))
        fprintf(stderr, "Signature failed\n");
    fprintf(stderr, "Signature succeeded\n");
    return 0;
}
Example #21
0
Blob
TpmKeyHandleMemory::doSign
  (DigestAlgorithm digestAlgorithm, const uint8_t* data, size_t dataLength) const
{
  if (digestAlgorithm == DIGEST_ALGORITHM_SHA256)
    return key_->sign(data, dataLength, digestAlgorithm);
  else
    return Blob();
}
void
DigestSha256Signature::set(const struct ndn_Signature& signatureStruct)
{
  // The caller should already have checked the type, but check again.
  if (signatureStruct.type != ndn_SignatureType_DigestSha256Signature)
    throw runtime_error("signatureStruct is not the expected type DigestSha256Signature");

  setSignature(Blob(signatureStruct.signature));
}
Example #23
0
Blob Sec256Dsa::DecompressPubKey(RCSpan cbuf) {
	uint8_t buf[65];
	size_t pubkeylen = 65;

	secp256k1_ge Q;
	Sec256Check(::secp256k1_eckey_pubkey_parse(&Q, cbuf.data(), cbuf.size()) &&
				::secp256k1_eckey_pubkey_serialize(&Q, buf, &pubkeylen, false));
	return Blob(buf, pubkeylen);
}
Example #24
0
std::pair<Blob, bool> strUnHex (std::string const& strSrc)
{
    std::string strTmp;

    if (strUnHex (strTmp, strSrc) == -1)
        return std::make_pair (Blob (), false);

    return std::make_pair(strCopy (strTmp), true);
}
Example #25
0
/**
 * @internal
 * @brief Find the blobs in the received image.
 * What it looks for in an image is bright areas, so typically 
 * the image result of a background subtraction is a good input.
 * 
 * @param[in] inImage image where the blobs will be searched
 */
void BlobFinder::update( const Image& inImage )
{
	// Check valid
	if ( !isValid() )
	THROW_EXCEPTION( "Trying to compute blobs, with the BlobFinder not initialized. Init method should be called" );

	// Check blob area... and if it has not been set, set it to the max and min (no lower than 10, to avoid opencv issues)
	if ( (m_minBlobArea < 0) || (m_maxBlobArea < 0) )
	{
		m_minBlobArea = 10;
		m_maxBlobArea = (float)inImage.getWidth() * (float)inImage.getHeight();
	}

	// Check both images have same size and it is the same than the filter size
	if( (inImage.getNChannels() != 1) && (inImage.getNChannels() != 3) )
	THROW_EXCEPTION( "Trying to compute blobs on images with non supporte format -> only RGB or GRAYSCALE images supported" );

	// Request temp image to work with
	IplImage* cvTempImage = ImageResourceManager::getSingleton().getImage( inImage.getWidth(), inImage.getHeight(), 1 );

	// If they have different number of channels -> convert them
	if ( inImage.getNChannels() == 3 )
		cvConvertImage( &inImage.getCVImage(), cvTempImage );
	// just one channel -> Copy the input image
	else 
		cvCopy( &inImage.getCVImage(), cvTempImage );

	// Find blobs (openCV contours)	
	int retrivalMode = CV_RETR_EXTERNAL; // CV_RETR_CCOMP
	cvFindContours( cvTempImage, m_findContoursStorage, &m_contour, sizeof(CvContour), retrivalMode, CV_CHAIN_APPROX_SIMPLE );

	// Extract found contours    

	// Iterate through found contours and store them..
	m_blobs.clear();
	for( ; m_contour != 0; m_contour = m_contour->h_next )
	{
		// Get contour area
		double area = fabs( cvContourArea( m_contour, CV_WHOLE_SEQ ) );

		// If it has a good size (between min and max)
		if ( ( area > m_maxBlobArea ) || ( area < m_minBlobArea ) )
		  continue;

		// Store new Blob
		m_blobs.push_back( Blob( area, m_contour ) );
	}

	// Release temp image
	ImageResourceManager::getSingleton().releaseImage( cvTempImage );

	// Extract information of found blobs
	extractBlobsInformation();

	// Clear OpenCV contours storage 
	cvClearMemStorage( m_findContoursStorage );
}
Example #26
0
void
DigestSha256Signature::set(const SignatureLite& signatureLite)
{
  // The caller should already have checked the type, but check again.
  if (signatureLite.getType() != ndn_SignatureType_DigestSha256Signature)
    throw runtime_error("signatureLite is not the expected type DigestSha256Signature");

  setSignature(Blob(signatureLite.getSignature()));
}
Example #27
0
/*
- FUNCTION: GetNthBlob
- FUNCTIONALITY: Gets the n-th blob ordering first the blobs with some criteria
- PARAMETERS:
	- criteri: criteria to order the blob array
	- nBlob: index of the returned blob in the ordered blob array
	- dst: where to store the result
- RESULT:
- RESTRICTIONS:
- AUTHOR: Ricard Borr�s
- CREATION DATE: 25-05-2005.
- MODIFICATION: Date. Author. Description.
*/
void BlobResult::GetNthBlob( funcio_calculBlob *criteri, int nBlob, Blob &dst ) const
{
    // verifiquem que no estem accedint fora el vector de blobs
    if( nBlob < 0 || nBlob >= GetNumBlobs() )
    {
        //RaiseError( EXCEPTION_BLOB_OUT_OF_BOUNDS );
        dst = Blob();
        return;
    }

    double_stl_vector avaluacioBlobs, avaluacioBlobsOrdenat;
    double valorEnessim;

    //avaluem els blobs amb la funci� pertinent
    avaluacioBlobs = GetSTLResult(criteri);

    avaluacioBlobsOrdenat = double_stl_vector( GetNumBlobs() );

    // obtenim els nBlob primers resultats (en ordre descendent)
    std::partial_sort_copy( avaluacioBlobs.begin(),
                            avaluacioBlobs.end(),
                            avaluacioBlobsOrdenat.begin(),
                            avaluacioBlobsOrdenat.end(),
                            std::greater<double>() );

    valorEnessim = avaluacioBlobsOrdenat[nBlob];

    // busquem el primer blob que t� el valor n-ssim
    double_stl_vector::const_iterator itAvaluacio = avaluacioBlobs.begin();

    bool trobatBlob = false;
    int indexBlob = 0;
    while( itAvaluacio != avaluacioBlobs.end() && !trobatBlob )
    {
        if( *itAvaluacio == valorEnessim )
        {
            trobatBlob = true;
            dst = Blob( GetBlob(indexBlob));
        }
        itAvaluacio++;
        indexBlob++;
    }
}
Example #28
0
Blob Sec256Dsa::SignHash(RCSpan hash) {
	if (hash.size() != 32)
		Throw(errc::invalid_argument);
	secp256k1_ecdsa_signature sig;
	Sec256Check(::secp256k1_ecdsa_sign(g_sec256Ctx, &sig, hash.data(), m_privKey.constData(), secp256k1_nonce_function_rfc6979, nullptr));
	uint8_t buf[72];
	size_t nSiglen = sizeof buf;
	Sec256Check(::secp256k1_ecdsa_signature_serialize_der(g_sec256Ctx, buf, &nSiglen, &sig));
	return Blob(buf, nSiglen);
}
void
Sha256WithEcdsaSignature::set(const struct ndn_Signature& signatureStruct)
{
  // The caller should already have checked the type, but check again.
  if (signatureStruct.type != ndn_SignatureType_Sha256WithEcdsaSignature)
    throw runtime_error("signatureStruct is not the expected type Sha256WithEcdsaSignature");

  setSignature(Blob(signatureStruct.signature));
  keyLocator_.get().set(signatureStruct.keyLocator);
}
Example #30
0
Blob
MemoryIdentityStorage::getKey(const Name& keyName)
{
  map<string, ptr_lib::shared_ptr<KeyRecord> >::iterator record = keyStore_.find(keyName.toUri());
  if (record == keyStore_.end())
    // Not found.  Silently return null.
    return Blob();

  return record->second->getKeyDer();
}