Esempio n. 1
0
int main(){

	struct dictionary *d;
	int i;
	d = dict_new(1,0);
	int min;
	int nums[7];
	int keys[7];
	
	keys[0] = 9;
	nums[0] = 14; 
	
	keys[1] = 4;
	nums[1] = 7; 
	
	keys[2] = 12;
	nums[2] = 5; 
	
	keys[3] = 0;
	nums[3] = 15; 
	
	keys[4] = 2;
	nums[4] = 3; 
	
	keys[5] = 14;
	nums[5] = 4; 
	
	keys[6] = 5;
	nums[6] = 2; 
	
	printf("new\n");
	
	//~ printHash(d);
		
	for(i = 0; i < 7; i++){
		//~ printf("Inserting %d...\n",nums[i]);
		dict_set(d,keys[i],nums[i]);
		//~ printHash(d);
	}
	
	printHash(d);
	
	dict_set(d,2,8);
	printf("set key 2 con 8\n");
	printf("get key 2 = %d\n",dict_get(d,2));
	
	printf("delete key 2\n");
	dict_delete(d,2);
	printHash(d);
	
	printf("delete key 9\n");
	dict_delete(d,9);
	printHash(d);
	
	dict_free(d);


}
Esempio n. 2
0
int main(void) {

	int i;
	HashTable H = InitTalbe(5);
    for(i=0;i<5;i++)
    	Insert(i,H);
    printHash(H);
    Insert(20,H);
    printHash(H);
	return EXIT_SUCCESS;
}
Esempio n. 3
0
int genPrivateKey(argMap map) {

	unsigned char *phrase = getArg("phrase", NULL, map);

	unsigned char hash[SHA256_DIGEST_LENGTH];

	if (phrase != NULL) {
		printf("Generating private key\n\n");
		printf("Pass phrase %s\n\n", phrase);

		genRepeatSHA256(phrase, strlen((signed char*) phrase), hash, 1024*1024);
	} else {
		printf("Generating random private key\n\n");

		if (RAND_bytes(hash, SHA256_DIGEST_LENGTH) == 0) {
			fprintf(stderr, "Error: random number generation failed\n");
			return 0;
		}
	}

	printf("Private key is ");
	printHash(hash, 32);
	printf("\n");

	return 1;

}
Esempio n. 4
0
void doAll(struct a_NODE * node)
{
	printNode(node);
	semanticEvaluation(node);
	printTac(generateTac(node));
	printHash();
	//generateTac(node);
}
Esempio n. 5
0
void LTable_Print(LTable* lt)
{
	for (u32 i = 0; i < lt->n_rows; i++)
	{
		printHash(CHASH(i), lt->l_hash);
		printf(" ");
		printString(CSTR(i), lt->l_string);
		printf("\n");
	}
}
Esempio n. 6
0
/*
 *
 * name: main
 *
 * Receives information from the user of the input and output files, and then
 * makes appropriate calls.
 *
 * @param	argc	the number of arguments passed (including the program)
 * @param	argv	the argument array of the program call
 * @return	error code
 */
