// . have we added the meta list to our rdbs yet?
// . can not delete the actual meta list from syncdb until so
bool Syncdb::canDeleteMetaList ( uint32_t sid , uint64_t zid ) {
	// make the "c" key to see if we still need to add the meta list
	key128_t k = makeKey(0,0,1,0,0,sid,zid,1);
	// get it
	long nn = m_qt.getNode ( 0 , (char *)&k );
	// if "c" key is there, that means we need to add to our rdb still
	// so we can not delete it yet!
	if ( nn >= 0 ) return false;
	// get group we are in
	Host *group = g_hostdb.getMyShard();
	// . if we need to send some requests still can not delete
	// . number hosts in group
	long nh = g_hostdb.getNumHostsPerShard();
	// loop over our twins
	for ( long i = 0 ; i < nh ; i++ ) {
		// get host
		Host *h = &group[i];
		// skip if us
		if ( h == g_hostdb.m_myHost ) continue;
		// check the need to send req key now. the "a" key.
		k = makeKey(1,0,0,0,h->m_hostId,sid,zid,1);
		// get it
		nn = m_qt.getNode ( 0 , (char *)&k );
		// if there, we cannot delete it yet
		if ( nn >= 0 ) return false;
		// check the recv key now. the "b" key.
		k = makeKey(0,1,0,0,h->m_hostId,sid,zid,1);
		// get it
		nn = m_qt.getNode ( 0 , (char *)&k );
		// if there, we cannot delete it yet
		if ( nn >= 0 ) return false;
	}
	// i guess we can delete it, all keys are gone
	return true;
}
Exemplo n.º 2
0
int lineReader(char *line, HashTable *numbers){

	int key;
    int x;

	if(line[0] == 'i' || line[0] == 'I'){
			key = makeKey(&line[2]);
       		x = insertValue(key, numbers);
       		if(x == -1){
       			printf("duplicate\n");
       			return 0;
       		}else{
       			printf("inserted\n");
       			return 0;
       		}
    }else if(line[0] == 's' || line[0] == 'S'){
    		key = makeKey(&line[2]);
       		x = searchValue(key, numbers);
        	if(x == -1){
        		printf("absent\n");
       			return 0;
       		}else{
       			printf("present\n");
       			return 0;
       		}
    }else{
    		printf("error\n");
    		return 0;
    }
}
Exemplo n.º 3
0
    std::list<ModelPair> LocationModelManager::collectModelPairs(ModelId mid)
    {
        std::list<ModelPair> keys;
        LocationModel *model = at(mid);

        if(nullptr != model)
        {
            for(AgentId const aid : model->sources())
            {
                Agent *agent = mLevel->agentMan()->getAgent(aid);

                if(nullptr == agent)
                    continue;

                keys.push_back(makeKey(agent->locationModelId(), mid));
                keys.push_back(makeKey(mid, agent->locationModelId()));
            }

            for(AgentId const aid : model->destinations())
            {
                Agent *agent = mLevel->agentMan()->getAgent(aid);

                if(nullptr == agent)
                    continue;

                keys.push_back(makeKey(agent->locationModelId(), mid));
                keys.push_back(makeKey(mid, agent->locationModelId()));
            }
        }

        return keys;
    }
