Ejemplo n.º 1
0
bool WestwoodRSA::Encrypt(unsigned char *in_buffer, unsigned int length, unsigned char *out_buffer)
{
    bool success = false;
    if (length > 0)
    {
        Integer e(WWRSA_e);
        Integer N(WWRSA_N);
        Integer M;
        Integer C;
        unsigned int offset = 0;
        unsigned int remaining = length;
        while (remaining >= WWRSA_BLOCK_SIZE)
        {
            M.Decode(in_buffer + offset, WWRSA_BLOCK_SIZE);
            C = a_exp_b_mod_c(M, e, N);
            C.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE);
            offset += WWRSA_BLOCK_SIZE;
            remaining -= WWRSA_BLOCK_SIZE;
        }
        if (remaining > 0)
        {
            unsigned char buffer[WWRSA_BLOCK_SIZE];
            memcpy(buffer, in_buffer + offset, remaining);
            memset(buffer + remaining, 0, WWRSA_BLOCK_SIZE - remaining);
            M.Decode(buffer, WWRSA_BLOCK_SIZE);
            C = a_exp_b_mod_c(M, e, N);
            C.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE);
        }
        success = true;
    }

    return success;
};
Ejemplo n.º 2
0
Archivo: dsa.cpp Proyecto: acat/emule
bool DSA::GeneratePrimes(const byte *seedIn, unsigned int g, int &counter,
						  Integer &p, unsigned int L, Integer &q, bool useInputCounterValue)
{
	assert(g%8 == 0);

	SHA sha;
	SecByteBlock seed(seedIn, g/8);
	SecByteBlock U(SHA::DIGESTSIZE);
	SecByteBlock temp(SHA::DIGESTSIZE);
	SecByteBlock W(((L-1)/160+1) * SHA::DIGESTSIZE);
	const int n = (L-1) / 160;
	const int b = (L-1) % 160;
	Integer X;

	sha.CalculateDigest(U, seed, g/8);

	for (int i=g/8-1, carry=true; i>=0 && carry; i--)
		carry=!++seed[i];

	sha.CalculateDigest(temp, seed, g/8);
	xorbuf(U, temp, SHA::DIGESTSIZE);

	U[0] |= 0x80;
	U[SHA::DIGESTSIZE-1] |= 1;
	q.Decode(U, SHA::DIGESTSIZE);

	if (!IsPrime(q))
		return false;

	int counterEnd = useInputCounterValue ? counter+1 : 4096;

	for (int c = 0; c < counterEnd; c++)
	{
		for (int k=0; k<=n; k++)
		{
			for (int i=g/8-1, carry=true; i>=0 && carry; i--)
				carry=!++seed[i];
			if (!useInputCounterValue || c == counter)
				sha.CalculateDigest(W+(n-k)*SHA::DIGESTSIZE, seed, g/8);
		}
		if (!useInputCounterValue || c == counter)
		{
			W[SHA::DIGESTSIZE - 1 - b/8] |= 0x80;
			X.Decode(W + SHA::DIGESTSIZE - 1 - b/8, L/8);
			p = X-((X % (2*q))-1);

			if (p.GetBit(L-1) && IsPrime(p))
			{
				counter = c;
				return true;
			}
		}
	}
	return false;
}
Ejemplo n.º 3
0
Integer NR_EncodeDigest(unsigned int modulusBits, const byte *digest, unsigned int digestLen)
{
	Integer h;
	if (digestLen*8 < modulusBits)
		h.Decode(digest, digestLen);
	else
	{
		h.Decode(digest, bitsToBytes(modulusBits));
		h >>= bitsToBytes(modulusBits)*8 - modulusBits + 1;
	}
	return h;
}
Ejemplo n.º 4
0
Integer NRDigestVerifier::EncodeDigest(const byte *digest, unsigned int digestLen) const
{
    Integer h;
    if (digestLen*8 < q.BitCount())
        h.Decode(digest, digestLen);
    else
    {
        h.Decode(digest, q.ByteCount());
        h >>= q.ByteCount()*8 - q.BitCount() + 1;
    }
    assert(h < q);
    return h;
}
Ejemplo n.º 5
0
// Generate Agreement
void DH::Agree(byte* agree, const byte* priv, const byte* otherPub, word32
               otherSz)
{
    const word32 bc(p_.ByteCount());
    Integer x(priv, bc);
    Integer y;
    if (otherSz)
        y.Decode(otherPub, otherSz);
    else
        y.Decode(otherPub, bc);

    Integer z(a_exp_b_mod_c(y, x, p_));
    z.Encode(agree, bc);
}
Ejemplo n.º 6
0
bool CMessageCrypter::Decrypt(const string& vchPrivKey, const string& vchCiphertext, string& vchPlaintext)
{
    try
    {
        AutoSeededRandomPool prng;

        StringSource ss(vchPrivKey, true /*pumpAll*/);

        Integer x;
        x.Decode(ss, ss.MaxRetrievable(), Integer::UNSIGNED);

        ECIES<ECP>::Decryptor decryptor;

		decryptor.AccessKey().AccessGroupParameters().Initialize(ASN1::secp256k1());	
        //make decryptor's access key using decoded private exponent's value
        decryptor.AccessKey().SetPrivateExponent(x);

        //check whether decryptor's access key is valid or not
        bool valid = decryptor.AccessKey().Validate(prng, 3);
        if(!valid)
           decryptor.AccessKey().ThrowIfInvalid(prng, 3);

        //decrypt the message using private key
        StringSource ss2 (vchCiphertext, true, new PK_DecryptorFilter(prng, decryptor, new StringSink(vchPlaintext) ) );

    }
    catch(const CryptoPP::Exception& ex)
    {
		return false;
    }
    return true;
}
Ejemplo n.º 7
0
ustring PubAddr::getPubOfPriv(ustring priv)
{
	OID CURVE = secp256k1();
	ECIES < ECP >::PrivateKey privK;

	Integer x;
	x.Decode(priv.c_str(), priv.size());
	privK.Initialize(CURVE, x);

	ECIES<ECP>::PublicKey pub;
	privK.MakePublicKey(pub);

	string encoded;
	int len = pub.GetPublicElement().x.MinEncodedSize();
	pub.GetPublicElement().x.Encode(StringSink(encoded).Ref(), len);

	len = pub.GetPublicElement().y.MinEncodedSize();
	pub.GetPublicElement().y.Encode(StringSink(encoded).Ref(), len);

	ustring ret;
	ret += 0x04;
	ret.fromString(encoded);

	return ret;
}
Ejemplo n.º 8
0
std::string Converter::SecByteBlockToString(SecByteBlock data){
	Integer a;
	a.Decode(data.BytePtr(), data.SizeInBytes());
	//cout<< "ze secbyteblock do integera: "<<a<<endl;
	std::ostrstream oss;
	oss << std::hex << a;
	std::string s(oss.str());
	s = s.substr(0, 2*data.SizeInBytes()+1); //Do zapamiêtania. d³ugoœæ stringa z s wynosi 2*d³ugoœæ w bytach plus 1.
	return s;
}
//***************************************************************
Integer HashClass::getSHA1Integer(string m, Integer r)
{
    byte *encodedMessage = (byte *)m.c_str();
    int messageSize = m.length();
    int rSize = r.MinEncodedSize();
    byte * encodedR = new byte[rSize];
    r.Encode(encodedR, rSize);
    
    byte * hashInput = new byte[rSize + messageSize];
    copy(encodedMessage, encodedMessage + messageSize, hashInput);
    copy(encodedR, encodedR + rSize, hashInput + messageSize);
    byte *hashOutput = getSHA1(hashInput, rSize+messageSize);
    Integer result;
    r.Decode(hashOutput, HashClass::size);
    return r;
}
Ejemplo n.º 10
0
Integer HashPointMessage(const ECP& ec, const ECPPoint& R,
	const byte* message, int mlen, bool compress = false)
{
	const int digestsize = 256/8;
	SHA3 sha(digestsize);

	int len = ec.EncodedPointSize();
	byte *buffer = new byte[len];
	ec.EncodePoint(buffer, R, compress);
	sha.Update(buffer, len);
	delete[] buffer;

	sha.Update(message, mlen);

	byte digest[digestsize];
	sha.Final(digest);
	
	Integer ans;
	ans.Decode(digest, digestsize);
	return ans;
}
Ejemplo n.º 11
0
bool WestwoodRSA::Decrypt(unsigned char *in_buffer, unsigned int length, unsigned char *out_buffer)
{
    bool success = false;
    unsigned int blocks = length / WWRSA_BLOCK_SIZE;
    if (blocks * WWRSA_BLOCK_SIZE == length)
    {
        Integer d(WWRSA_d);
        Integer N(WWRSA_N);
        Integer C;
        Integer M;
        unsigned int offset = 0;
        for (unsigned int i = 0; i < blocks; i++)
        {
            C.Decode(in_buffer + offset, WWRSA_BLOCK_SIZE);
            M = a_exp_b_mod_c(C, d, N);
            M.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE);
            offset += WWRSA_BLOCK_SIZE;
        }
        success = true;
    }

    return success;
};
Ejemplo n.º 12
0
void DL_PrivateKey_EC<EC>::BERDecodeKey2(BufferedTransformation &bt, bool parametersPresent, unsigned int size)
{
	BERSequenceDecoder seq(bt);
		word32 version;
		BERDecodeUnsigned<word32>(seq, version, INTEGER, 1, 1);	// check version

		BERGeneralDecoder dec(seq, OCTET_STRING);
		if (!dec.IsDefiniteLength())
			BERDecodeError();
		Integer x;
		x.Decode(dec, dec.RemainingLength());
		dec.MessageEnd();
		if (!parametersPresent && seq.PeekByte() != (CONTEXT_SPECIFIC | CONSTRUCTED | 0))
			BERDecodeError();
		if (!seq.EndReached() && seq.PeekByte() == (CONTEXT_SPECIFIC | CONSTRUCTED | 0))
		{
			BERGeneralDecoder parameters(seq, CONTEXT_SPECIFIC | CONSTRUCTED | 0);
			AccessGroupParameters().BERDecode(parameters);
			parameters.MessageEnd();
		}
		if (!seq.EndReached())
		{
			// skip over the public element
			SecByteBlock subjectPublicKey;
			unsigned int unusedBits;
			BERGeneralDecoder publicKey(seq, CONTEXT_SPECIFIC | CONSTRUCTED | 1);
			BERDecodeBitString(publicKey, subjectPublicKey, unusedBits);
			publicKey.MessageEnd();
			Element Q;
			if (!(unusedBits == 0 && GetGroupParameters().GetCurve().DecodePoint(Q, subjectPublicKey, subjectPublicKey.size())))
				BERDecodeError();
		}
	seq.MessageEnd();

	SetPrivateExponent(x);
}
Ejemplo n.º 13
0
//********************************************************************************************************
Integer Converter::decodeSecByteBlock(SecByteBlock key)
{
    Integer x;
    x.Decode(key.BytePtr(), key.SizeInBytes());
    return x;
}
Ejemplo n.º 14
0
int Addr::generateDeterministic(ustring passphrase, int nonce)
{
	int nonce_old = nonce;
	int stream = 1;
	int version = 4;

	OID CURVE = secp256k1();
	AutoSeededRandomPool rng;


	ECIES<ECP>::PrivateKey privE, privS;

	ustring pubSKey;
	ustring pubEKey;

	string encoded;
	size_t len;

	byte digest2[CryptoPP::RIPEMD160::DIGESTSIZE];

	int zeros = 0;
	do
	{
		CryptoPP::SHA512 hash;
		byte digest[CryptoPP::SHA512::DIGESTSIZE];

		ustring passP = passphrase;
		passP.appendVarInt_B(nonce++);

		hash.CalculateDigest(digest, (byte*)passP.c_str(), passP.size());

		Integer x;
		x.Decode(digest, 32); //first 32 bytes
		privS.Initialize(CURVE, x);

		passP = passphrase;
		passP.appendVarInt_B(nonce++);

		hash.CalculateDigest(digest, (byte*)passP.c_str(), passP.size());

		x.Decode(digest, 32);
		privE.Initialize(CURVE, x);

		ECIES<ECP>::PublicKey pubE, pubS;
		privE.MakePublicKey(pubE);
		privS.MakePublicKey(pubS);

		encoded.clear();
		len = pubE.GetPublicElement().x.MinEncodedSize();
		pubE.GetPublicElement().x.Encode(StringSink(encoded).Ref(), len);

		len = pubE.GetPublicElement().y.MinEncodedSize();
		pubE.GetPublicElement().y.Encode(StringSink(encoded).Ref(), len);

		pubEKey.clear();
		pubEKey += 0x04;
		pubEKey.fromString(encoded);


		encoded.clear();
		len = pubS.GetPublicElement().x.MinEncodedSize();
		pubS.GetPublicElement().x.Encode(StringSink(encoded).Ref(), len);

		len = pubS.GetPublicElement().y.MinEncodedSize();
		pubS.GetPublicElement().y.Encode(StringSink(encoded).Ref(), len);

		pubSKey.clear();
		pubSKey += 0x04;
		pubSKey.fromString(encoded);


		memset(digest, 0, SHA512::DIGESTSIZE);

		ustring buffer;
		buffer += pubSKey;
		buffer += pubEKey;

		hash.CalculateDigest(digest, (byte*)buffer.c_str(), buffer.length());

		CryptoPP::RIPEMD160 hash2;
		memset(digest2, 0x00, 20);
		hash2.CalculateDigest(digest2, digest, sizeof digest);


		while (digest2[zeros] == 0x00)
			zeros++;
	} while (zeros == 0);

	encoded.clear();
	len = privE.GetPrivateExponent().MinEncodedSize();
	privE.GetPrivateExponent().Encode(StringSink(encoded).Ref(), len);

	ustring privEKey;
	privEKey.fromString(encoded);

	encoded.clear();
	len = privS.GetPrivateExponent().MinEncodedSize();
	privS.GetPrivateExponent().Encode(StringSink(encoded).Ref(), len);

	ustring privSKey;
	privSKey.fromString(encoded);

	if (!this->loadKeys(pubEKey, pubSKey, privEKey, privSKey, stream, version))
		return nonce_old;

	return nonce;
}
Ejemplo n.º 15
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;
}