int main(int argc, char** argv){
	line current;
	sourceContainer source;
	source.current = &current;

	char input[MAX_FILE_LEN];
	int i;
	token tokenList[MAX_TOKENS];

	// The user can pass a parameter to the program for the file name.
	// If no parameter is given, the program will ask explicitly.
	if(argc == 2){
		strcpy(input, argv[1]);
	}
	else{
		printf("\n Name of your input file (%d characters max): ", MAX_FILE_LEN);
		scanf("%s", input);
	}
	source.infile = fopen(input, "r");

	if(source.infile == NULL){
		printf("Could not open input file!\n");
		exit(1);
	}

	// prepare and build the token table
	for(i=0;i<HASH_TABLE_SIZE;i++){
		source.hashTable[i] = NULL;
		source.symbolTable[i] = NULL;
	}

	readTokens(tokenList, "tokens");
	buildHashes(source.hashTable, tokenList);

	source.current->scanIndex = 0;
	source.current->lineNumber = 0;
	source.current->atEOF = 0;
	memset(source.current->line, '\0', MAX_LINE_LEN);


	// parse the source
	if(prog(&source)){
		printf("\n\nParse successful!\n");
	}
	else{
		while(!source.current->atEOF){
			getLine(source.current, source.infile);
		}
		printf("\n\nParse failure!\n");
	}

	printf("\nSymbol table:\n");
	printHash(source.symbolTable);
	return 0;
}
// A function to show Menu D3 question.
void displayMenuD3(void)
{
    printHeader("D3. Rainfall database manager - Manage Rainfall category.");
    puts("Please select an option:");
    puts("1. Add a Rainfall category.");
    puts("2. Rename a Rainfall category.");
    puts("3. Remove a Rainfall category.");
    puts("4. Reset to factory default.");
    puts("5. Go back to Rainfall database manager menu.");
    printHash();
}
Esempio n. 8
0
int main() {
    
    char * buf1 = "The quick brown fox jumps over the lazy dog";
    char digest[32];

    int len = strlen(buf1);
    void * result = sha256_buffer(buf1, len, (void*)digest);

    printf("str=[%s] len=%d result=%p digest=%p\n", buf1, strlen(buf1), result, digest);
    printHash(digest);

    printf("\n");

    char * buf2="The quick brown fox jumps over the lazy dogThe quick brown fox jumps over the lazy dog";
    len = strlen(buf2);
    result = sha256_buffer(buf2, len, (void*)digest);

    printf("str=[%s] len=%d result=%p digest=%p\n", buf2, strlen(buf2), result, digest);
    printHash(digest);
}
Esempio n. 9
0
int Manager(HashTablePtr H){
    int choice;
    printf("***********************************\n"
           "*        Enter your choice        *\n"
           "*        1 to insert a user       *\n"
           "*        2 to delete a user       *\n"
           "*        3 to print Userlist      *\n"
           "*        4 to end                 *\n"
           "***********************************\n");
    printf("your choice:\n");
    if(!scanf("%d",&choice)){
        printf("input error!!!\n");
        exit(1);
    }

    while(choice != 4) {
        switch (choice) {
            case 1:
                Read(H);
                InsertUser(H);
                Write(H);
                break;
            case 2:
                Read(H);
                DeleteUser(H);
                Write(H);
                break;
            case 3:
                Read(H);
                printHash(H);
                break;
            default:
                printf("Invalid choice!!!\n");
                break;
        }
        printf("***********************************\n"
               "*        Enter your choice        *\n"
               "*        1 to insert a user       *\n"
               "*        2 to delete a user       *\n"
               "*        3 to print Userlist      *\n"
               "*        4 to end                 *\n"
               "***********************************\n");
        printf("your choice:\n");
        if(!scanf("%d",&choice)){
            printf("input error!!!\n");
            exit(1);
        }
    }
}
Esempio n. 10
0
int main()
{
	FILE *file;
	file = fopen("txt.txt", "r");
	while(!feof(file))
	{
		char string[12];
		fscanf(file, "%s", string);
		addHash(string);
	}
	printHash();
	delHash();
	std :: cin.get();
	return 0;
}
Esempio n. 11
0
void setup()
{
    printf("Test: FIPS 180-2 B.1\n");
    printf("Expect:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad\n");
    printf("Result:");
    Sha256Class sha;
    sha.init();
    uint32_t value = 0x1010101;
    sha.write('a');    
    sha.write('b');
    sha.write('c');
    uint8_t *ans = sha.result();
    printHash(ans);
    printf("\n");

}
Esempio n. 12
0
int crack_password_permutations(uint8_t* hash_ptr, int current_len, char* solution, int ends_with) {

   sha1nfo current_hash;
   uint8_t *current_hash_ptr;
   char    current_pw[100];
   uint8_t current_idxs[100]; // index into charset
   int i;

   // initialize
   for (i = 0; i < 100; i++) {
      current_pw[i] = 0;
      current_idxs[i] = 0;
   }

   for (i = 0; i < current_len; i++) {
      current_pw[0] = charset[0];
   }
   
   current_pw[current_len-1] = charset[ends_with];
   //if (my_id == id)
    //  printf("start: %s\n", current_pw);

   do { // loops over password space for given password length
      //printf("%s\n", current_pw);
      // hash current password attempt
      sha1_init(&current_hash);
      sha1_write(&current_hash, current_pw, strlen(current_pw));
      current_hash_ptr = sha1_result(&current_hash);

      // check if equal to hash we are cracking
      if (strncmp((char *)hash_ptr, (char *)current_hash_ptr, HASH_LENGTH) == 0) {

         strncpy(solution, current_pw, current_len);

         printf("found a password with a matching hash!\n");
         printHash(current_hash_ptr);
         printf("password is: %s\n", current_pw);

         return 1;
      }
   } while (next_password(current_pw, current_idxs, current_len - 1));

   return 0;
}
// A function to show menu E.
void displayMenuE(int* menuCount)
{
	int i;
	int expectedRainfallCategoryListCount = rainfallCategoryListCount();

	printHeader("E. Display the highest and lowest average rainfall.");
	printf("Please select the category list from options 1 to %d that you want to display.\n", expectedRainfallCategoryListCount);

	*menuCount = 1;

	for (i = 0; i < expectedRainfallCategoryListCount; i++)
	{
		printf("%d. %s\n", *menuCount, rainfallCategoryListGetItem(i));
		*menuCount = *menuCount + 1;
	}

	printf("%d. Go back to main menu.\n", *menuCount);
	printHash();
}
Esempio n. 14
0
int newPacketGET(Packet *pkt, queue *getQueue)
{
  int ret = 0;
  uint8_t numHash = getPacketNumHash(pkt);
  int i, idx;
  uint8_t *hash;
  for(i = 0; i < numHash; i++) {
    hash = getPacketHash(pkt, i);
    printHash(hash);
    idx = searchHash(hash, &getChunk, -1);
    printf("idx %d hashSeq %d getState %d\n", idx, getChunk.list[idx].seq, getChunk.list[idx].fetchState);
    //Only GET when chunk hasn't been fetched
    if(idx >= 0 && getChunk.list[idx].fetchState == 0) {
      printf("geting chunk %d\n",getChunk.list[idx].seq);
      Packet *thisObj = newPacketSingleGET(hash);
      enqueue(getQueue, (void *)thisObj);
      ret = 1;
    }
  }
  return ret;
}
Esempio n. 15
0
/* ===== process =====
    This function presents the user with the menu.
    Pre     hash, list, tree
    Post    nothing
 */