Exemplo n.º 4
0
int Core::pullHost(string hostname, string &ip_address, int& port, string &username, string &password, string &enable_password) {
    map<string,hosts_t>::iterator it;
    std::string key;

    key = makeKey(hostname, 22);
    it = hosts.find(key);
    
    if (it == hosts.end()) {
        return -1;
    }

    hosts_t * tmp_host = &(*it).second;
    ip_address = tmp_host->ip_address;
    port = tmp_host->port;
    username = tmp_host->username;
    password = tmp_host->password;

    if (!cisco_mode) return 0;

    key = makeKey(hostname, 0);
    it = hosts.find(key);
    if (it == hosts.end()) {
        return 0; // may be we don't need enable password
    }

    tmp_host = &(*it).second;
    enable_password = tmp_host->password;

    return 0;
}
Exemplo n.º 5
0
static void rijndaelVKKAT(FILE * fp, int keyLength)
{
        int i, j, r;
        BYTE block[4 * 4];
        BYTE keyMaterial[320];
        BYTE byteVal = (BYTE) '8';
        keyInstance keyInst;
        cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
        printf("Executing Variable-Key KAT (key %d): ", keyLength);
        fflush(stdout);
#endif                          /* ?TRACE_KAT_MCT */
        fprintf(fp, "\n" "==========\n" "\n" "KEYSIZE=%d\n" "\n", keyLength);
        fflush(fp);
        memset(block, 0, 16);
        blockPrint(fp, block, "PT");
        memset(keyMaterial, 0, sizeof(keyMaterial));
        memset(keyMaterial, '0', keyLength / 4);
        for (i = 0; i < keyLength; i++) {
                keyMaterial[i / 4] = byteVal;   /* set only the i-th bit of the i-th test key */
                r = makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
                if (TRUE != r) {
                        fprintf(stderr, "makeKey error %d\n", r);
                        exit(-1);
                }
                fprintf(fp, "\nI=%d\n", i + 1);
                fprintf(fp, "KEY=%s\n", keyMaterial);
                memset(block, 0, 16);
                r = cipherInit(&cipherInst, MODE_ECB, NULL);
                if (TRUE != r) {
                        fprintf(stderr, "cipherInit error %d\n", r);
                        exit(-1);
                }
                r = blockEncrypt(&cipherInst, &keyInst, block, 128, block);
                if (128 != r) {
                        fprintf(stderr, "blockEncrypt error %d\n", r);
                        exit(-1);
                }
                blockPrint(fp, block, "CT");
                /* now check decryption: */
                makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
                blockDecrypt(&cipherInst, &keyInst, block, 128, block);
                for (j = 0; j < 16; j++) {
                        assert(block[j] == 0);
                }
                /* undo changes for the next iteration: */
                keyMaterial[i / 4] = (BYTE) '0';
                byteVal =
                    (byteVal == '8') ? '4' :
                    (byteVal == '4') ? '2' : (byteVal == '2') ? '1' :
                    /*      (byteVal == '1') */ '8';
        }
        assert(byteVal == (BYTE) '8');

#ifdef TRACE_KAT_MCT
        printf(" done.\n");
#endif                          /* ?TRACE_KAT_MCT */
}                               /* rijndaelVKKAT */
Exemplo n.º 6
0
void PhraseLVI::setText( int column, const QString& text )
{
    if ( column == SourceTextShown ) {
	sourceTextKey = makeKey( text );
    } else if ( column == TargetTextShown ) {
	targetTextKey = makeKey( text );
    }
    QListViewItem::setText( column, text );
}
Exemplo n.º 7
0
static void rijndaelIVKAT (FILE *fp, int keyLength) {
	int i;
	BYTE pt[4*4], ct[4*4];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;
	char format[10];
#ifdef TRACE_KAT_MCT
	printf ("Executing Intermediate value KAT (key %d): ", keyLength);
	fflush (stdout);
#endif /* ?TRACE_KAT_MCT */

	fprintf(fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n",
		keyLength);
	fflush(fp);
	memset(keyMaterial, 0, sizeof (keyMaterial));
	for (i = 0; i < keyLength/8; i++) {
		sprintf(&keyMaterial[2*i], "%02X", i);
	}
	fprintf(fp, "KEY=%s\n", keyMaterial);
	
	for (i = 0; i < 16; i++) {
		pt[i] = i;
	}
	
	fprintf(fp, "\nIntermediate Ciphertext Values (Encryption)\n\n");
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	blockPrint(fp, pt, "PT");
	cipherInit(&cipherInst, MODE_ECB, NULL);
	for(i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, i);
		sprintf(format, "CT%d", i);
		blockPrint(fp, ct, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, pt, 16, ct, keyInst.Nr);
	blockPrint(fp, ct, "CT");
	
	fprintf(fp, "\nIntermediate Ciphertext Values (Decryption)\n\n");
	makeKey(&keyInst, DIR_DECRYPT, keyLength, keyMaterial);
	blockPrint(fp, ct, "CT");
	cipherInit(&cipherInst, MODE_ECB, NULL);
	for(i = 1; i < keyInst.Nr; i++) {
		cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, i);
		sprintf(format, "PT%d", i);
		blockPrint(fp, pt, format);
	}
	cipherUpdateRounds(&cipherInst, &keyInst, ct, 16, pt, keyInst.Nr);
	blockPrint(fp, pt, "PT");
	
