Ejemplo n.º 1
0
void BlumGoldwasserPublicKey::DEREncode(BufferedTransformation &bt) const
{
	DERSequenceEncoder seq(bt);
	n.DEREncode(seq);
}
Ejemplo n.º 2
0
bool PubAddr::decodeFromObj(packet_pubkey pubkey)
{
	ustring data;
	try
	{
		data = this->decode(pubkey.encrypted, this->getTagE());
	}
	catch (...)
	{
		return false;
	}
	unsigned int p = 0;
	int bitfield = data.getInt32(p);
	ustring signingKey;
	signingKey += 0x04;
	signingKey += data.getUstring(64, p);
	ustring encryptionKey;
	encryptionKey += 0x04;
	encryptionKey += data.getUstring(64, p);
	int nonce_trials = (int)data.getVarInt_B(p);
	int extra_bytes = (int)data.getVarInt_B(p);
	int k = p;
	int sig_len = (int)data.getVarInt_B(p);
	ustring sign = data.getUstring(sig_len, p);


	//checking signature

	OID CURVE = secp256k1();
	AutoSeededRandomPool prng;

	ECPPoint point;
	unsigned int i = 1;
	string xA = signingKey.getString(32, i);
	string yA = signingKey.getString(32, i);

	point.identity = false;
	point.x.Decode((byte*)xA.c_str(), 32);
	point.y.Decode((byte*)yA.c_str(), 32);

	ECDSA<ECP, SHA1>::PublicKey publicKey;
	publicKey.Initialize(CURVE, point);

	bool res = publicKey.Validate(prng, 3);

	ECDSA<ECP, SHA1>::Verifier verifier(publicKey);

	// Result of the verification process
	bool result = false;

	ustring mess1;
	unsigned int j = 8;
	mess1.appendInt64(pubkey.message_payload.getInt64(j));
	mess1.appendInt32(pubkey.message_payload.getInt32(j));
	mess1.appendVarInt_B(pubkey.message_payload.getVarInt_B(j));
	mess1.appendVarInt_B(pubkey.message_payload.getVarInt_B(j));
	mess1 += this->getTag();
	string mess;

	mess += mess1.toString();
	j = 0;
	mess += data.getString(k, j);

	string tmp_sign = sign.toString();

	//BER decoding
	Integer r, s;
	StringStore store(tmp_sign);
	BERSequenceDecoder seq(store);
	r.BERDecode(seq);
	s.BERDecode(seq);
	seq.MessageEnd();
	string signature;
	StringSink sink(signature);
	r.Encode(sink, 32);
	s.Encode(sink, 32);
	//end conversion

	StringSource sss(signature + mess, true,
		new SignatureVerificationFilter(
			verifier,
			new ArraySink((byte*)&result, sizeof(result))
			) // SignatureVerificationFilter
		);

	if (result)
	{

		this->loadKeys(signingKey, encryptionKey, nonce_trials, extra_bytes);

		return true;
	}
	return false;
}
Ejemplo n.º 3
0
BlumGoldwasserPublicKey::BlumGoldwasserPublicKey(BufferedTransformation &bt)
{
	BERSequenceDecoder seq(bt);
	n.BERDecode(seq);
	modulusLen = n.ByteCount();
}
Ejemplo n.º 4
0
bool CsFetcher::saveSlot(Item* item, DBConn* conn)
{
//	usleep(1000000 * 3);
	CsItem* cItem = (CsItem*)item;
	CsParam p = cItem->getParam();
	QString sql = "";
	QSqlQuery q(conn->qtDatabase());

	int i = 0;
	if (p.id != 0)
	{
		sql =
			"UPDATE client_service"
				" SET"
					" client_id = ?"
					", date = ?"
					", summ = ?"
					", limit_value = ?"
					", limit_days = ?"
					", limit_type = ?"
					", name = ?"
					", vid_id = ?"
				" WHERE id = ?";
		q.prepare(sql);
		q.bindValue(i++, p.client_id);
		q.bindValue(i++, p.date);
		q.bindValue(i++, p.summ);
		q.bindValue(i++, p.limit_value);
		q.bindValue(i++, p.limit_days);
		q.bindValue(i++, p.limit_type);
		q.bindValue(i++, p.name);
		q.bindValue(i++, p.vid_id);
		q.bindValue(i++, p.id);
	}
	else
	{
		sql = "SELECT nextval('client_service_id_seq')";
		QSqlQuery seq(conn->qtDatabase());
		seq.exec(sql);
		if (seq.next())
		{
			qDebug() << "NEW ID = " << seq.value(0).toInt();
			p.id = seq.value(0).toInt();
			cItem->setParam(p);
		}
		sql =
			"INSERT INTO client_service("
					" id, client_id, date, summ, limit_value, limit_days, limit_type, name, vid_id)"
				" VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)";
		q.prepare(sql);
		q.bindValue(i++, p.id);
		q.bindValue(i++, p.client_id);
		q.bindValue(i++, p.date);
		q.bindValue(i++, p.summ);
		q.bindValue(i++, p.limit_value);
		q.bindValue(i++, p.limit_days);
		q.bindValue(i++, p.limit_type);
		q.bindValue(i++, p.name);
		q.bindValue(i++, p.vid_id);
	}

	return conn->executeQuery(q);
}
Ejemplo n.º 5
0
packet_pubkey Addr::encodePubKey()
{
	std::shared_lock<std::shared_timed_mutex> mlock(this->mutex_);
	packet_pubkey pubkey;
	time_t ltime = std::time(nullptr);

	this->lastPubKeyRequest = ltime;

	std::random_device rd;
	std::mt19937 engine(rd());
	std::uniform_int_distribution<int> distribution(-300, 300);
	int random = distribution(engine);

	time_t TTL = 4 * 24 * 60 * 60 + random; //4 days +- 5 min
	ltime = ltime + TTL;

	pubkey.objectType = 1;
	pubkey.Time = ltime;
	pubkey.stream = this->getStream();
	pubkey.version = 4;

	pubkey.encodePayload();

	ustring plain;


	OID CURVE = secp256k1();
	AutoSeededRandomPool rng;

	ECDH < ECP >::Domain dhA(CURVE);
	//generating ephemeral key pair
	SecByteBlock privA(dhA.PrivateKeyLength()), pubA(dhA.PublicKeyLength());

	dhA.GenerateKeyPair(rng, privA, pubA);

	ustring pubEKey;
	pubEKey.append(pubA.data(), pubA.size());

	ustring privEKey;
	privEKey.append(privA.data(), privA.size());

	plain.appendInt32(1); //bitfiled 1 not yet integrated
	plain.append(this->pubSigningKey.c_str() + 1, 64);
	plain.append(this->pubEncryptionKey.c_str() + 1, 64);
	plain.appendVarInt_B(this->nonce_trials);
	plain.appendVarInt_B(this->extra_bytes);


	AutoSeededRandomPool prng;

	ECDSA<ECP, SHA1>::PrivateKey privateKey;

	Integer x;
	x.Decode(this->getPrivSigningKey().c_str(), this->getPrivSigningKey().size());
	privateKey.Initialize(CURVE, x);

	ECDSA<ECP, SHA1>::Signer signer(privateKey);

	string signature;
	string mess;
	ustring mess1;
	unsigned int i = 8;
	mess1.appendInt64(pubkey.message_payload.getInt64(i));
	mess1.appendInt32(pubkey.message_payload.getInt32(i));
	mess1.appendVarInt_B(pubkey.message_payload.getVarInt_B(i));
	mess1.appendVarInt_B(pubkey.message_payload.getVarInt_B(i));
	mess1 += this->getTag();

	mess += mess1.toString();
	mess += plain.toString();

	StringSource ss(mess, true /*pump all*/,
		new SignerFilter(prng,
			signer,
			new StringSink(signature)
			) // SignerFilter
		); // StringSource

		   //DER encoding
	Integer r, s;
	StringStore store(signature);
	r.Decode(store, signature.size() / 2);
	s.Decode(store, signature.size() / 2);
	string sign;
	StringSink sink(sign);
	DERSequenceEncoder seq(sink);
	r.DEREncode(seq);
	s.DEREncode(seq);
	seq.MessageEnd();
	//end conversion

	plain.appendVarInt_B(sign.size());
	plain.append((unsigned char*)sign.c_str(), sign.size());

	ECIES<ECP>::PrivateKey priv;
	ustring pubK = this->getPubOfPriv(this->getTagE());
	//Integer e;
	//e.Decode(this->getTagE().c_str(), 32);
	//priv.Initialize(CURVE, e);
	//ECIES<ECP>::PublicKey pub;
	//priv.MakePublicKey(pub);
	//const ECP::Point& qq = pub.GetPublicElement();
	//string pubS;
	//StringSink sinkK(pubS);
	//qq.x.Encode(sinkK, 32);
	//qq.y.Encode(sinkK, 32);

	//ustring pubK;
	//pubK += 0x04;
	//pubK.fromString(pubS);

	ustring encoded = this->encode(pubK, privEKey, pubEKey, plain);
	pubkey.tag = this->getTag();
	pubkey.encrypted = encoded;

	pubkey.encodeObject();
	return pubkey;
}
Ejemplo n.º 6
0
// 4.2.1.12. Extended Key Usage (id-ce-extKeyUsage)
// 4.2.1.12. Extended Key Usage (id-ce-extKeyUsage)
Result
CheckExtendedKeyUsage(EndEntityOrCA endEntityOrCA, const SECItem* encodedEKUs,
                      SECOidTag requiredEKU)
{
  // TODO: Either do not allow anyExtendedKeyUsage to be passed as requiredEKU,
  // or require that callers pass anyExtendedKeyUsage instead of
  // SEC_OID_UNKNWON and disallow SEC_OID_UNKNWON.

  // XXX: We're using SEC_ERROR_INADEQUATE_CERT_TYPE here so that callers can
  // distinguish EKU mismatch from KU mismatch from basic constraints mismatch.
  // We should probably add a new error code that is more clear for this type
  // of problem.

  bool foundOCSPSigning = false;

  if (encodedEKUs) {
    ScopedPtr<CERTOidSequence, CERT_DestroyOidSequence>
      seq(CERT_DecodeOidSequence(encodedEKUs));
    if (!seq) {
      PR_SetError(SEC_ERROR_INADEQUATE_CERT_TYPE, 0);
      return RecoverableError;
    }

    bool found = false;

    // XXX: We allow duplicate entries.
    for (const SECItem* const* oids = seq->oids; oids && *oids; ++oids) {
      SECOidTag oidTag = SECOID_FindOIDTag(*oids);
      if (requiredEKU != SEC_OID_UNKNOWN && oidTag == requiredEKU) {
        found = true;
      }
      if (oidTag == SEC_OID_OCSP_RESPONDER) {
        foundOCSPSigning = true;
      }
    }

    // If the EKU extension was included, then the required EKU must be in the
    // list.
    if (!found) {
      PR_SetError(SEC_ERROR_INADEQUATE_CERT_TYPE, 0);
      return RecoverableError;
    }
  }

  // pkixocsp.cpp depends on the following additional checks.

  if (foundOCSPSigning) {
    // When validating anything other than an delegated OCSP signing cert,
    // reject any cert that also claims to be an OCSP responder, because such
    // a cert does not make sense. For example, if an SSL certificate were to
    // assert id-kp-OCSPSigning then it could sign OCSP responses for itself,
    // if not for this check.
    if (requiredEKU != SEC_OID_OCSP_RESPONDER) {
      PR_SetError(SEC_ERROR_INADEQUATE_CERT_TYPE, 0);
      return RecoverableError;
    }
  } else if (requiredEKU == SEC_OID_OCSP_RESPONDER &&
             endEntityOrCA == MustBeEndEntity) {
    // http://tools.ietf.org/html/rfc6960#section-4.2.2.2:
    // "OCSP signing delegation SHALL be designated by the inclusion of
    // id-kp-OCSPSigning in an extended key usage certificate extension
    // included in the OCSP response signer's certificate."
    //
    // id-kp-OCSPSigning is the only EKU that isn't implicitly assumed when the
    // EKU extension is missing from an end-entity certificate. However, any CA
    // certificate can issue a delegated OCSP response signing certificate, so
    // we can't require the EKU be explicitly included for CA certificates.
    PR_SetError(SEC_ERROR_INADEQUATE_CERT_TYPE, 0);
    return RecoverableError;
  }

  return Success;
}
Ejemplo n.º 7
0
void PPLMGeneralComparison::do_next (xqp_tuple &t)
{
 	if (first_time)
    {
		first_time = false;
		tuple_cell (*comp_op) (const tuple_cell&,const tuple_cell&,CollationHandler*);
		if (strict)
		{
			if (more)
				comp_op=op_gt;
			else
				comp_op=op_lt;
		}
		else
		{
			if (more)
				comp_op=op_ge;
			else
				comp_op=op_le;
		}
		//INSERT CODE HERE
		if (!eos_reached1) seq1.op->reopen();
		if (!eos_reached2) seq2.op->reopen();
		eos_reached2 = false;
		eos_reached1 = false;
		xqp_tuple cont1(seq1.ts);
		xqp_tuple cont2(seq2.ts);
		seq1.op->next(cont1);
		sequence seq(1);
		xqp_tuple at_tup(1);
		seq2.op->next(cont2);
		if (cont2.is_eos())
		{
			eos_reached2 = true;
			t.copy(tuple_cell::atomic(false));
			return;
		}
		tuple_cell res1=getAtomizedCell(cont2);
		while (!cont1.is_eos())
		{
			tuple_cell res=getAtomizedCell(cont1);
			at_tup.cells[0]=res;
			generalNodePrepare(res,res1);
			if (comp_op(res,res1,handler).get_xs_boolean())
			{
				t.copy(tuple_cell::atomic(true));
				return;
			}
			seq.add(at_tup);
			seq1.op->next(cont1);
		}
		eos_reached1 = true;
		if (seq.size()<1)
		{
			t.copy(tuple_cell::atomic(false));
			return;
		}
		seq2.op->next(cont2);
		while (!cont2.is_eos())
		{
			tuple_cell res1=getAtomizedCell(cont2);
			sequence::iterator it=seq.begin();
			do
			{
				tuple_cell res2=(*it).cells[0];
				generalNodePrepare(res1,res2);
				if (comp_op(res2,res1,handler).get_xs_boolean())
				{
					t.copy(tuple_cell::atomic(true));
					return;
				}
				it++;
			}
			while (it!=seq.end());
			seq2.op->next(cont2);
		}
		eos_reached2 = true;
		t.copy(tuple_cell::atomic(false));
		return;

	}
	else 
    {
        first_time = true;
        t.set_eos();
    }
}
Ejemplo n.º 8
0
int PreClusterCommand::mergeGroupCounts(string newcount, string newname, string newfasta){
	try {
		ifstream inNames;
        m->openInputFile(newname, inNames);
        
        string group, first, second;
        set<string> uniqueNames;
        while (!inNames.eof()) {
            if (m->control_pressed) { break; }
            inNames >> group; m->gobble(inNames);
            inNames >> first; m->gobble(inNames);
            inNames >> second; m->gobble(inNames);
            
            vector<string> names;
            m->splitAtComma(second, names);
            
            uniqueNames.insert(first);
            
            int total = ct.getGroupCount(first, group);
            for (int i = 1; i < names.size(); i++) {
                total += ct.getGroupCount(names[i], group);
                ct.setAbund(names[i], group, 0);
            }
            ct.setAbund(first, group, total);
        }
        inNames.close();
        
        vector<string> namesOfSeqs = ct.getNamesOfSeqs();
        for (int i = 0; i < namesOfSeqs.size(); i++) {
            if (ct.getNumSeqs(namesOfSeqs[i]) == 0) {
                ct.remove(namesOfSeqs[i]);
            }
        }
        
        ct.printTable(newcount); 
        m->mothurRemove(newname);
        
        if (bygroup) { //if by group, must remove the duplicate seqs that are named the same
            ifstream in;
            m->openInputFile(newfasta, in);
            
            ofstream out;
            m->openOutputFile(newfasta+"temp", out);
            
            int count = 0;
            set<string> already;
            while(!in.eof()) {
                if (m->control_pressed) { break; }
                
                Sequence seq(in); m->gobble(in);
                
                if (seq.getName() != "") {
                    count++;
                    if (already.count(seq.getName()) == 0) {
                        seq.printSequence(out);
                        already.insert(seq.getName());
                    }
                }
            }
            in.close();
            out.close();
            m->mothurRemove(newfasta);
            m->renameFile(newfasta+"temp", newfasta);
        }
		        return 0;
		
	}
	catch(exception& e) {
		m->errorOut(e, "PreClusterCommand", "mergeGroupCounts");
		exit(1);
	}
}
Ejemplo n.º 9
0
 operator Sequence<ObjectName<ObjTag>>() const {
     return seq();
 }