void process (HASH *hash, D_LIST *list, BST_TREE *tree)
{
    //	Local Definitions
	char choice;
	CAR car;
    
    //	Statements
	do
    {
	    choice = getChoice ();
        
	    switch (choice)
        {
	        case 'P': printHash(hash);
                printLinkedList(list);
                printManager(tree);
                break;
			case 'R': printIndentedBST(tree);
                break;
			case 'E': printData(hash);
                break;
	        case 'S': searchByHash(hash, list);
                break;
			case 'T': searchByDList(list);
                break;
			case 'I': car = addNewNode();
                insert(hash,car);
                insertDNode(list, car);
                insertTree(tree,car);
                break;
			case 'D': deleteCar(list, hash, tree);
                break;
			case 'W': writeToFile(list);
                break;
	        case 'Q': break;
        } // switch
    } while (choice != 'Q');
	return;
}	// process
// A function to show menu E.
void displayMenuEYear(int* menuCount, int categoryIndex, int* yearRefIndex)
{
	int year;
	int expectedRainfallYearListCount = rainfallYearListCount(categoryIndex);

	printHeader("E. Display the highest and lowest average rainfall.");
	printf("Please select the year from options 1 to %d that you want to display.\n", expectedRainfallYearListCount);

	*menuCount = 1;

	for (year = 0; year < rainfallYearListGetCapacity(); year++)
	{
		if (rainfallMonthListCount(categoryIndex, year) > 0)
		{
			printf("%d. %d\n", *menuCount, year + START_YEAR);
			yearRefIndex[*menuCount - 1] = year;
			*menuCount = *menuCount + 1;
		}
	}

	printf("%d. Go back to category list selection.\n", *menuCount);
	printHash();
}
Esempio n. 17
0
void nibbParseImageDir(char *sourceDir, char *goodTab, char *badTab)
/* nibbParseImageDir - Look through nibb image directory and allowing for 
 * typos and the like create a table that maps a file name to clone name, 
 * developmental stage, and view of body part. */
{
struct fileInfo *l1List, *l1, *l2List, *l2, *l3List, *l3;
struct hash *stageHash = hashNew(0);
struct hash *viewHash = hashNew(0);
struct hash *otherHash = hashNew(0);
struct hash *probeHash = hashNew(0);
struct hash *fixHash = hashFixers();
struct imageInfo *imageList = NULL, *image;
FILE *good = mustOpen(goodTab, "w");
FILE *bad = mustOpen(badTab, "w");
int goodCount = 0, badCount = 0;
int jpgCount = 0, jpgDir = 0;


l1List = listDirX(sourceDir, "XL*", FALSE);
for (l1 = l1List; l1 != NULL; l1 = l1->next)
    {
    char l1Path[PATH_LEN];
    safef(l1Path, sizeof(l1Path), "%s/%s", sourceDir, l1->name);
    l2List = listDirX(l1Path, "XL*", FALSE);
    for (l2 = l2List; l2 != NULL; l2 = l2->next)
        {
	char l2Path[PATH_LEN];
	char cloneName[64], *permanentCloneName;
	char *cloneDir = l2->name;
	char *cloneEnd;
	int cloneNameSize = 0;

	if (stringIx(cloneDir, skipDir) >= 0)
	    continue;

	/* Figure out clone name, whish is directory component up to
	 * first underbar. */
	cloneEnd = strchr(cloneDir, '_');
	if (cloneEnd != NULL)
	    cloneNameSize = cloneEnd - cloneDir;
	else
	    errAbort("Strangely formatted image dir %s, no underbar", cloneDir);
	if (cloneNameSize >= sizeof(cloneName))
	    errAbort("Clone name too long in dir %s", cloneDir);
	if (cloneNameSize < 8 || cloneNameSize > 12)
	    errAbort("Clone name wrong size %s", cloneDir);
	memcpy(cloneName, cloneDir, cloneNameSize);
	cloneName[cloneNameSize] = 0;
	/* Check format is XL###L##.  We already checked the XL. */
	if (!isdigit(cloneName[2]) || !isdigit(cloneName[3]) 
		 || !isdigit(cloneName[4]) || isdigit(cloneName[5]) 
		 || !isdigit(cloneName[6]) || !isdigit(cloneName[7]))
	    errAbort("Strangely formatted clone name %s", cloneDir);

	permanentCloneName = hashStoreName(probeHash, cloneName);


	/* Get all files in dir. */
	safef(l2Path, sizeof(l2Path), 
		"%s/%s/%s", sourceDir, l1->name, l2->name);
	l3List = listDirX(l2Path, "*.jpg", FALSE);
	for (l3 = l3List; l3 != NULL; l3 = l3->next)
	    {
	    char *fileName = l3->name;

	    if (stringIx(l3->name, skipFile) >= 0)
		continue;
	    image = getImageInfo(fixHash, permanentCloneName, 
	    	l1->name, cloneDir, fileName,
	    	stageHash, viewHash, otherHash, probeHash);
	    slAddHead(&imageList, image);
	    ++jpgCount;
	    }
	++jpgDir;
	}
    }
slReverse(&imageList);

verbose(1, "%d jpg images in %d directories\n", jpgCount, jpgDir);

#ifdef OLD
verbose(1, "%d probes, %d stages, %d views, %d other\n", 
	probeHash->elCount, stageHash->elCount, 
	viewHash->elCount, otherHash->elCount);
printHash("stages", stageHash);
printHash("views", viewHash);
printHash("other", otherHash);
#endif /* OLD */

for (image = imageList; image != NULL; image = image->next)
    {
    if (image->clone != NULL && image->stage != NULL && image->view != NULL)
        {
	imageInfoOut(image, good);
	++goodCount;
	}
    else
	{
	imageInfoOut(image, bad);
	++badCount;
	}
    }
verbose(1, "%d (%4.1f%%) parsed ok, %d (%4.2f%%) didn't\n", 
	goodCount, 100.0 * goodCount/(goodCount + badCount), 
	badCount, 100.0 * badCount/(goodCount + badCount));
carefulClose(&good);
carefulClose(&bad);
}
Esempio n. 18
0
void flushDownload(int sock)
{
  int i = 0;
  int idx;
  uint8_t *hash;
  Packet *pkt;
  connDown *pool = downloadPool;
  for(i = 0; i < peerInfo.numPeer; i++) {
    int peerID = peerInfo.peerList[i].peerID;
    Packet *ack = peek(pool[peerID].ackSendQueue);

    while(ack != NULL) {
      peerList_t *p = &(peerInfo.peerList[i]);
      fprintf(stderr,"Sending ACK %d\n", getPacketAck(ack));
      int retVal = spiffy_sendto(sock,
				 ack->payload,
				 getPacketSize(ack),
				 0,
				 (struct sockaddr *) & (p->addr),
				 sizeof(p->addr));
      fprintf(stderr,"Sent ACK %d\n", getPacketAck(ack));
      if(retVal == -1) { // spiffy_sendto() does not work!!
	fprintf(stderr,"spiffy_sendto() returned -1.\n");
	enqueue(pool[peerID].ackSendQueue, dequeue(pool[peerID].ackSendQueue));
      } else {
	dequeue(pool[peerID].ackSendQueue);
	freePacket(ack);
	ack = dequeue(pool[peerID].ackSendQueue);
      }
    }

    switch(pool[peerID].state) {
    case 0: // Ready
      pkt = dequeue(pool[peerID].getQueue);
      while(pkt != NULL) {
	hash = getPacketHash(pkt, 0);
	printHash(hash);
	idx = searchHash(hash, &getChunk, 0);
	if(idx == -1) { // Someone else is sending or has sent this chunk
	  freePacket(pkt);
	  pkt = dequeue(pool[peerID].getQueue);
	} else if(numConnDown < maxConn){
	  getChunk.list[idx].fetchState = 2;
	  if(downloadPool[peerID].connected == 1)
	    fprintf(stderr,"NOT SUPPOSED TO BE CONNECTEED! \n\n\n\n\n\n");
	  downloadPool[peerID].connected = 1;
	  numConnDown++;
	  break;
	} else { // Cannot allow more download connections
	  fprintf(stderr,"->No more download connection allowed!\n");
	  pool[peerID].state = 2;
	  break;
	}
      }
      if(pool[peerID].state == 2)
	break;
      
      if(pkt != NULL) {
	fprintf(stderr,"Sending a GET\n");
	peerList_t *p = &(peerInfo.peerList[i]);
	hash = pkt->payload + 16;
	char buf[50];
	bzero(buf, 50);
	binary2hex(hash, 20, buf);
	fprintf(stderr,"GET hash:%s\n", buf);
	pool[peerID].curChunkID = searchHash(hash, &getChunk, -1);
	
	int retVal = spiffy_sendto(sock,
				   pkt->payload,
				   getPacketSize(pkt),
				   0,
				   (struct sockaddr *) & (p->addr),
				   sizeof(p->addr));

	if(retVal == -1) { // Spiffy is broken!
	  fprintf(stderr,"spiffy_snetto() returned -1.\n");
	  newPacketWHOHAS(nonCongestQueue);
	  freePacket(pkt);
	  cleanUpConnDown(&(pool[peerID]));
	  numConnDown--;
	  return;
	}

	setPacketTime(pkt);

	enqueue(pool[peerID].timeoutQueue, pkt);
	pool[peerID].state = 1;
      }
      break;
    case 1: { // Downloading
      pkt = peek(pool[peerID].timeoutQueue);
      struct timeval curTime;
      gettimeofday(&curTime, NULL);
      long dt = diffTimeval(&curTime, &(pkt->timestamp));
      if(dt > GET_TIMEOUT_SEC) {
	pool[peerID].timeoutCount++;
	fprintf(stderr,"GET request timed out %d times!\n", pool[peerID].timeoutCount);
	setPacketTime(pkt);
	if(pool[peerID].timeoutCount == 3) {
	  getChunk.list[pool[peerID].curChunkID].fetchState = 0;
	  pool[peerID].state = 0;
	  newPacketWHOHAS(nonCongestQueue);
	  freePacket(pkt);
	  cleanUpConnDown(&(pool[peerID]));
	  numConnDown--;
	}
      }
      break;
    }
    case 2: {
      break;
    }
    default:
      break;
    }

  }
}
Esempio n. 19
0
void * rpmShowProgress(const void * arg,
			const rpmCallbackType what,
			const rpm_loff_t amount,
			const rpm_loff_t total,
			fnpyKey key,
			void * data)
{
    Header h = (Header) arg;
    int flags = (int) ((long)data);
    void * rc = NULL;
    const char * filename = (const char *)key;
    static FD_t fd = NULL;

    switch (what) {
    case RPMCALLBACK_INST_OPEN_FILE:
	if (filename == NULL || filename[0] == '\0')
	    return NULL;
	fd = Fopen(filename, "r.ufdio");
	/* FIX: still necessary? */
	if (fd == NULL || Ferror(fd)) {
	    rpmlog(RPMLOG_ERR, _("open of %s failed: %s\n"), filename,
			Fstrerror(fd));
	    if (fd != NULL) {
		Fclose(fd);
		fd = NULL;
	    }
	} else
	    fd = fdLink(fd);
#if defined(POSIX_FADV_WILLNEED)
	(void) Fadvise(fd, 0, 0, POSIX_FADV_WILLNEED);
#endif
	return (void *)fd;
	break;

    case RPMCALLBACK_INST_CLOSE_FILE:
	/* FIX: still necessary? */
	fd = fdFree(fd);
	if (fd != NULL) {
	    Fclose(fd);
	    fd = NULL;
	}
	break;

    case RPMCALLBACK_INST_START:
    case RPMCALLBACK_UNINST_START:
	if (rpmcliProgressState != what) {
	    rpmcliProgressState = what;
	    if (flags & INSTALL_HASH) {
		if (what == RPMCALLBACK_INST_START) {
		    fprintf(stdout, _("Updating / installing...\n"));
		} else {
		    fprintf(stdout, _("Cleaning up / removing...\n"));
		}
		fflush(stdout);
	    }
	}
		
	rpmcliHashesCurrent = 0;
	if (h == NULL || !(flags & INSTALL_LABEL))
	    break;
	if (flags & INSTALL_HASH) {
	    char *s = headerGetAsString(h, RPMTAG_NEVR);
	    if (isatty (STDOUT_FILENO))
		fprintf(stdout, "%4d:%-33.33s", rpmcliProgressCurrent + 1, s);
	    else
		fprintf(stdout, "%-38.38s", s);
	    (void) fflush(stdout);
	    free(s);
	} else {
	    char *s = headerGetAsString(h, RPMTAG_NEVRA);
	    fprintf(stdout, "%s\n", s);
	    (void) fflush(stdout);
	    free(s);
	}
	break;

    case RPMCALLBACK_INST_STOP:
	break;

    case RPMCALLBACK_TRANS_PROGRESS:
    case RPMCALLBACK_INST_PROGRESS:
    case RPMCALLBACK_UNINST_PROGRESS:
	if (flags & INSTALL_PERCENT)
	    fprintf(stdout, "%%%% %f\n", (double) (total
				? ((((float) amount) / total) * 100)
				: 100.0));
	else if (flags & INSTALL_HASH)
	    printHash(amount, total);
	(void) fflush(stdout);
	break;

    case RPMCALLBACK_TRANS_START:
	rpmcliHashesCurrent = 0;
	rpmcliProgressTotal = 1;
	rpmcliProgressCurrent = 0;
	rpmcliPackagesTotal = total;
	rpmcliProgressState = what;
	if (!(flags & INSTALL_LABEL))
	    break;
	if (flags & INSTALL_HASH)
	    fprintf(stdout, "%-38s", _("Preparing..."));
	else
	    fprintf(stdout, "%s\n", _("Preparing packages..."));
	(void) fflush(stdout);
	break;

    case RPMCALLBACK_TRANS_STOP:
	if (flags & INSTALL_HASH)
	    printHash(1, 1);	/* Fixes "preparing..." progress bar */
	rpmcliProgressTotal = rpmcliPackagesTotal;
	rpmcliProgressCurrent = 0;
	break;

    case RPMCALLBACK_UNINST_STOP:
	break;
    case RPMCALLBACK_UNPACK_ERROR:
	break;
    case RPMCALLBACK_CPIO_ERROR:
	break;
    case RPMCALLBACK_SCRIPT_ERROR:
	break;
    case RPMCALLBACK_SCRIPT_START:
	break;
    case RPMCALLBACK_SCRIPT_STOP:
	break;
    case RPMCALLBACK_UNKNOWN:
    default:
	break;
    }

    return rc;
}	
Esempio n. 20
0
/*	================== getOption =================
 This function reads in the user's desired chose
 of operation. Calls upon other functions to
 perform the procedure.
 Pre		pHeader - pointer to HEAD structure
 Post
 Return
 */
