Example #1
0
bool OSSLDSA::reconstructParameters(AsymmetricParameters** ppParams, ByteString& serialisedData)
{
	// Check input parameters
	if ((ppParams == NULL) || (serialisedData.size() == 0))
	{
		return false;
	}

	DSAParameters* params = new DSAParameters();

	if (!params->deserialise(serialisedData))
	{
		delete params;

		return false;
	}

	*ppParams = params;

	return true;
}
Example #2
0
bool BotanRSA::reconstructPublicKey(PublicKey** ppPublicKey, ByteString& serialisedData)
{
	// Check input
	if ((ppPublicKey == NULL) ||
	    (serialisedData.size() == 0))
	{
		return false;
	}

	BotanRSAPublicKey* pub = new BotanRSAPublicKey();

	if (!pub->deserialise(serialisedData))
	{
		delete pub;

		return false;
	}

	*ppPublicKey = pub;

	return true;
}
Example #3
0
bool BotanRSA::reconstructPrivateKey(PrivateKey** ppPrivateKey, ByteString& serialisedData)
{
	// Check input
	if ((ppPrivateKey == NULL) ||
	    (serialisedData.size() == 0))
	{
		return false;
	}

	BotanRSAPrivateKey* priv = new BotanRSAPrivateKey();

	if (!priv->deserialise(serialisedData))
	{
		delete priv;

		return false;
	}

	*ppPrivateKey = priv;

	return true;
}
Example #4
0
void HashTests::readTmpFile(ByteString& data)
{
	unsigned char buf[256];

	data.wipe();

	FILE* in = fopen("shsmv2-hashtest-out.tmp", "r");
	CPPUNIT_ASSERT(in != NULL);

	int read = 0;

	do
	{
		read = fread(buf, 1, 256, in);

		data += ByteString(buf, read);
	}
	while (read > 0);

	CPPUNIT_ASSERT(read == 0);
	CPPUNIT_ASSERT(!fclose(in));
}
Example #5
0
bool FileSystem::ReadFile(const char *Filename, ByteString &DataBuffer)
{
	// Waste of time.
	if (!FileExists(Filename))
		return false;

	bool Result = false;
	uint32_t ReadSize = GetFileSize(Filename);
	uint8_t *ReadBuffer = new uint8_t[ReadSize];
	SecureZeroMemory(ReadBuffer, ReadSize);

	// Read the file.
	Result = ReadFile(Filename, ReadBuffer, ReadSize);

	// Append the data.
	DataBuffer.append(ReadBuffer, ReadSize);

	// Clear the buffer.
	SecureZeroMemory(ReadBuffer, ReadSize);
	delete[] ReadBuffer;

	return Result;
}
Example #6
0
void loadLogo (String fileName)
{
  //Read the file
  File file( fileName );
  if( !file.open( "rb" ))
  {
    printf( "Failed opening file '%s'!\n", fileName.toCSTR().buffer() );
    getchar();
    exit( 1 );
  }
  
  data = file.read( file.getSize() );
  file.close();
  
  //Load character data
  SerializeManager sm;
  mshLogo = (TriMesh*) sm.load( (void*)data.buffer() );
  mshLogo->sendToGpu();

  printf ("Logo: %d verts, %d faces\n",
          mshLogo->getVertexCount(),
          mshLogo->getFaceCount());
}
Example #7
0
bool BotanRSA::reconstructKeyPair(AsymmetricKeyPair** ppKeyPair, ByteString& serialisedData)
{
	// Check input
	if ((ppKeyPair == NULL) ||
	    (serialisedData.size() == 0))
	{
		return false;
	}

	ByteString dPub = ByteString::chainDeserialise(serialisedData);
	ByteString dPriv = ByteString::chainDeserialise(serialisedData);

	BotanRSAKeyPair* kp = new BotanRSAKeyPair();

	bool rv = true;

	if (!((RSAPublicKey*) kp->getPublicKey())->deserialise(dPub))
	{
		rv = false;
	}

	if (!((RSAPrivateKey*) kp->getPrivateKey())->deserialise(dPriv))
	{
		rv = false;
	}

	if (!rv)
	{
		delete kp;

		return false;
	}

	*ppKeyPair = kp;

	return true;
}
Example #8
0
bool DHPrivateKey::deserialise(ByteString& serialised)
{
	ByteString dP = ByteString::chainDeserialise(serialised);
	ByteString dG = ByteString::chainDeserialise(serialised);
	ByteString dX = ByteString::chainDeserialise(serialised);

	if ((dP.size() == 0) ||
	    (dG.size() == 0) ||
	    (dX.size() == 0))
	{
		return false;
	}

	setP(dP);
	setG(dG);
	setX(dX);

	return true;
}
Example #9
0
bool OSAttribute::peekValue(ByteString& value) const
{
	switch (attributeType)
	{
		case BOOL:
			value.resize(sizeof(boolValue));
			memcpy(&value[0], &boolValue, value.size());
			return true;

		case ULONG:
			value.resize(sizeof(ulongValue));
			memcpy(&value[0], &ulongValue, value.size());
			return true;

		case BYTESTR:
			value.resize(byteStrValue.size());
			memcpy(&value[0], byteStrValue.const_byte_str(), value.size());
			return true;

		default:
			return false;
	}
}
Example #10
0
// Encryption functions
bool BotanRSA::encrypt(PublicKey* publicKey, const ByteString& data,
		       ByteString& encryptedData, const AsymMech::Type padding)
{
	// Check if the public key is the right type
	if (!publicKey->isOfType(BotanRSAPublicKey::type))
	{
		ERROR_MSG("Invalid key type supplied");

		return false;
	}

	std::string eme;

	switch (padding)
	{
		case AsymMech::RSA_PKCS:
			eme = "PKCS1v15";
			break;
		case AsymMech::RSA_PKCS_OAEP:
			eme = "EME1(SHA-160)";
			break;
		case AsymMech::RSA:
			eme = "Raw";
			break;
		default:
			ERROR_MSG("Invalid padding mechanism supplied (%i)", padding);

			return false;
	}

	BotanRSAPublicKey* pk = (BotanRSAPublicKey*) publicKey;
	Botan::RSA_PublicKey* botanKey = pk->getBotanKey();

	if (!botanKey)
	{
		ERROR_MSG("Could not get the Botan public key");

		return false;
	}

	Botan::PK_Encryptor_EME* encryptor = NULL;
	try
	{
		encryptor = new Botan::PK_Encryptor_EME(*botanKey, eme);
	}
	catch (...)
	{
		ERROR_MSG("Could not create the encryptor token");

		return false;
	}

	// Perform the encryption operation
#if BOTAN_VERSION_MINOR == 11
	std::vector<Botan::byte> encResult;
#else
	Botan::SecureVector<Botan::byte> encResult;
#endif
	try
	{
		BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG();
		encResult = encryptor->encrypt(data.const_byte_str(), data.size(), *rng->getRNG());
	}
	catch (...)
	{
		ERROR_MSG("Could not encrypt the data");

		delete encryptor;

		return false;
	}

	// Return the result
	encryptedData.resize(encResult.size());
#if BOTAN_VERSION_MINOR == 11
	memcpy(&encryptedData[0], encResult.data(), encResult.size());
#else
	memcpy(&encryptedData[0], encResult.begin(), encResult.size());
#endif

	delete encryptor;

	return true;
}
Example #11
0
// Signing functions
bool BotanRSA::sign(PrivateKey* privateKey, const ByteString& dataToSign,
		    ByteString& signature, const AsymMech::Type mechanism,
		    const void* param /* = NULL */, const size_t paramLen /* = 0 */)
{
	std::string emsa = "";

	switch (mechanism)
	{
		case AsymMech::RSA:
			emsa = "Raw";
			break;
		case AsymMech::RSA_PKCS:
			emsa = "EMSA3(Raw)";
			break;
		default:
			// Call default implementation
			return AsymmetricAlgorithm::sign(privateKey, dataToSign, signature, mechanism, param, paramLen);
	}

	// Check if the private key is the right type
	if (!privateKey->isOfType(BotanRSAPrivateKey::type))
	{
		ERROR_MSG("Invalid key type supplied");

		return false;
	}

	BotanRSAPrivateKey* pk = (BotanRSAPrivateKey*) privateKey;
	Botan::RSA_PrivateKey* botanKey = pk->getBotanKey();

	if (!botanKey)
	{
		ERROR_MSG("Could not get the Botan private key");

		return false;
	}

	try
	{
		signer = new Botan::PK_Signer(*botanKey, emsa);
		// Should we add DISABLE_FAULT_PROTECTION? Makes this operation faster.
	}
	catch (...)
	{
		ERROR_MSG("Could not create the signer token");

		return false;
	}

	// Perform the signature operation
#if BOTAN_VERSION_MINOR == 11
	std::vector<Botan::byte> signResult;
#else
	Botan::SecureVector<Botan::byte> signResult;
#endif
	try
	{
		BotanRNG* rng = (BotanRNG*)BotanCryptoFactory::i()->getRNG();
		signResult = signer->sign_message(dataToSign.const_byte_str(), dataToSign.size(), *rng->getRNG());
	}
	catch (std::exception& e)
	{
		ERROR_MSG("Could not sign the data: %s", e.what());

		delete signer;
		signer = NULL;

		return false;
	}

	// Return the result
	signature.resize(signResult.size());
#if BOTAN_VERSION_MINOR == 11
	memcpy(&signature[0], signResult.data(), signResult.size());
#else
	memcpy(&signature[0], signResult.begin(), signResult.size());
#endif

	delete signer;
	signer = NULL;

	return true;
}
Example #12
0
// Verification functions
bool BotanRSA::verify(PublicKey* publicKey, const ByteString& originalData,
		      const ByteString& signature, const AsymMech::Type mechanism,
		      const void* param /* = NULL */, const size_t paramLen /* = 0 */)
{
	std::string emsa = "";

	switch (mechanism)
	{
		case AsymMech::RSA:
			emsa = "Raw";
			break;
		case AsymMech::RSA_PKCS:
			emsa = "EMSA3(Raw)";
			break;
		default:
			// Call the generic function
			return AsymmetricAlgorithm::verify(publicKey, originalData, signature, mechanism, param, paramLen);
	}

	// Check if the public key is the right type
	if (!publicKey->isOfType(BotanRSAPublicKey::type))
	{
		ERROR_MSG("Invalid key type supplied");

		return false;
	}

	BotanRSAPublicKey* pk = (BotanRSAPublicKey*) publicKey;
	Botan::RSA_PublicKey* botanKey = pk->getBotanKey();

	if (!botanKey)
	{
		ERROR_MSG("Could not get the Botan public key");

		return false;
	}

	try
	{
		verifier = new Botan::PK_Verifier(*botanKey, emsa);
	}
	catch (...)
	{
		ERROR_MSG("Could not create the verifier token");

		return false;
	}

	// Perform the verify operation
	bool verResult;
	try
	{
		verResult = verifier->verify_message(originalData.const_byte_str(),
							originalData.size(),
							signature.const_byte_str(),
							signature.size());
	}
	catch (...)
	{
		ERROR_MSG("Could not check the signature");

		delete verifier;
		verifier = NULL;

		return false;
	}

	delete verifier;
	verifier = NULL;

	return verResult;
}
Example #13
0
void DSATests::testSigningVerifying()
{
	AsymmetricKeyPair* kp;

	// Key sizes to test
	std::vector<size_t> keySizes;
#ifndef WITH_FIPS
	keySizes.push_back(512);
	keySizes.push_back(768);
	keySizes.push_back(1024);
	keySizes.push_back(1536);
#else
	keySizes.push_back(1024);
#endif
#ifndef WITH_BOTAN
	keySizes.push_back(2048);
#endif

	// Mechanisms to test
	std::vector<AsymMech::Type> mechanisms;
	mechanisms.push_back(AsymMech::DSA_SHA1);
	mechanisms.push_back(AsymMech::DSA_SHA224);
	mechanisms.push_back(AsymMech::DSA_SHA256);

	for (std::vector<size_t>::iterator k = keySizes.begin(); k != keySizes.end(); k++)
	{
		// Generate parameters
		AsymmetricParameters* p;

		CPPUNIT_ASSERT(dsa->generateParameters(&p, (void*) *k));

		// Generate key-pair
		CPPUNIT_ASSERT(dsa->generateKeyPair(&kp, p));

		// Generate some data to sign
		ByteString dataToSign;

		RNG* rng = CryptoFactory::i()->getRNG();

		CPPUNIT_ASSERT(rng->generateRandom(dataToSign, 567));

		// Test mechanisms that perform internal hashing
		for (std::vector<AsymMech::Type>::iterator m = mechanisms.begin(); m != mechanisms.end(); m++)
		{
			ByteString blockSignature, singlePartSignature;

			// Sign the data in blocks
			CPPUNIT_ASSERT(dsa->signInit(kp->getPrivateKey(), *m));
			CPPUNIT_ASSERT(dsa->signUpdate(dataToSign.substr(0, 134)));
			CPPUNIT_ASSERT(dsa->signUpdate(dataToSign.substr(134, 289)));
			CPPUNIT_ASSERT(dsa->signUpdate(dataToSign.substr(134 + 289)));
			CPPUNIT_ASSERT(dsa->signFinal(blockSignature));

			// Sign the data in one pass
			CPPUNIT_ASSERT(dsa->sign(kp->getPrivateKey(), dataToSign, singlePartSignature, *m));

			// Now perform multi-pass verification
			CPPUNIT_ASSERT(dsa->verifyInit(kp->getPublicKey(), *m));
			CPPUNIT_ASSERT(dsa->verifyUpdate(dataToSign.substr(0, 125)));
			CPPUNIT_ASSERT(dsa->verifyUpdate(dataToSign.substr(125, 247)));
			CPPUNIT_ASSERT(dsa->verifyUpdate(dataToSign.substr(125 + 247)));
			CPPUNIT_ASSERT(dsa->verifyFinal(blockSignature));

			// And single-pass verification
			CPPUNIT_ASSERT(dsa->verify(kp->getPublicKey(), dataToSign, singlePartSignature, *m));
		}

		// Test mechanisms that do not perform internal hashing
		CPPUNIT_ASSERT(rng->generateRandom(dataToSign, *k >= 2048 ? 32 : 20));

		// Sign the data
		ByteString signature;
		CPPUNIT_ASSERT(dsa->sign(kp->getPrivateKey(), dataToSign, signature, AsymMech::DSA));

		// Verify the signature
		CPPUNIT_ASSERT(dsa->verify(kp->getPublicKey(), dataToSign, signature, AsymMech::DSA));

		dsa->recycleKeyPair(kp);
		dsa->recycleParameters(p);
	}
}
Example #14
0
// Generic function for creating an encrypted version of the key from the specified passphrase
bool SecureDataManager::pbeEncryptKey(const ByteString& passphrase, ByteString& encryptedKey)
{
	// Generate salt
	ByteString salt;

	if (!rng->generateRandom(salt, 8)) return false;

	// Derive the key using RFC4880 PBE
	AESKey* pbeKey = NULL;

	if (!RFC4880::PBEDeriveKey(passphrase, salt, &pbeKey))
	{
		return false;
	}

	// Add the salt
	encryptedKey.wipe();
	encryptedKey += salt;

	// Generate random IV
	ByteString IV;

	if (!rng->generateRandom(IV, aes->getBlockSize())) return false;

	// Add the IV
	encryptedKey += IV;

	// Encrypt the data
	ByteString block;

	if (!aes->encryptInit(pbeKey, SymMode::CBC, IV))
	{
		delete pbeKey;

		return false;
	}

	// First, add the magic
	if (!aes->encryptUpdate(magic, block))
	{
		delete pbeKey;

		return false;
	}

	encryptedKey += block;

	// Then, add the key itself
	ByteString key;

	{
		MutexLocker lock(dataMgrMutex);

		unmask(key);

		bool rv = aes->encryptUpdate(key, block);

		remask(key);

		if (!rv)
		{
			delete pbeKey;

			return false;
		}
	}

	encryptedKey += block;

	// And finalise encryption
	if (!aes->encryptFinal(block))
	{
		delete pbeKey;

		return false;
	}

	encryptedKey += block;

	delete pbeKey;

	return true;
}
Example #15
0
// Set the specified attribute
bool DBObject::setAttribute(CK_ATTRIBUTE_TYPE type, const OSAttribute& attribute)
{
	MutexLocker lock(_mutex);

	if (_connection == NULL)
	{
		ERROR_MSG("Object is not connected to the database.");
		return false;
	}
	if (_objectId == 0)
	{
		ERROR_MSG("Cannot update invalid object.");
		return false;
	}

	// Retrieve and existing attribute if it exists or NULL if it doesn't
	OSAttribute *attr = getAttributeDB(type);

	// Update an existing attribute...
	if (attr)
	{
		DB::Statement statement;
		if (attr->isBooleanAttribute())
		{
			// update boolean attribute
			statement = _connection->prepare(
					"update attribute_boolean set value=%d where type=%lu and object_id=%lld",
					attribute.getBooleanValue() ? 1 : 0,
					type,
					_objectId);
		}
		else if (attr->isUnsignedLongAttribute())
		{
			// update integer attribute
			statement = _connection->prepare(
					"update attribute_integer set value=%lld where type=%lu and object_id=%lld",
					static_cast<long long>(attribute.getUnsignedLongValue()),
					type,
					_objectId);
		}
		else if (attr->isByteStringAttribute())
		{
			// update binary attribute
			statement = _connection->prepare(
					"update attribute_binary set value=? where type=%lu and object_id=%lld",
					type,
					_objectId);
			DB::Bindings(statement).bindBlob(1, attribute.getByteStringValue().const_byte_str(), attribute.getByteStringValue().size(), SQLITE_STATIC);
		}
		else if (attr->isMechanismTypeSetAttribute())
		{
			// update binary attribute
			ByteString value;
			encodeMechanismTypeSet(value, attribute.getMechanismTypeSetValue());

			statement = _connection->prepare(
					"update attribute_binary set value=? where type=%lu and object_id=%lld",
					type,
					_objectId);
			DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
		}
		else if (attr->isAttributeMapAttribute())
		{
			// update attribute map attribute
			ByteString value;
			if (!encodeAttributeMap(value, attribute.getAttributeMapValue()))
			{
				return false;
			}

			statement = _connection->prepare(
					"update attribute_array set value=? where type=%lu and object_id=%lld",
					type,
					_objectId);
			DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
		}

		// Statement is valid when a prepared statement has been attached to it.
		if (statement.isValid())
		{
			if (!_connection->execute(statement))
			{
				ERROR_MSG("Failed to update attribute %lu for object %lld",type,_objectId);
				return false;
			}

			if (_transaction)
			{
				std::map<CK_ATTRIBUTE_TYPE,OSAttribute*>::iterator it =	 _transaction->find(type);
				if (it != _transaction->end())
					*it->second = attribute;
				else
					(*_transaction)[type] = new OSAttribute(attribute);
			} else
				*attr = attribute;
			return true;
		}
	}

	DB::Statement statement;

	// Insert the attribute, because it is currently unknown
	if (attribute.isBooleanAttribute())
	{
		// Could not update it, so we need to insert it.
		statement = _connection->prepare(
					"insert into attribute_boolean (value,type,object_id) values (%d,%lu,%lld)",
					attribute.getBooleanValue() ? 1 : 0,
					type,
					_objectId);

	}
	else if (attribute.isUnsignedLongAttribute())
	{
		// Could not update it, so we need to insert it.
		statement = _connection->prepare(
					"insert into attribute_integer (value,type,object_id) values (%lld,%lu,%lld)",
					static_cast<long long>(attribute.getUnsignedLongValue()),
					type,
					_objectId);
	}
	else if (attribute.isByteStringAttribute())
	{
		// Could not update it, so we need to insert it.
		statement = _connection->prepare(
					"insert into attribute_binary (value,type,object_id) values (?,%lu,%lld)",
					type,
					_objectId);

		DB::Bindings(statement).bindBlob(1, attribute.getByteStringValue().const_byte_str(), attribute.getByteStringValue().size(), SQLITE_STATIC);
	}
	else if (attribute.isMechanismTypeSetAttribute())
	{
		// Could not update it, so we need to insert it.
		ByteString value;
		encodeMechanismTypeSet(value, attribute.getMechanismTypeSetValue());

		statement = _connection->prepare(
				"insert into attribute_binary (value,type,object_id) values (?,%lu,%lld)",
				type,
				_objectId);
		DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
	}
	else if (attribute.isAttributeMapAttribute())
	{
		// Could not update it, so we need to insert it.
		ByteString value;
		if (!encodeAttributeMap(value, attribute.getAttributeMapValue()))
		{
			return false;
		}

		statement = _connection->prepare(
				"insert into attribute_array (value,type,object_id) values (?,%lu,%lld)",
				type,
				_objectId);
		DB::Bindings(statement).bindBlob(1, value.const_byte_str(), value.size(), SQLITE_TRANSIENT);
	}

	// Statement is valid when a prepared statement has been attached to it.
	if (statement.isValid())
	{
		if (!_connection->execute(statement))
		{
			ERROR_MSG("Failed to insert attribute %lu for object %lld",type,_objectId);
			return false;
		}

		if (_transaction)
			(*_transaction)[type] = new OSAttribute(attribute);
		else
			_attributes[type] = new OSAttribute(attribute);
		return true;
	}

	return false;
}
// Encryption functions
bool BotanSymmetricAlgorithm::encryptInit(const SymmetricKey* key, const std::string mode /* = "cbc" */, const ByteString& IV /* = ByteString()*/, bool padding /* = true */)
{
	// Call the superclass initialiser
	if (!SymmetricAlgorithm::encryptInit(key, mode, IV, padding))
	{
		return false;
	}

	// Check the IV
	if ((IV.size() > 0) && (IV.size() != getBlockSize()))
	{
		ERROR_MSG("Invalid IV size (%d bytes, expected %d bytes)", IV.size(), getBlockSize());

		ByteString dummy;
		SymmetricAlgorithm::encryptFinal(dummy);

		return false;
	}

	ByteString iv;

	if (IV.size() > 0)
	{
		iv = IV;
	}
	else
	{
		iv.wipe(getBlockSize());
	}

	// Set the padding mode (PCKS7 or NoPadding)
	if (padding)
	{
		currentPaddingMode = "PKCS7";
	}
	else
	{
		currentPaddingMode = "NoPadding";
	}

	// Determine the cipher
	std::string cipherName = getCipher();

	if (cipherName == "")
	{
		ERROR_MSG("Invalid encryption cipher");

		ByteString dummy;
		SymmetricAlgorithm::encryptFinal(dummy);

		return false;
	}

	// Allocate the context
	try
	{
		Botan::SymmetricKey botanKey = Botan::SymmetricKey(key->getKeyBits().const_byte_str(), key->getKeyBits().size());
		Botan::InitializationVector botanIV = Botan::InitializationVector(IV.const_byte_str(), IV.size());
		if (mode == "ecb")
		{
			cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, Botan::ENCRYPTION));
		}
		else
		{
			cryption = new Botan::Pipe(Botan::get_cipher(cipherName, botanKey, botanIV, Botan::ENCRYPTION));
		}
		cryption->start_msg();
	}
	catch (...)
	{
		ERROR_MSG("Failed to create the encryption token");

		ByteString dummy;
		SymmetricAlgorithm::encryptFinal(dummy);

		delete cryption;
		cryption = NULL;

		return false;
	}

	return true;
}
bool BPlusTree::recursiveInsert(Node* nodoCorriente, Key clave, ByteString dato, Key* clavePromocion, Node** nuevoNodo) {

	if (!nodoCorriente->isLeaf()) {

		InnerNode *nodoInteriorCorriente = static_cast<InnerNode*> (nodoCorriente);
		Key nuevaClave;
		Node* nuevoNodoHijo = NULL;
		int posicion = getPosition(nodoInteriorCorriente, clave);
		Node* nodoHijo = hidratateNode(nodoInteriorCorriente->sons[posicion]);

		bool resultado = recursiveInsert(nodoHijo, clave, dato, &nuevaClave, &nuevoNodoHijo);

		if (nuevoNodoHijo) {

			if (nodoInteriorCorriente->isOverflow(nuevaClave.getSize() + TreeConstraits::getControlSizeRecord() + keyTopSize)) {

				splitInnerNode(nodoInteriorCorriente, clavePromocion, nuevoNodo, posicion);

				if (posicion == nodoInteriorCorriente->keyMount + 1
						&& nodoInteriorCorriente->keyMount < (*nuevoNodo)->keyMount) {

					InnerNode *nuevoNodoInterior = static_cast<InnerNode*> (*nuevoNodo);
					nodoInteriorCorriente->keys[nodoInteriorCorriente->keyMount] = *clavePromocion;
					nodoInteriorCorriente->sons[nodoInteriorCorriente->keyMount + 1] = nuevoNodoInterior->sons[0];
					nodoInteriorCorriente->keyMount++;
					nodoInteriorCorriente->occupiedSpace += (*clavePromocion).getSize() + TreeConstraits::getControlSizeRecord();
					nuevoNodoInterior->sons[0] = nuevoNodoHijo->number;
					*clavePromocion = nuevaClave;

					persistNode(nuevoNodoHijo);
					freeNodeMemory(nuevoNodoHijo);

					persistNode(nodoHijo);
					freeNodeMemory(nodoHijo);

					return resultado;

				} else {

					if (posicion >= nodoInteriorCorriente->keyMount + 1) {
						posicion -= (nodoInteriorCorriente->keyMount + 1);
						nodoInteriorCorriente = static_cast<InnerNode*> (*nuevoNodo);
					}
				}
			}

			int i = nodoInteriorCorriente->keyMount;
			while (i > posicion) {
				nodoInteriorCorriente->keys[i] = nodoInteriorCorriente->keys[i - 1];
				nodoInteriorCorriente->sons[i + 1] = nodoInteriorCorriente->sons[i];
				i--;
			}
			nodoInteriorCorriente->keys[posicion] = nuevaClave;
			nodoInteriorCorriente->sons[posicion + 1] = nuevoNodoHijo->number;
			nodoInteriorCorriente->keyMount++;
			nodoInteriorCorriente->occupiedSpace += nuevaClave.getSize() + TreeConstraits::getControlSizeRecord();

			persistNode(nuevoNodoHijo);
			freeNodeMemory(nuevoNodoHijo);
		}
		persistNode(nodoHijo);
		freeNodeMemory(nodoHijo);

		return resultado;

	} else {

		LeafNode *nodoHojaCorriente = static_cast<LeafNode*> (nodoCorriente);
		int posicion = getPosition(nodoHojaCorriente, clave);

		// chequea que no exista la clave
		if (posicion < nodoHojaCorriente->keyMount && equalKey(clave, nodoHojaCorriente->keys[posicion])) {
			return false;
		}

		int i = nodoHojaCorriente->keyMount - 1;
		while (i >= 0 && minorKey(clave, nodoHojaCorriente->keys[i])) {
			nodoHojaCorriente->keys[i + 1] = nodoHojaCorriente->keys[i];
			nodoHojaCorriente->byteData[i + 1] = nodoHojaCorriente->byteData[i];
			i--;
		}
		nodoHojaCorriente->keys[i + 1] = clave;
		nodoHojaCorriente->byteData[i + 1] = dato;
		nodoHojaCorriente->keyMount++;
		nodoHojaCorriente->occupiedSpace += dato.getSize() + clave.getSize() + TreeConstraits::getControlSizeRecord();

		if (nodoHojaCorriente->isOverflow(keyTopSize)) {

			splitLeafNode(nodoHojaCorriente, clavePromocion, nuevoNodo);

			if (posicion >= nodoHojaCorriente->keyMount) {
				posicion -= nodoHojaCorriente->keyMount;
				nodoHojaCorriente = static_cast<LeafNode*> (*nuevoNodo);
			}
		}

		if (nuevoNodo && nodoHojaCorriente != *nuevoNodo && posicion == nodoHojaCorriente->keyMount - 1) {
			*clavePromocion = clave;
		}

		return true;
	}
}
Example #18
0
 // Read a DER encoded bytestring
 // =============================================================================================
 PkiPublicKey PkiPublicKey::fromDER(const ByteString& data)
 {
     UaByteArray uaByteArray;
     data.toSdk(uaByteArray);
     return PkiPublicKey(uaByteArray);
 }