#ifdef TRACE_KAT_MCT
	printf(" done.\n");
#endif 
}
// . ***** META LIST DELETE LOOP *****
// . scan for meta lists to remove from syncdb
// . check every D KEY
// . must NOT have any "need to send request" keys (a bit set)
// . must NOT have any "need to recv request" keys (b bit set)
// . must NOT have our "need to add" key (c bit set)
void Syncdb::loop3 ( ) {
	// . loop over the meta lists we need to delete
	// . these are "d" keys
	// . use a "tid" of 0
	key128_t sk = makeKey ( 0,0,0,1,0,0,0,0 );
	key128_t ek = makeKey ( 0,0,0,1,0,0xffffffff,0xffffffffffffffffLL,1 );
	// get the first node in sequence, if any
	long nn = m_qt.getNextNode ( 0 , (char *)&sk );
	// do the loop
	for ( ; nn >= 0 ; nn = m_qt.getNextNode ( nn ) ) {
		// breathe
		QUICKPOLL ( MAX_NICENESS );
		// get key
		key128_t k = *(key128_t *)m_qt.getKey ( nn );
		// stop when we hit the end
		if ( k > ek ) break;
		// get zid
		uint64_t zid = getZid ( &k );
		// get sid
		uint32_t sid = getSid ( &k );
		// have we sent/recvd all checkoff requests required? have
		// we added the meta list? if so, we can nuke it from syncdb
		if ( ! canDeleteMetaList ( sid, zid ) ) {
			// no use banging away at this sid any more since we
			// are missing another action for this one
			sid++;
			// find the key of the FIRST meta list we need to add
			// for this new senderId, "sid"
			key128_t nk = makeKey ( 0,0,0,1,0,sid,0,0 );
			// undo the m_qt.getNextNode(nn) we call in for loop
			nn = m_qt.getPrevNode ( 0 , (char *)&nk );
			// sanity check
			if ( nn < 0 ) { char *xx=NULL;*xx=0; }
			// get next key from this new sid
			continue;
		}
		// . make the negative key for syncdb
		// . it just uses a negative "c" key, with a tid of 0
		key128_t dk = makeKey ( 0,0,1,0,0,sid,zid,0);
		// . add it to syncdb to signifiy a delete
		// . this returns false and sets g_errno on error
		if(!m_rdb.addRecord((collnum_t)0,(char *)&dk,NULL,0,
				    MAX_NICENESS)) return;
		// delete it from quick tree now that we added the negative
		// key successfully to syncdb
		long dn = m_qt.getNode ( 0, (char *)&k );
		// must be there!
		if ( ! dn ) { char *xx=NULL;*xx=0; }
		// nuke it
		m_qt.deleteNode ( dn , true );
	}
	// . success
	// . do not recall until big loop completes a round
	m_calledLoop3 = true;
}
void Syncdb::loopReset() {
	m_outstanding = false;
	// reset flags
	m_calledLoop1 = false;
	m_calledLoop2 = false;
	m_calledLoop3 = false;
	m_calledLoop4 = false;
	m_calledLoop5 = false;
	m_syncKey     = makeKey(0,1,0,0,0,0,0,0);
	m_addCount    = 0;
	// if done calling loop5(), reset this
	m_nextk = makeKey ( 1,0,0,0,0,0,0,0 );
}
Exemplo n.º 10
0
void
AES_SetKey(AES_Struct *aes, const unsigned char *key, unsigned int key_len) {
	unsigned char hexkey[64];

	if (key_len != 16 && key_len != 24 && key_len != 32) {
		fprintf(stderr, "AES_SetKey: key must be 128, 192 or 256 bits.\n");
		abort();
	}

	str_to_hex(key, key_len, hexkey);

	makeKey(&aes->encrypt_key, DIR_ENCRYPT, key_len * 8, (char *) hexkey);
	makeKey(&aes->decrypt_key, DIR_DECRYPT, key_len * 8, (char *) hexkey);
	aes->key_gen = 1;
}
void mgcStatusTblAdd(struct mgcStatusTbl *mst, unsigned imageId,
                     struct mgcStatusType *status, char *acc,
                     char *organism, char* geneName)