void getOption (HEAD* pHeader)
{
	//	Local Declarations
    char command;
    DATA target;
    DATA* airport = NULL;
	int i;
    
	//	Statements
    while ((command = menu()) != 'Q') {
        switch (command)
        {
            case 'A':
                if (addAirport(pHeader))
                {
                    while (checkHash(pHeader->pHash) == 1) {
                        pHeader->pHash = upsizeHash(pHeader->pHash);
                    }
					printf ("\n Succesfully added data.\n\n");
                }
                break;
            case 'D':
                printf("Enter the airport code: ");
                scanf(" %s", target.arpCode);
                
				if (deleteHash (pHeader, target))
                {
                    while (checkHash(pHeader->pHash) == -1) {
                        pHeader->pHash = downsizeHash(pHeader->pHash);
                    }
					printf ("\n Succesfully deleted data.\n\n");
                }
                
                break;
            case 'F':
                printf("Enter the airport code: ");
                scanf(" %s", target.arpCode);
				// fix sensitive input cases
				for (i = 0; i < strlen(target.arpCode); i++) {
					target.arpCode[i] = toupper(target.arpCode[i]);
				}
                airport = findHash(pHeader->pHash, &target);
                if (airport != NULL) {
                    processScreen(airport);
                }
                else printf("No airport exists\n");
                
                break;
            case 'L':
                printHash(pHeader->pHash);
                break;
            case 'K':
                BST_Traverse(pHeader->pTree, processScreen);
                break;
            case 'P':
                printTree(pHeader->pTree->root, 0);
				printf("\n");
                break;
            case 'W':
				outputFile (pHeader->pHash);
                break;
            case 'E':
				efficiency(pHeader->pHash);
                break;
			case 'H':
				pHeader->pHash = hashDemo(pHeader->pHash);
				break;
            default:
                printf("Invalid choice. Choose again\n");
                break;
        }
    }
    return;
}	// getOption
Esempio n. 21
0
int main(){

  int maxSize = 8;
  int used = 0;
  float loadFactor = 0;
  Hashtable h;

  h = init(h,maxSize);

  int r=0,resposta;
  while(r!=1){
    printHash(h,used, maxSize);
    char input[1024];
    printf("\naction (he for help)$ ");
    fgets(input, sizeof(input), stdin);
    input[strlen(input)-1] = '\0';
    if(strcmp(input,"in") == 0) {
      long int num, scanres;
      char tempInput[50], enter;
      printf("Key to insert: ");
      fgets(tempInput,sizeof(tempInput), stdin);
      tempInput[strlen(tempInput)-1] = '\0';
      char tempNum[20];
      printf("Value: ");
      fgets(tempNum,sizeof(tempNum), stdin);
      scanres = sscanf(tempNum,"%ld%c",&num,&enter);
      if(!(scanres == 2 && enter == '\n'))
        printf("Not a number. ");
      else {
        resposta=insert(h,tempInput,strlen(tempInput),num,maxSize);
        if(resposta) {
          used++;
          updateLoadFactor(used,maxSize,&loadFactor);
          printf("Inserted %ld. ",num);
          if(loadFactor > 0.7) {
            h = duplicate(h,&maxSize);
            printf("\n--> Load Factor of 0.7 exceeded. Duplicated hash table size. ");
          }
        }
        else
          printf("Not inserted. ");
      }
      printf("<ENTER>");
      getchar();
    }
    else if(strcmp(input,"te") == 0) {
      printf("h[0]: %s\n",h[0]->key);
      getchar();
    }
    else if(strcmp(input,"al") == 0) {
      long int num, scanres;
      char tempInput[50], enter;
      printf("Key to alter: ");
      fgets(tempInput,sizeof(tempInput), stdin);
      tempInput[strlen(tempInput)-1] = '\0';
      char tempNum[20];
      printf("New value: ");
      fgets(tempNum,sizeof(tempNum), stdin);
      scanres = sscanf(tempNum,"%ld%c",&num,&enter);
      if(!(scanres == 2 && enter == '\n'))
        printf("Not a number. ");
      else {
        resposta=alter(h,tempInput,strlen(tempInput),num,maxSize);
        if(resposta)
          printf("%s's value altered to %ld. ",tempInput,num);
        else
          printf("[error] No changes. ");
      }
      printf("<ENTER>");
      getchar();
    }
    else if(strcmp(input,"se") == 0) {
      long int num, scanres;
      Node res;
      char tempInput[50], enter;
      printf("Key to search: ");
      fgets(tempInput,sizeof(tempInput), stdin);
      tempInput[strlen(tempInput)-1] = '\0';
      res=search(h,tempInput,strlen(tempInput),maxSize);
      if(res)
        printf("Found '%s'. Value: %ld. ", tempInput, res->entry);
      else
        printf("'%s' was not found. ", tempInput);
      printf("<ENTER>");
      getchar();
    }
    else if(strcmp(input,"re") == 0) {
      long int num, scanres;
      char tempInput[50], enter;
      printf("Key to remove: ");
      fgets(tempInput,sizeof(tempInput), stdin);
      tempInput[strlen(tempInput)-1] = '\0';
      resposta=rem(h,tempInput,strlen(tempInput),maxSize);
      if(resposta) {
        used--;
        updateLoadFactor(used,maxSize,&loadFactor);
        printf("Removed %s. ",tempInput);
      }
      else
        printf("'%s' was not removed. ", tempInput);
      printf("<ENTER>");
      getchar();
    }
    else if(strcmp(input,"pr") == 0) {
      printHash(h,used,maxSize);
    }
    else if(strcmp(input,"he") == 0) {
      printf("\n# available actions:\n");
      printf("# in - insert in hash table;\n");
      printf("# re - remove from hash table;\n");
      printf("# al - alter the value of a key;\n");
      printf("# se - search in hash table;\n");
      printf("# pr - print hashtable contents;\n");
      printf("# ex - exit.\n\n<ENTER>");
      getchar();
    }
    else if(strcmp(input,"ex") == 0) {
      r = 1;
      printf("Leaving... <ENTER>");
      getchar();
    }
    else {
      printf("\nNot an action. Type he for available actions. <ENTER>");
      getchar();
    }
  }
  printf("Done.\n");

  return 1;
}
Esempio n. 22
0
int main(int argc, char** argv)
{
	if (argc == 1 || !strcmp(argv[1], "--help") || !strcmp(argv[1], "-h"))
	{
		usage(argc, argv);
		exit(0);
	}
	else if (!strcmp(argv[1], "--version") || !strcmp(argv[1], "-v"))
	{
		printf("ltcrack\n");
		printf("Compiled on %s at %s\n", __DATE__, __TIME__);
		exit(0);
	}

	if (argc < 4)
	{
		usage(argc, argv);
		exit(1);
	}

	Target ttype;
	char* tstr = argv[1];
	if (strcmp(tstr, "-x") == 0 || strcmp(tstr, "--hash") == 0)
		ttype = T_HASH;
	else if (strcmp(tstr, "-f") == 0 || strcmp(tstr, "--file") == 0)
		ttype = T_FILE;
	else if (strcmp(tstr, "-r") == 0 || strcmp(tstr, "--random") == 0)
		ttype = T_RAND;
	else
		ERROR("Invalid target '%s'\n", tstr);

	char* tparam = argv[2];

	// load tables
	n_lt = argc-3;
	lt = malloc(sizeof(LTable) * n_lt);
	assert(lt);
	for (u32 i = 0; i < n_lt; i++)
		if (!LTable_FromFile(&lt[i], argv[i+3]))
			ERROR("Could no load table '%s'\n", argv[i+3])

	// some parameters
	u32   l_string  = lt[0].l_string;
	char* charset   = lt[0].charset;
	u32   n_charset = lt[0].n_charset;

	// some buffers
	char hash[16];
	bufstr = malloc(l_string);
	assert(bufstr);

	// try and crack hash(es)
	switch (ttype)
	{
	case T_HASH:
		hex2hash(tparam, hash, 16);
		if (reverseHash(hash))
		{
			printHash(hash, 16);
			printf(" ");
			printString(bufstr, l_string);
			printf("\n");
		}
		else
			printf("Could not reverse hash\n");
		break;
	case T_FILE:
		(void) 0;
		FILE* f = strcmp(tparam, "-") == 0 ? stdin : fopen(tparam, "r");
		assert(f);

		while (1)
		{
			char hashstr[33];
			fread(hashstr, 1, 33, f);
			if (feof(f))
				break;

			hex2hash(hashstr, hash, 16);
			if (reverseHash(hash))
			{
				printHash(hash, 16);
				printf(" ");
				printString(bufstr, l_string);
				printf("\n");
			}
			else
				printf("Could not reverse hash\n");
		}

		fclose(f);
		break;
	case T_RAND:
		srandom(time(NULL));
		u32 n = atoi(tparam);
		u32 n_crack = 0;
		for (u32 i = 0; i < n; i++)
		{
			for (u32 j = 0; j < l_string; j++)
				bufstr[j] = charset[random() % n_charset];

			char hash[16];
			MD5((u8*) hash, (u8*) bufstr, l_string);
			if (reverseHash(hash))
				n_crack++;
			rewriteLine();
			printf("%lu / %lu", n_crack, i+1);
			fflush(stdout);
		}
		printf("\n");
	}
	free(bufstr);

	for (u32 i = 0; i < n_lt; i++)
		LTable_Delete(&lt[i]);
	free(lt);

	return 0;
}
int main (int argc, char **argv) {
  uint32_t a;
  sha1nfo s;

  printf("sizeof(sha1nfo)=%d\n\n", sizeof(sha1nfo));

  // SHA tests
  printf("Test: FIPS 180-2 C.1 and RFC3174 7.3 TEST1\n");
  printf("Expect:a9993e364706816aba3e25717850c26c9cd0d89d\n");
  printf("Result:");
  sha1_init(&s);
  sha1_write(&s, "abc", 3);
  printHash(sha1_result(&s));
  printf("\n\n");

  printf("Test: FIPS 180-2 C.2 and RFC3174 7.3 TEST2\n");
  printf("Expect:84983e441c3bd26ebaae4aa1f95129e5e54670f1\n");
  printf("Result:");
  sha1_init(&s);
  sha1_write(&s, "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", 56);
  printHash(sha1_result(&s));
  printf("\n\n");

  printf("Test: RFC3174 7.3 TEST4\n");
  printf("Expect:dea356a2cddd90c7a7ecedc5ebb563934f460452\n");
  printf("Result:");
  sha1_init(&s);
  for (a=0; a<80; a++) sha1_write(&s, "01234567", 8);
  printHash(sha1_result(&s));
  printf("\n\n");

  // HMAC tests
  printf("Test: FIPS 198a A.1\n");
  printf("Expect:4f4ca3d5d68ba7cc0a1208c9c61e9c5da0403c0a\n");
  printf("Result:");
  sha1_initHmac(&s, hmacKey1, 64);
  sha1_write(&s, "Sample #1",9);
  printHash(sha1_resultHmac(&s));
  printf("\n\n");

  printf("Test: FIPS 198a A.2\n");
  printf("Expect:0922d3405faa3d194f82a45830737d5cc6c75d24\n");
  printf("Result:");
  sha1_initHmac(&s, hmacKey2, 20);
  sha1_write(&s, "Sample #2", 9);
  printHash(sha1_resultHmac(&s));
  printf("\n\n");

  printf("Test: FIPS 198a A.3\n");
  printf("Expect:bcf41eab8bb2d802f3d05caf7cb092ecf8d1a3aa\n");
  printf("Result:");
  sha1_initHmac(&s, hmacKey3,100);
  sha1_write(&s, "Sample #3", 9);
  printHash(sha1_resultHmac(&s));
  printf("\n\n");

  printf("Test: FIPS 198a A.4\n");
  printf("Expect:9ea886efe268dbecce420c7524df32e0751a2a26\n");
  printf("Result:");
  sha1_initHmac(&s, hmacKey4,49);
  sha1_write(&s, "Sample #4", 9);
  printHash(sha1_resultHmac(&s));
  printf("\n\n");

  // Long tests
  printf("Test: FIPS 180-2 C.3 and RFC3174 7.3 TEST3\n");
  printf("Expect:34aa973cd4c4daa4f61eeb2bdbad27316534016f\n");
  printf("Result:");
  sha1_init(&s);
  for (a=0; a<1000000; a++) sha1_writebyte(&s, 'a');
  printHash(sha1_result(&s));

  // liang: 65536 zeros
  printf("\n\n");
  printf("Test: 65536 zeros\n");
  printf("Expect:1adc95bebe9eea8c112d40cd04ab7a8d75c4f961\n");
  printf("Result:");
  sha1_init(&s);
  for (a=0; a<65536; a++) sha1_writebyte(&s, 0);
  printHash(sha1_result(&s));

  // test liang_zhash
  printf("\n\n");
  printf("Test: 65536 zeros\n");
  printf("Expect:1adc95bebe9eea8c112d40cd04ab7a8d75c4f961\n");
  printf("Result:");
  uint8_t hash[20];
  char buf[65536];
  for(a=0; a<65536; a++) buf[a]=0;
  liang_zhash((const uint8_t *)buf, 65536, hash);
  printHash(hash);
  
  return 0;
}
Esempio n. 24
0
File: rpminstall.c Progetto: xrg/RPM
void * rpmShowProgress(const void * arg,
			const rpmCallbackType what,
			const rpm_loff_t amount,
			const rpm_loff_t total,
			fnpyKey key,
			void * data)
{
    Header h = (Header) arg;
    char * s;
    int flags = (int) ((long)data);
    void * rc = NULL;
    const char * filename = (const char *)key;
    static FD_t fd = NULL;
    int xx;

    switch (what) {
    case RPMCALLBACK_INST_OPEN_FILE:
	if (filename == NULL || filename[0] == '\0')
	    return NULL;
	fd = Fopen(filename, "r.ufdio");
	/* FIX: still necessary? */
	if (fd == NULL || Ferror(fd)) {
	    rpmlog(RPMLOG_ERR, _("open of %s failed: %s\n"), filename,
			Fstrerror(fd));
	    if (fd != NULL) {
		xx = Fclose(fd);
		fd = NULL;
	    }
	} else
	    fd = fdLink(fd, RPMDBG_M("persist (showProgress)"));
	return (void *)fd;
	break;

    case RPMCALLBACK_INST_CLOSE_FILE:
	/* FIX: still necessary? */
	fd = fdFree(fd, RPMDBG_M("persist (showProgress)"));
	if (fd != NULL) {
	    xx = Fclose(fd);
	    fd = NULL;
	}
	break;

    case RPMCALLBACK_INST_START:
	rpmcliHashesCurrent = 0;
	if (h == NULL || !(flags & INSTALL_LABEL))
	    break;
	/* @todo Remove headerFormat() on a progress callback. */
	if (flags & INSTALL_HASH) {
	    s = headerFormat(h, "%{NAME}", NULL);
	    if (isatty (STDOUT_FILENO))
		fprintf(stdout, "%4d:%-23.23s", rpmcliProgressCurrent + 1, s);
	    else
		fprintf(stdout, "%-28.28s", s);
	    (void) fflush(stdout);
	    s = _free(s);
	} else {
	    s = headerFormat(h, "%{NAME}-%{VERSION}-%{RELEASE}", NULL);
	    fprintf(stdout, "%s\n", s);
	    (void) fflush(stdout);
	    s = _free(s);
	}
	break;

    case RPMCALLBACK_TRANS_PROGRESS:
    case RPMCALLBACK_INST_PROGRESS:
	if (flags & INSTALL_PERCENT)
	    fprintf(stdout, "%%%% %f\n", (double) (total
				? ((((float) amount) / total) * 100)
				: 100.0));
	else if (flags & INSTALL_HASH)
	    printHash(amount, total);
	(void) fflush(stdout);
	break;

    case RPMCALLBACK_TRANS_START:
	rpmcliHashesCurrent = 0;
	rpmcliProgressTotal = 1;
	rpmcliProgressCurrent = 0;
	if (!(flags & INSTALL_LABEL))
	    break;
	if (flags & INSTALL_HASH)
	    fprintf(stdout, "%-28s", _("Preparing..."));
	else
	    fprintf(stdout, "%s\n", _("Preparing packages for installation..."));
	(void) fflush(stdout);
	break;

    case RPMCALLBACK_TRANS_STOP:
	if (flags & INSTALL_HASH)
	    printHash(1, 1);	/* Fixes "preparing..." progress bar */
	rpmcliProgressTotal = rpmcliPackagesTotal;
	rpmcliProgressCurrent = 0;
	break;

    case RPMCALLBACK_UNINST_PROGRESS:
	break;
    case RPMCALLBACK_UNINST_START:
	break;
    case RPMCALLBACK_UNINST_STOP:
	break;
    case RPMCALLBACK_UNPACK_ERROR:
	break;
    case RPMCALLBACK_CPIO_ERROR:
	break;
    case RPMCALLBACK_SCRIPT_ERROR:
	break;
    case RPMCALLBACK_UNKNOWN:
    default:
	break;
    }

    return rc;
}	
int main(int argc, char** argv)
{
  uint8_t* hash;
  uint32_t a;
  double ms;
  // HMAC tests
  printf("Test: RFC4231 4.2\n");
  printf("Expect:b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7\n");
  printf("Result:");
  ms = Sha256.millis();
  Sha256.initHmac(hmacKey1,20);
  Sha256.print("Hi There");
  printHash(Sha256.resultHmac());
  printf(" Hash took %f \n",(Sha256.millis() - ms));
  
  printf("Test: RFC4231 4.3\n");
  printf("Expect:5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843\n");
  printf("Result:");
  ms = Sha256.millis();
  Sha256.initHmac((uint8_t*)"Jefe",4);
  Sha256.print("what do ya want for nothing?");
  printHash(Sha256.resultHmac());
  printf(" Hash took %f \n",(Sha256.millis() - ms));
  
  printf("Test: RFC4231 4.4\n");
  printf("Expect:773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe\n");
  printf("Result:");
  ms = Sha256.millis();
  Sha256.initHmac(hmacKey3,20);
  for (a=0; a<50; a++) Sha256.write(0xdd);
  printHash(Sha256.resultHmac());
  printf(" Hash took %f \n",(Sha256.millis() - ms));

  printf("Test: RFC4231 4.5\n");
  printf("Expect:82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b\n");
  printf("Result:");
  ms = Sha256.millis();
  Sha256.initHmac(hmacKey2,25);
  for (a=0; a<50; a++) Sha256.write(0xcd);
  printHash(Sha256.resultHmac());
  printf(" Hash took %f \n",(Sha256.millis() - ms));
  
  printf("Test: RFC4231 4.6\n");
  printf("Expect:a3b6167473100ee06e0c796c2955552b-------------------------------\n");
  printf("Result:");
  ms = Sha256.millis();
  Sha256.initHmac(hmacKey4,20);
  Sha256.print("Test With Truncation");
  printHash(Sha256.resultHmac());
  printf(" Hash took %f \n",(Sha256.millis() - ms));
  
  printf("Test: RFC4231 4.7\n");
  printf("Expect:60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54\n");
  printf("Result:");
  ms = Sha256.millis();
  Sha256.initHmac(hmacKey5,131);
  Sha256.print("Test Using Larger Than Block-Size Key - Hash Key First");
  printHash(Sha256.resultHmac());
  printf(" Hash took %f \n",(Sha256.millis() - ms));

  printf("Test: RFC4231 4.8\n");
  printf("Expect:9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2\n");
  printf("Result:");
  ms = Sha256.millis();
  Sha256.initHmac(hmacKey5,131);
  Sha256.print("This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.");
  printHash(Sha256.resultHmac());
  printf(" Hash took %f \n",(Sha256.millis() - ms));
  return 0;
}