Ejemplo n.º 10
0
bool ChopSeqsCommand::driver(linePair filePos, string filename, string outFasta, string outAccnos, string fastaFileTemp) {
	try {
		
		ofstream out;
		m->openOutputFile(outFasta, out);
        
        ofstream outAcc;
		m->openOutputFile(outAccnos, outAcc);
        
        ofstream outfTemp;
        if (fastaFileTemp != "") { m->openOutputFile(fastaFileTemp, outfTemp); }
        
		ifstream in;
		m->openInputFile(filename, in);
        
		in.seekg(filePos.start);
        
        //adjust
        if (filePos.start == 0) {
            m->zapGremlins(in); m->gobble(in);
        }
        
		bool done = false;
        bool wroteAccnos = false;
		int count = 0;
        
		while (!done) {
            
			if (m->control_pressed) { in.close(); out.close(); return 1; }
            
			Sequence seq(in); m->gobble(in);
			
			if (m->control_pressed) {  in.close(); out.close(); outAcc.close(); m->mothurRemove(outFasta); m->mothurRemove(outAccnos); if (fastaFileTemp != "") { outfTemp.close(); m->mothurRemove(fastaFileTemp); } return 0;  }
			
			if (seq.getName() != "") {
                string qualValues = "";
				string newSeqString = getChopped(seq, qualValues);
				
				//output trimmed sequence
				if (newSeqString != "") {
					out << ">" << seq.getName() << endl << newSeqString << endl;
				}else{
					outAcc << seq.getName() << endl;
					wroteAccnos = true;
				}
                if (fastaFileTemp != "") {  outfTemp << qualValues << endl;  }
                count++;
			}
			
#if defined (__APPLE__) || (__MACH__) || (linux) || (__linux) || (__linux__) || (__unix__) || (__unix)
            unsigned long long pos = in.tellg();
            if ((pos == -1) || (pos >= filePos.end)) { break; }
#else
            if (in.eof()) { break; }
#endif
            //report progress
			if((count) % 10000 == 0){	m->mothurOut(toString(count)); m->mothurOutEndLine();		}
			
		}
		//report progress
		if((count) % 10000 != 0){	m->mothurOut(toString(count)); m->mothurOutEndLine();		}

		
		in.close();
        out.close();
        outAcc.close();
        if (fastaFileTemp != "") { outfTemp.close(); }
		
		return wroteAccnos;
	}
	catch(exception& e) {
		m->errorOut(e, "ChopSeqsCommand", "driver");
		exit(1);
	}
}