/* Add an entry to the table. acc maybe NULL */
{
struct mgcStatus *ms;
lmAllocVar(mst->lm, ms);
ms->imageId = imageId;
ms->status = status;
if ((acc != NULL) && (acc[0] != '\0'))
    ms->acc = lmCloneString(mst->lm, acc);
else
    ms->acc = NULL;
safef(ms->organism, sizeof(ms->organism), "%s", organism);
if ((geneName != NULL) && (geneName[0] != '\0'))
    ms->geneName = lmCloneString(mst->lm, geneName);
else
    ms->geneName = NULL;
if (mst->imageIdHash != NULL)
    {
    char key[64];
    makeKey(imageId, key);
    hashAdd(mst->imageIdHash, key, ms);
    }
if ((mst->accHash != NULL) && (acc != NULL))
    hashAdd(mst->accHash, ms->acc, ms);

}
Exemplo n.º 12
0
BOOL SetRegistryDWordArray(HKEY root, const CString & var, CDWordArray & data)
    {
     CString path;
     
     path.LoadString(IDS_PROGRAM_ROOT);
     CString name;
     makePath(path, var, name);

     HKEY key;
     LONG result = makeKey(root,
     			        path,
			        &key);
     if(result != ERROR_SUCCESS)
	{ /* save it */
	 ::SetLastError((DWORD)result);
	 return FALSE;
	} /* save it */
     
     result = ::RegSetValueEx(key, name, 0, REG_BINARY, (LPBYTE)&(data[0]), 
     				data.GetSize() * sizeof(DWORD));
     ::RegCloseKey(key);
     if(result != ERROR_SUCCESS)
	::SetLastError((DWORD)result);
     
     return result == ERROR_SUCCESS;

    }
// . have we sent all the checkoff requests (and got replies) for this sid/zid?
// . we cannot add a meta list until we have
bool Syncdb::sentAllCheckoffRequests ( uint32_t sid , uint64_t zid ) {
	// get group we are in
	Host *group = g_hostdb.getMyShard();
	// number hosts in group
	long nh = g_hostdb.getNumHostsPerShard();
	// loop over our twins
	for ( long i = 0 ; i < nh ; i++ ) {
		// get host
		Host *h = &group[i];
		// skip if us
		if ( h == g_hostdb.m_myHost ) continue;
		// skip if dead
		if ( g_hostdb.isDead ( h ) ) continue;
		// make the key
		key128_t k = makeKey(1,0,0,0,h->m_hostId,sid,zid,1);
		// get it
		long nn = m_qt.getNode ( 0 , (char *)&k );
		// if it is there, that means we have yet to get a reply
		// for this checkoff request! because once we get a successful
		// reply for it, we delete it from quick tree
		if ( nn >= 0 ) return false;
	}
	// i guess we are good to go!
	return true;
}
Exemplo n.º 14
0
// =======================================================
// =======================================================
int INIReader::valueHandler(void* user, const char* section, const char* name,
                            const char* value)
{
  INIReader* reader = (INIReader*)user;
  reader->_values[makeKey(section, name)] = value;
  return 1;
}
Exemplo n.º 15
0
void testObj::test<3>(void)
{
  const char text[] = "alice has a cypher";
  assert( (sizeof(text) < Aes256::keySize()) && "test text is too long" );

  // copy text to vector
  Algo::Data data;
  for(const char* str=text; *str!=0; ++str)
    data.push_back(*str);

  // encrypt
  api_.encrypt(data);

  // check if it is not plaintext
  {
    std::string tmp;
    copy( data.begin(), data.end(), std::back_insert_iterator<std::string>(tmp) );
    ensure("plaintext detected!", tmp.c_str()!=std::string(text) ); // NOTE: tmp has trailing '0' that makes != fail to detect difference
  }

  // decrypt
  Aes256 dec( makeKey() );
  dec.decrypt(data);

  // check decrypted message
  {
    std::string tmp;
    copy( data.begin(), data.end(), std::back_insert_iterator<std::string>(tmp) );
    ensure_equals("decryption error", tmp.c_str(), std::string(text) ); // NOTE: tmp has trailing '0' that makes != fail to detect difference
  }
}
//////////////////////////////////////////////////////////////////////
// Checks if the goals given as parameter have not already been 
//proven unsatisfiable
//////////////////////////////////////////////////////////////////////
bool MemoizationLevel::isNoGood(IntVector &ivGoals)
{
	string sKey=makeKey(ivGoals);
	bool bRes = (ivmNoGoods.find(sKey) != ivmNoGoods.end());

	return bRes;
}
Exemplo n.º 17
0
 void
 SensorArray::addSensor(unsigned thePortId, unsigned theControllerId, unsigned theBitNumber,
                        const asl::Vector2i & theCoordinate)
 {
     unsigned key = makeKey(thePortId, theControllerId, theBitNumber);
     _mySensorMap[key] = theCoordinate;
 }