void ReplicatedKeyspaceDB::AsyncOnAppend()
{
	Log_Trace();
	
	unsigned		nread;
	bool			ret;
	uint64_t		commandID;
	KeyspaceOp*		op;
	KeyspaceOp**	it;
	ByteString		value;
	Stopwatch		sw;

	value.Set(valueBuffer);
	Log_Trace("length: %d", value.length);
	
	numOps = 0;
	if (ownAppend)
		it = ops.Head();
	else
		it = NULL;
	
	commandID = 0;	
	while (true)
	{
		if (msg.Read(value, nread))
		{
			sw.Start();
			ret = Execute(transaction, paxosID, commandID);
			commandID++;
			sw.Stop();
			value.Advance(nread);
			numOps++;
			
			if (ownAppend)
			{
				op = *it;
				if (op->type == KeyspaceOp::DIRTY_GET ||
					op->type == KeyspaceOp::GET)
						ASSERT_FAIL();
				if ((op->type == KeyspaceOp::ADD ||
					 op->type == KeyspaceOp::TEST_AND_SET ||
					 op->type == KeyspaceOp::REMOVE) && ret)
						op->value.Set(wdata);
				op->status = ret;
				it = ops.Next(it);
			}
			
			if (value.length == 0)
				break;
		}
		else
		{
			Log_Trace("Failed parsing:");
			Log_Trace("%.*s", value.length, value.buffer);
			ASSERT_FAIL();
			break;
		}
	}
	
	Log_Trace("time spent in Execute(): %ld", sw.elapsed);
	Log_Trace("numOps = %u", numOps);
	Log_Trace("ops/sec = %f", (double)1000*numOps/sw.elapsed);
	
	IOProcessor::Complete(&onAppendComplete);
}
Example #20
0
// Seed the random pool
void OSSLRNG::seed(ByteString& seedData)
{
	RAND_seed(seedData.byte_str(), seedData.size());
}
Example #21
0
// Generate random data
bool OSSLRNG::generateRandom(ByteString& data, const size_t len)
{
	data.wipe(len);

	return RAND_bytes(&data[0], len);
}
Example #22
0
// Decryption functions
bool BotanRSA::decrypt(PrivateKey* privateKey, const ByteString& encryptedData,
		       ByteString& data, const AsymMech::Type padding)
{
	// Check if the private key is the right type
	if (!privateKey->isOfType(BotanRSAPrivateKey::type))
	{
		ERROR_MSG("Invalid key type supplied");

		return false;
	}

	std::string eme;

	switch (padding)
	{
		case AsymMech::RSA_PKCS:
			eme = "PKCS1v15";
			break;
		case AsymMech::RSA_PKCS_OAEP:
			eme = "EME1(SHA-160)";
			break;
		case AsymMech::RSA:
			eme = "Raw";
			break;
		default:
			ERROR_MSG("Invalid padding mechanism supplied (%i)", padding);

			return false;
	}

	BotanRSAPrivateKey* pk = (BotanRSAPrivateKey*) privateKey;
	Botan::RSA_PrivateKey* botanKey = pk->getBotanKey();

	if (!botanKey)
	{
		ERROR_MSG("Could not get the Botan private key");

		return false;
	}

	Botan::PK_Decryptor_EME* decryptor = NULL;
	try
	{
		decryptor = new Botan::PK_Decryptor_EME(*botanKey, eme);
	}
	catch (...)
	{
		ERROR_MSG("Could not create the decryptor token");

		return false;
	}

	// Perform the decryption operation
#if BOTAN_VERSION_MINOR == 11
	Botan::secure_vector<Botan::byte> decResult;
#else
	Botan::SecureVector<Botan::byte> decResult;
#endif
	try
	{
		decResult = decryptor->decrypt(encryptedData.const_byte_str(), encryptedData.size());
	}
	catch (...)
	{
		ERROR_MSG("Could not decrypt the data");

		delete decryptor;

		return false;
	}

	// Return the result
	if (padding == AsymMech::RSA)
	{
		// We compensate that Botan removes leading zeros
		int modSize = pk->getN().size();
		int decSize = decResult.size();
		data.resize(modSize);
#if BOTAN_VERSION_MINOR == 11
		memcpy(&data[0] + modSize - decSize, decResult.data(), decSize);
#else
		memcpy(&data[0] + modSize - decSize, decResult.begin(), decSize);
#endif
	}
	else
	{
		data.resize(decResult.size());
#if BOTAN_VERSION_MINOR == 11
		memcpy(&data[0], decResult.data(), decResult.size());
#else
		memcpy(&data[0], decResult.begin(), decResult.size());
#endif
	}

	delete decryptor;

	return true;
}
// Test that the large length of the child serial number causes
// CreateEncodedOCSPRequest to fail.
TEST_F(pkixocsp_CreateEncodedOCSPRequest, ChildCertLongSerialNumberTest)
{
  static const uint8_t UNSUPPORTED_LEN = 128; // must be larger than 127

  ByteString serialNumberString;
  // tag + length + value is 1 + 2 + UNSUPPORTED_LEN
  // Encoding the length takes two bytes: one byte to indicate that a
  // second byte follows, and the second byte to indicate the length.
  serialNumberString.push_back(0x80 + 1);
  serialNumberString.push_back(UNSUPPORTED_LEN);
  // value is 0x010000...00
  serialNumberString.push_back(0x01);
  for (size_t i = 1; i < UNSUPPORTED_LEN; ++i) {
    serialNumberString.push_back(0x00);
  }

  ByteString issuerDER;
  ByteString issuerSPKI;
  ASSERT_NO_FATAL_FAILURE(MakeIssuerCertIDComponents("CA", issuerDER,
                                                     issuerSPKI));

  Input issuer;
  ASSERT_EQ(Success, issuer.Init(issuerDER.data(), issuerDER.length()));

  Input spki;
  ASSERT_EQ(Success, spki.Init(issuerSPKI.data(), issuerSPKI.length()));

  Input serialNumber;
  ASSERT_EQ(Success, serialNumber.Init(serialNumberString.data(),
                                       serialNumberString.length()));

  uint8_t ocspRequest[OCSP_REQUEST_MAX_LENGTH];
  size_t ocspRequestLength;
  ASSERT_EQ(Result::ERROR_BAD_DER,
            CreateEncodedOCSPRequest(trustDomain,
                                     CertID(issuer, spki, serialNumber),
                                     ocspRequest, ocspRequestLength));
}
int luatpt_get_property(lua_State* l)
{
	ByteString prop = luaL_optstring(l, 1, "");
	int i = luaL_optint(l, 2, 0); //x coord or particle index, depending on arguments
	int y = luaL_optint(l, 3, -1);
	if (y!=-1 && y<YRES && y>=0 && i < XRES && i>=0)
	{
		int r = luacon_sim->pmap[y][i];
		if (!r)
		{
			r = luacon_sim->photons[y][i];
			if (!r)
			{
				if (!prop.compare("type"))
				{
					lua_pushinteger(l, 0);
					return 1;
				}
				return luaL_error(l, "Particle does not exist");
			}
		}
		i = ID(r);
	}
	else if (y != -1)
		return luaL_error(l, "Coordinates out of range (%d,%d)", i, y);
	if (i < 0 || i >= NPART)
		return luaL_error(l, "Invalid particle ID '%d'", i);

	if (luacon_sim->parts[i].type)
	{
		int tempinteger;
		float tempfloat;
		CommandInterface::FormatType format;
		int offset = luacon_ci->GetPropertyOffset(prop, format);

		if (offset == -1)
		{
			if (!prop.compare("id"))
			{
				lua_pushnumber(l, i);
				return 1;
			}
			else
				return luaL_error(l, "Invalid property");
		}
		switch(format)
		{
		case CommandInterface::FormatInt:
		case CommandInterface::FormatElement:
			tempinteger = *((int*)(((unsigned char*)&luacon_sim->parts[i])+offset));
			lua_pushnumber(l, tempinteger);
			break;
		case CommandInterface::FormatFloat:
			tempfloat = *((float*)(((unsigned char*)&luacon_sim->parts[i])+offset));
			lua_pushnumber(l, tempfloat);
			break;
		default:
			break;
		}
		return 1;
	}
	else if (!prop.compare("type"))
	{
		lua_pushinteger(l, 0);
		return 1;
	}
	return luaL_error(l, "Particle does not exist");
}
void BPlusTree::exportNode(ofstream& salida, Node* unNodo, int tabulacion,bool keyText,bool textContent) {

	if (unNodo->isLeaf()) {

		LeafNode *unNodoHoja = static_cast<LeafNode*> (unNodo);
		salida << endl;
		for(int i = 0 ; i < tabulacion ; i++)
			salida << "  ";

		salida << "Numero: " << unNodoHoja->number << "  Nivel: " << unNodoHoja->level << "  Cant.Elem: " << unNodoHoja->keyMount
			   << "  Esp.Libre: " << TreeConstraits::getEfectiveSizeNode() - unNodoHoja->occupiedSpace << "  Hoja.Sig: " << unNodoHoja->nextLeaf << endl;

		for (int posicion = 0; posicion < unNodoHoja->keyMount; ++posicion) {

			for(int i = 0 ; i < tabulacion + 4 ; i++)
						salida << "  ";

			salida << "(";

			Key unaClave = unNodoHoja->keys[posicion];
			if(keyText)
			{
				salida << unaClave.toString();
			}
			else
			{
				ByteString clave(unaClave.toString());
				salida << Utility::toString(clave.readAsInt(0));
			}

			salida << ";";
			ByteString unDato = unNodoHoja->byteData[posicion];
			if(textContent)
			{
				salida << unDato.toString();
			}
			else
			{
				salida << Utility::intToString(unDato.readAsInt(0));
			}

			salida << ")";

			salida << (unaClave.getSize() + unDato.getSize() + TreeConstraits::getControlSizeRecord()) << endl;
		}

		salida << endl;

	} else {

		InnerNode *unNodoInterior = static_cast<InnerNode*> (unNodo);
		salida << endl << endl;
		for(int i=0; i<tabulacion ; i++)
			salida << "  ";

		salida << "Numero: " << unNodoInterior->number << "  Nivel: " << unNodoInterior->level << "  Cant.Elem: " << unNodoInterior->keyMount
			   << "  Esp.Libre: " << TreeConstraits::getEfectiveSizeNode() - unNodoInterior->occupiedSpace << endl;

		for (int posicion = 0; posicion <= unNodoInterior->keyMount; ++posicion) {

			if (posicion < unNodoInterior->keyMount) {
				Key unaClave = unNodoInterior->keys[posicion];

				for(int i=0; i<(tabulacion+1) ; i++)
					salida << "  ";
				salida << "(";
				if(keyText)
				{
					salida << unaClave.toString();
				}
				else
				{
					ByteString clave(unaClave.toString());
					salida << Utility::toString(clave.readAsInt(0));
				}
				salida << ")";
				salida << unaClave.getSize();
				salida << "  ";
				salida << unNodoInterior->getSons()[posicion] << "   ";
			}
		}
		for (int posicion = 0; posicion <= unNodoInterior->keyMount; ++posicion) {
			Node *hijo = hidratateNode(unNodoInterior->sons[posicion]);
			exportNode(salida, hijo, tabulacion + 2,keyText,textContent);
			if (hijo)
				freeNodeMemory(hijo);
		}
		for(int i=0; i<tabulacion ; i++)
			salida << "  ";
		salida << endl;
	}
}
// Test that CreateEncodedOCSPRequest handles the longest serial number that
// it's required to support (i.e. 20 octets).
TEST_F(pkixocsp_CreateEncodedOCSPRequest, LongestSupportedSerialNumberTest)
{
  static const uint8_t LONGEST_REQUIRED_LEN = 20;

  ByteString serialNumberString;
  // tag + length + value is 1 + 1 + LONGEST_REQUIRED_LEN
  serialNumberString.push_back(der::INTEGER);
  serialNumberString.push_back(LONGEST_REQUIRED_LEN);
  serialNumberString.push_back(0x01);
  // value is 0x010000...00
  for (size_t i = 1; i < LONGEST_REQUIRED_LEN; ++i) {
    serialNumberString.push_back(0x00);
  }

  ByteString issuerDER;
  ByteString issuerSPKI;
  ASSERT_NO_FATAL_FAILURE(MakeIssuerCertIDComponents("CA", issuerDER,
                                                     issuerSPKI));

  Input issuer;
  ASSERT_EQ(Success, issuer.Init(issuerDER.data(), issuerDER.length()));

  Input spki;
  ASSERT_EQ(Success, spki.Init(issuerSPKI.data(), issuerSPKI.length()));

  Input serialNumber;
  ASSERT_EQ(Success, serialNumber.Init(serialNumberString.data(),
                                       serialNumberString.length()));

  uint8_t ocspRequest[OCSP_REQUEST_MAX_LENGTH];
  size_t ocspRequestLength;
  ASSERT_EQ(Success,
            CreateEncodedOCSPRequest(trustDomain,
                                     CertID(issuer, spki, serialNumber),
                                     ocspRequest, ocspRequestLength));
}
Example #27
0
// Seed the random pool
void BotanRNG::seed(ByteString& seedData)
{
	rng->add_entropy(seedData.byte_str(), seedData.size());
	rng->reseed(seedData.size());
}
Example #28
0
// Convert a ByteString to an OpenSSL NID
int OSSL::byteString2oid(const ByteString& byteString)
{
	const unsigned char *p = byteString.const_byte_str();
	return OBJ_obj2nid(d2i_ASN1_OBJECT(NULL, &p, byteString.size()));
}
Example #29
0
static bool decodeAttributeMap(std::map<CK_ATTRIBUTE_TYPE,OSAttribute>& map, const unsigned char *binary, size_t size)
{
	for (size_t pos = 0; pos < size; )
	{
		// finished?
		if (pos == size) break;

		CK_ATTRIBUTE_TYPE attrType;
		if (pos + sizeof(attrType) > size)
		{
			goto overrun;
		}
		memcpy(&attrType, binary + pos, sizeof(attrType));
		pos += sizeof(attrType);

		AttributeKind attrKind;
		if (pos + sizeof(AttributeKind) > size)
		{
			goto overrun;
		}
		memcpy(&attrKind, binary + pos, sizeof(attrKind));
		pos += sizeof(attrKind);

		// Verify using attributeKind()?

		switch (attrKind)
		{
			case akBoolean:
			{
				bool value;
				if (pos + sizeof(value) > size)
				{
					goto overrun;
				}
				memcpy(&value, binary + pos, sizeof(value));
				pos += sizeof(value);

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			case akInteger:
			{
				unsigned long value;
				if (pos + sizeof(value) > size)
				{
					goto overrun;
				}
				memcpy(&value, binary + pos, sizeof(value));
				pos += sizeof(value);

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			case akBinary:
			{
				ByteString value;
				unsigned long len;
				if (pos + sizeof(len) > size)
				{
					goto overrun;
				}
				memcpy(&len, binary + pos, sizeof(len));
				pos += sizeof(len);

				if (pos + len > size)
				{
					goto overrun;
				}
				value.resize(len);
				memcpy(&value[0], binary + pos, len);
				pos += len;

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			case akMechSet:
			{
				unsigned long len;
				if (pos + sizeof(len) > size)
				{
					goto overrun;
				}
				memcpy(&len, binary + pos, sizeof(len));
				pos += sizeof(len);

				if (pos + len > size)
				{
					goto overrun;
				}

				std::set<CK_MECHANISM_TYPE> value;
				if (!decodeMechanismTypeSet(value, binary + pos, len)) {
					return false;
				}
				pos += len;

				map.insert(std::pair<CK_ATTRIBUTE_TYPE,OSAttribute> (attrType, value));
			}
			break;

			default:
			ERROR_MSG("unsupported attribute kind in attribute map");

			return false;
		}
	}

	return true;

overrun:
	ERROR_MSG("attribute map template overrun");

	return false;
}
Example #30
0
// Verification functions
bool OSSLECDSA::verify(PublicKey* publicKey, const ByteString& originalData, const ByteString& signature, const std::string mechanism)
{
	std::string lowerMechanism;
	lowerMechanism.resize(mechanism.size());
	std::transform(mechanism.begin(), mechanism.end(), lowerMechanism.begin(), tolower);

	if (lowerMechanism.compare("ecdsa"))
	{
		ERROR_MSG("Invalid mechanism supplied (%s)", mechanism.c_str());
		return false;
	}

	// Check if the private key is the right type
	if (!publicKey->isOfType(OSSLECPublicKey::type))
	{
		ERROR_MSG("Invalid key type supplied");

		return false;
	}

	OSSLECPublicKey* pk = (OSSLECPublicKey*) publicKey;
	EC_KEY* eckey = pk->getOSSLKey();

	if (eckey == NULL)
	{
		ERROR_MSG("Could not get the OpenSSL public key");

		return false;
	}

	// Perform the verify operation
	size_t len = pk->getOrderLength();
	if (len == 0)
		return false;
	if (signature.size() != 2 * len)
		return false;
	ECDSA_SIG* sig = ECDSA_SIG_new();
	if (sig == NULL)
		return false;
	if (sig->r != NULL)
		BN_clear_free(sig->r);
	const unsigned char *s = signature.const_byte_str();
	sig->r = BN_bin2bn(s, len, NULL);
	if (sig->s != NULL)
		BN_clear_free(sig->s);
	sig->s = BN_bin2bn(s + len, len, NULL);
	if (sig->r == NULL || sig->s == NULL)
	{
		ECDSA_SIG_free(sig);
		return false;
	}
	int ret = ECDSA_do_verify(originalData.const_byte_str(), originalData.size(), sig, eckey);
	if (ret != 1)
	{
		if (ret < 0)
			ERROR_MSG("ECDSA verify failed (0x%08X)", ERR_get_error());

		ECDSA_SIG_free(sig);
		return false;
	}

	ECDSA_SIG_free(sig);
	return true;
}