Exemplo n.º 18
0
    void getRooms(AbstractRoomVisitor &stream, ParseEvent &event_) override
    {
        const auto &event = event_;

        assert(event.size() == 3);
        const MaskFlags mask = getKeyMask(event);

        if (!isMatchedByTree(mask))
            return;

        auto tmp = event.clone();
        tmp.reset();

        auto key = makeKey(tmp, mask, m_useVerboseKeys);

        Secondary &thislevel = m_secondary[mask];
        SV &homes = thislevel[key];
        for (const PV &home : homes) {
            if (home != nullptr) {
                home->forEach(stream);
            }
        }

        return;
    }
Exemplo n.º 19
0
void * Win32SharedMemory::open(size_t key, size_t size)
{
    handle_ = OpenFileMapping(FILE_MAP_ALL_ACCESS,   // read/write access
                              FALSE,                 // do not inherit the name
                              makeKey(key).c_str()); // name of mapping object

    if(handle_ == NULL) {
        fprintf(stderr, TEXT("Could not open file mapping object (%d).\n"), GetLastError());
        return NULL;
    }

    void * mem = MapViewOfFile(handle_, // handle to map object
                               FILE_MAP_ALL_ACCESS,  // read/write permission
                               0,
                               0,
                               size);

    if(mem == NULL) {
        fprintf(stderr, "Could not map view of file (%d).\n", GetLastError());
        CloseHandle(handle_);
        return NULL;
    }

    return mem;
}
Exemplo n.º 20
0
void * Win32SharedMemory::create(size_t key, size_t size)
{
    handle_ = CreateFileMapping(INVALID_HANDLE_VALUE,    // use paging file
                                NULL,                    // default security
                                PAGE_READWRITE,          // read/write access
                                0,                       // maximum object size (high-order DWORD)
                                size,                    // maximum object size (low-order DWORD)
                                makeKey(key).c_str());   // name of mapping object

    if(handle_ == NULL) {
        fprintf(stderr, TEXT("Could not create file mapping object (%d).\n"), GetLastError());
        return NULL;
    }

    void * mem = MapViewOfFile(handle_,   // handle to map object
                               FILE_MAP_ALL_ACCESS, // read/write permission
                               0,
                               0,
                               size);

    if(mem == NULL) {
        fprintf(stderr, TEXT("Could not map view of file (%d).\n"), GetLastError());
        CloseHandle(handle_);
        return NULL;
    }

    return mem;
}
Exemplo n.º 21
0
CStringArray * EnumRegistryKeys(HKEY root, const CString & group)
    {
     CString path;

     CStringArray * keys;
     TCHAR itemName[512];

     path.LoadString(IDS_PROGRAM_ROOT);

     path += _T("\\");
     path += group;


     HKEY key;

     LONG result = makeKey(root, path, &key);
     if(result != ERROR_SUCCESS)
	return NULL;

     keys = new CStringArray;
     DWORD i = 0;
     while(TRUE) //lint -e716
        { /* loop */
	 result = ::RegEnumKey(key, i, itemName, sizeof(itemName)/sizeof(TCHAR));
	 if(result != ERROR_SUCCESS)
	    break;
         // we have a valid key name
	 keys->SetAtGrow(i, itemName);
	 i++;
	} /* loop */

     ::RegCloseKey(key);
     return keys;
    }
Exemplo n.º 22
0
void QWSSharedMemory::detach()
{
#ifndef QT_POSIX_IPC
    if (shmBase && shmBase != (void*)-1)
        shmdt(shmBase);
#else
    if (shmBase && shmBase != (void*)-1)
        munmap(shmBase, shmSize);
    if (hand > 0) {
        // get the number of current attachments
        int shm_nattch = 0;
        QT_STATBUF st;
        if (QT_FSTAT(hand, &st) == 0) {
            // subtract 2 from linkcount: one for our own open and one for the dir entry
            shm_nattch = st.st_nlink - 2;
        }
        qt_safe_close(hand);
        // if there are no attachments then unlink the shared memory
        if (shm_nattch == 0) {
            QByteArray shmName = makeKey(shmId);
            shm_unlink(shmName.constData());
        }
    }
#endif
    shmBase = 0;
    shmSize = 0;
    shmId = -1;
}
Exemplo n.º 23
0
static void rijndaelVTKAT(FILE *fp, int keyLength) {
	int i;
	BYTE block[4*4];
	BYTE keyMaterial[320];
	keyInstance keyInst;
	cipherInstance cipherInst;

#ifdef TRACE_KAT_MCT
	printf("Executing Variable-Text KAT (key %d): ", keyLength);
	fflush(stdout);
#endif /* ?TRACE_KAT_MCT */
	fprintf(fp,
		"\n"
		"==========\n"
		"\n"
		"KEYSIZE=%d\n"
		"\n", keyLength);
	fflush(fp);
	memset(keyMaterial, 0, sizeof (keyMaterial));
	memset(keyMaterial, '0', keyLength/4);
	makeKey(&keyInst, DIR_ENCRYPT, keyLength, keyMaterial);
	fprintf(fp, "KEY=%s\n", keyMaterial);
	for (i = 0; i < 128; i++) {
		memset(block, 0, 16);
		block[i/8] |= 1 << (7 - i%8); /* set only the i-th bit of the i-th test block */
		fprintf (fp, "\nI=%d\n", i+1);
		blockPrint(fp, block, "PT");
		cipherInit(&cipherInst, MODE_ECB, NULL);
		blockEncrypt(&cipherInst, &keyInst, block, 128, block);
		blockPrint(fp, block, "CT");
	}
#ifdef TRACE_KAT_MCT
	printf(" done.\n");
#endif /* ?TRACE_KAT_MCT */
}
Exemplo n.º 24
0
FileLineInfo
FileLineInfoMap::getInfo(const std::string & key0,
                         const std::string & key1,
                         const std::string & key2) const
{
  return getInfo(makeKey(key0, key1, key2));
}
const Graphics::TFont* TCustomFontsCache::Get(const TCustomFont& font) {
    const Key key = makeKey(font);
    if (isLoaded(key) == true) {
        return loadedFonts.at(key).get();
    } else {
        return load(font);
    }
}
Exemplo n.º 26
0
void
FileLineInfoMap::addInfo(const std::string & key0,
                         const std::string & key1,
                         const std::string & file,
                         int line)
{
  addInfo(makeKey(key0, key1), file, line);
}
Exemplo n.º 27
0
int TwoFishCrypt(
   int direction, /* 1=encrypt or 0=decrypt */
   int keySize,
   const char *passwd,
   const struct CryptData *data_in,
   struct CryptData *data_out
   )
{
   keyInstance    ki;         /* key information, including tables */
   cipherInstance ci;         /* keeps mode (ECB, CBC) and IV */
   int  i;
   int pwLen, result;
   int blkCount = (data_in->len+1)/(BLOCK_SIZE/8) + 1;
   int byteCnt = (BLOCK_SIZE/8) * blkCount;

   BYTE * input = (BYTE *) calloc(byteCnt,1);
   BYTE * output = (BYTE *) calloc(byteCnt,1);
   memcpy(input, data_in->data, byteCnt);

   if ( !makeKey(&ki,DIR_ENCRYPT,keySize,NULL) )
   {
      free(input);
      free(output);
      return 0;
   }
   if ( !cipherInit(&ci,MODE_ECB,NULL) )
   {
      free(input);
      free(output);
      return 0;
   }

   /* Set key bits from password. */
   pwLen = strlen(passwd);
   for (i=0;i<keySize/32;i++)   /* select key bits */
   {
      ki.key32[i] = (i < pwLen) ? passwd[i] : 0;
      ki.key32[i] ^= passwd[0];
   }
   reKey(&ki);

   /* encrypt the bytes */
   result = direction ? blockEncrypt(&ci, &ki, input, byteCnt*8, output)
                      : blockDecrypt(&ci, &ki, input, byteCnt*8, output);

   if(result == byteCnt*8)
   {
      data_out->data = (BYTE *) malloc(byteCnt);
      memcpy(data_out->data, output, byteCnt);
      data_out->len = byteCnt;
      free(input);
      free(output);
      return 1;
   }
   free(input);
   free(output);
   return 0;
}
Exemplo n.º 28
0
bool QWSSharedMemory::create(int size)
{
    if (shmId != -1)
        detach();

#ifndef QT_POSIX_IPC
    shmId = shmget(IPC_PRIVATE, size, IPC_CREAT | 0600);
#else
    // ### generate really unique IDs
    shmId = (getpid() << 16) + (localUniqueId.fetchAndAddRelaxed(1) % ushort(-1));
    QByteArray shmName = makeKey(shmId);
    EINTR_LOOP(hand, shm_open(shmName.constData(), O_RDWR | O_CREAT, 0660));
    if (hand != -1) {
        // the size may only be set once; ignore errors
        int ret;
        EINTR_LOOP(ret, ftruncate(hand, size));
        if (ret == -1)
            shmId = -1;
    } else {
        shmId = -1;
    }
#endif
    if (shmId == -1) {
#ifdef QT_SHM_DEBUG
        perror("QWSSharedMemory::create():");
        qWarning("Error allocating shared memory of size %d", size);
#endif
        detach();
        return false;
    }

#ifndef QT_POSIX_IPC
    shmBase = shmat(shmId, 0, 0);
    // On Linux, it is possible to attach a shared memory segment even if it
    // is already marked to be deleted. However, POSIX.1-2001 does not specify
    // this behaviour and many other implementations do not support it.
    shmctl(shmId, IPC_RMID, 0);
#else
    // grab the size
    QT_STATBUF st;
    if (QT_FSTAT(hand, &st) != -1) {
        shmSize = st.st_size;
        // grab the memory
        shmBase = mmap(0, shmSize, PROT_READ | PROT_WRITE, MAP_SHARED, hand, 0);
    }
#endif
    if (shmBase == (void*)-1 || !shmBase) {
#ifdef QT_SHM_DEBUG
        perror("QWSSharedMemory::create():");
        qWarning("Error attaching to shared memory id %d", shmId);
#endif
        detach();
        return false;
    }

    return true;
}
//////////////////////////////////////////////////////////////////////
// Adds a given set of goals as not satisfiable in the memoization
//level
//////////////////////////////////////////////////////////////////////
void MemoizationLevel::addNoGood(IntVector &ivGoals)
{
	string sKey=makeKey(ivGoals);

	if(ivmNoGoods.find(sKey) == ivmNoGoods.end())
	{
		ivmNoGoods[sKey]=true;
	}
}
Exemplo n.º 30
0
void TokenDatabase::generateKey(const Context &context,
	const AccessCredentials *cred, const AclEntryPrototype *owner,
	CSSM_KEYUSE pubUsage, CSSM_KEYATTR_FLAGS pubAttrs,
	CSSM_KEYUSE privUsage, CSSM_KEYATTR_FLAGS privAttrs,
    RefPointer<Key> &publicKey, RefPointer<Key> &privateKey)
{
	Access access(token());
	TRY
	GUARD
	KeyHandle hPrivate, hPublic;
	CssmKey *privKey, *pubKey;
	access().generateKey(context, cred, owner,
		pubUsage, modattrs(pubAttrs), privUsage, modattrs(privAttrs),
		hPublic, pubKey, hPrivate, privKey);
	publicKey = makeKey(hPublic, pubKey, 0, owner);
	privateKey = makeKey(hPrivate, privKey, 0, owner);
	DONE
}