Exemplo n.º 1
0
int main(){
  char t[]="abc";
  printf("%s\n",cipher(t));
  printf("%s\n",decipher(t));


}
Exemplo n.º 2
0
int32 CTCPRequestPacket::ReceiveFromSocket()
{
	int8 recvbuf[DEFAULT_BUFLEN];

	m_size = recv(*m_socket, recvbuf, DEFAULT_BUFLEN, 0);
	if (m_size == -1) 
	{
#ifdef WIN32
		ShowError(CL_RED"recv failed with error: %d\n" CL_RESET, WSAGetLastError());
#else
		ShowError(CL_RED"recv failed with error: %d\n" CL_RESET, errno);
#endif
		return 0;
	}
    if (m_size == 0) 
	{
		//ShowError("TCP Connection closing...\n");
		return 0;
	}
	if (m_size != RBUFW(recvbuf,(0x00)) || m_size < 28) 
	{
		ShowError(CL_RED"Search packetsize wrong. Size %d should be %d.\n" CL_RESET, m_size, RBUFW(recvbuf,(0x00)));
		return 0;
	}
    delete[] m_data; 
    m_data = new uint8[m_size];

    memcpy(&m_data[0], &recvbuf[0], m_size);
	WBUFL(key,(16)) = RBUFL(m_data,(m_size-4));

	return decipher();
}
Exemplo n.º 3
0
double simulatedAnnealing(char *key, char *ciphertext, char *plaintext, int messageLen) {
	int count, iter;
	float annealStep;
	char newKey[26], oldKey[26];
	double prob, delta, maxScore, score, bestScore;
	
	// Copy over key so we don't screw up our master copy. Decipher ciphertext using key and score it
	strcpy(oldKey,key);
	decipher(oldKey, ciphertext, plaintext, messageLen);
	maxScore = scoreText(plaintext,messageLen);
	bestScore = maxScore;
	iter = 0;

	// For each step, find our best key
	for (annealStep = ANNEALING_TEMP; annealStep >= 0; annealStep -= ANNEALING_STEP_SIZE) {
		for (count = 0; count < MAX_ITERATIONS; count++) { 
			strcpy(newKey, oldKey);
			alterKey(newKey);
			decipher(newKey, ciphertext, plaintext, messageLen);
			score = scoreText(plaintext, messageLen);
			// our difference between our current maxScore and step score
			delta = score - maxScore;
			// We did work in the positive direction (hopefully...)
			if (delta >= 0) {
				maxScore = score;
				strcpy(oldKey, newKey);
			} else if (annealStep > 0) {
				// the work we did is a side-grade 
				prob = exp(delta / annealStep);
				if (prob > 1.0 * rand() / RAND_MAX) {
					maxScore = score;
					strcpy(oldKey, newKey);				
				}
			}
			// This is our best score so far
			if (maxScore > bestScore){
				bestScore = maxScore;
				strcpy(key, oldKey);
				outputStats(iter, bestScore, key);
			} 
			iter++;
		}
	}
	
	return bestScore;
}
Exemplo n.º 4
0
Arquivo: login.c Projeto: xuwenbo/KR
void
login(void)
{
    char szCode[] = {
        0x5F, 0x7F, 0x5E, 0x5E, 0xE0, 0x70, 0x84, 0x64, 0xBB, 0x6C, 0x34, 0x6C, 0x34, 0xD0, 0xA9, 0x31, 0x3C, 0xB9, 0x1E, 0x85, 0x64, 0x84, 0x4C, 0xAE, 0x92, 0xCA, 0xEF, 0xF0, 0x43, 0x50, 0x58, 0x31, 0xAF, 0x89, 0x18, 0x37, 0x87, 0x3F, 0xD8, 0x38, 0xD1, 0xEF, 0xF6, 0x52, 0xE4, 0x60, 0x88, 0xDF, 0xD8, 0xEE, 0x48, 0x88, 0x37, 0x26, 0x62, 0x5D, 0x58, 0x14, 0x11, 0x6D, 0xDD, 0x21, 0x31, 0x53, 0x6D, 0xB6, 0xA8, 0x30, 0xB8, 0x60, 0x5D, 0x70, 0x14, 0x11, 0x6D, 0xDD, 0x52, 0x31, 0x53, 0x6D, 0xB6, 0xA8, 0x30
    };


    int nBase;
    size_t len;
    char szInput[16];
    int i = 0;
    
    printf("Please Enter the passwd, "
           "you can only try %d times\r\n", MAX_TRY);
    
    while (i < MAX_TRY)
    {
        printf("Trying the %d time: ", i + 1);
        
        scanf("%15s", szInput);
        fflush(stdin);

        //this is used to restore key code 
        decipher(szInput);

        //verify whether decipher ok
        if (0 == verify())
        {
            //restore the key code for next try;
            restore(szCode);
            continue;
        }
        else
        {
            //nothing, go on

        }

        if (0xDA9B5D6D == ror_hash(szInput, strlen(szInput), 13, 19))
        {
            //do what u want to do;
            break;
        }
        
        i++;
    }
    
    if (MAX_TRY == i)
    {
        printf("Sorry!! U r under arrest\r\n");
    }
    else
    {
        printf("Congratulations!!\r\n");
    }
}
Exemplo n.º 5
0
Arquivo: main.c Projeto: chaws-unb/acg
char * work(char option, char * buffer, size_t length, unsigned int key)
{
	char * output;
	switch((int)option)
	{
		case 1/*DECIPHER_BRUTE*/: return breaker_bf(buffer, length);
		case 3/*DECIPHER_SUB*/:   return breaker_s(buffer, length);
		case 2/*DECIPHER_KEY*/:   return decipher(buffer, length, key);
		case 4/*CIPHER_KEY*/:     return cipher(buffer, length, key);
	}
}
Exemplo n.º 6
0
void av_cast5_crypt(AVCAST5* cs, uint8_t* dst, const uint8_t* src, int count, int decrypt)
{
    while (count--) {
        if (decrypt){
            decipher(cs,dst,src);
        } else {
            encipher(cs,dst,src);
        }
        src=src+8;
        dst=dst+8;
    }
}
Exemplo n.º 7
0
int main()
{
    char str[80];
    printf("Enter the string: \n");
    gets(str);
    printf("To cipher: %s -> ", str);
    cipher(str);
    printf("%s\n", str);
    printf("To decipher: %s -> ", str);
    decipher(str);
    printf("%s\n", str);
    return 0;
}
Exemplo n.º 8
0
//main()
int main()
{
	int i = 0;
	int fd[DEFAULT_LINE_NUM][2]; //pipe for each child process
	pid_t childpid[DEFAULT_LINE_NUM];
	FILE* cipherfd = fopen("cipher.txt", "r");

	while(1)
	{
		pipe(fd[i]);
	
		childpid[i] = fork();

		if(childpid[i] == 0) //child
		{
			close(fd[i][1]); //write end close
			char* buffer = NULL; //store your ciphertext from pipe in this buffer

			//TODO: read ciphertext from parent using pipe
			//Note: read() will return 0 when parent closes the write end of pipe

			if(buffer)
				decipher(buffer);
			exit(0);
		}
		else //parent
		{
			close(fd[i][0]); //read end close
			char* buffer = NULL; //store your ciphertext in this buffer

			//TODO: read a line of ciphertext from the FILE pointer using getline!
			
			//if getline returns EOF
			break;

			//TODO: give ciphertext to child using pipe
		}

		i++;
	}

	int j;

	for(j = 0; j < i; j++)
		while(-1 == waitpid(childpid[j], NULL, 0) && errno == EINTR);

	system("./complete");

	return 0;
}
Exemplo n.º 9
0
void Cblowfish::decipher(const void* s, void* d, int size) const
{
    const dword* r = reinterpret_cast<const dword*>(s);
    dword* w = reinterpret_cast<dword*>(d);
    size >>= 3;
    while (size--)
    {
        dword a = reverse(*r++);
        dword b = reverse(*r++);
        decipher(a, b);
        *w++ = reverse(a);
        *w++ = reverse(b);
    }
}
Exemplo n.º 10
0
void Role::makeConnection()
{
    connect(logic->getClient(),SIGNAL(getMessage(QString)),this,SLOT(decipher(QString)));
    connect(this,SIGNAL(sendCommand(QString)),logic->getClient(),SLOT(sendMessage(QString)));
    connect(decisionArea,SIGNAL(okClicked()),this,SLOT(onOkClicked()));
    connect(decisionArea,SIGNAL(cancelClicked()),this,SLOT(onCancelClicked()));
    connect(decisionArea,SIGNAL(exchangeClicked()),this,SLOT(exchangeCards()));
    connect(decisionArea,SIGNAL(resignClicked()),this,SLOT(resign()));
    connect(buttonArea->getButtons().at(0),SIGNAL(buttonSelected(int)),this,SLOT(buy()));
    connect(buttonArea->getButtons().at(1),SIGNAL(buttonSelected(int)),this,SLOT(synthetize()));
    connect(buttonArea->getButtons().at(2),SIGNAL(buttonSelected(int)),this,SLOT(extract()));
    connect(buttonArea,SIGNAL(buttonUnselected()),this,SLOT(onCancelClicked()));
    connect(handArea,SIGNAL(cardReady()),this,SLOT(cardAnalyse()));
    connect(playerArea,SIGNAL(playerReady()),this,SLOT(playerAnalyse()));
}
Exemplo n.º 11
0
void av_cast5_crypt2(AVCAST5* cs, uint8_t* dst, const uint8_t* src, int count, uint8_t *iv, int decrypt)
{
    int i;
    while (count--) {
        if (decrypt) {
            decipher(cs, dst, src, iv);
        } else {
            if (iv) {
                for (i = 0; i < 8; i++)
                    dst[i] = src[i] ^ iv[i];
                encipher(cs, dst, dst);
                memcpy(iv, dst, 8);
            } else {
                encipher(cs, dst, src);
            }
        }
        src = src + 8;
        dst = dst + 8;
    }
}
Exemplo n.º 12
0
int Arithmetic::TeaDecode(char* p_in, int i_in_len, char* p_key, char* p_out)
{
    int i;
	char key[16]={0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
	if(p_in == NULL || i_in_len <= 0){
		return -1;
	}
	if(i_in_len & 0x07L){
		return -2;
	}
	if(p_out == NULL){
		return i_in_len;
	}
	memcpy(p_out, p_in, i_in_len);
	memcpy((void*)key, p_key, (strlen(p_key) > 16) ? 16 : strlen(p_key));
	for(i = 0; i < i_in_len; i += 8){
		decipher(&p_out[i], key);
	}
	return i_in_len;
}
Exemplo n.º 13
0
/**
 * decrypt()
 * c:           Cipherext			[in]
 * k:           Key used to encrypt text        [in]
 * buff:        Buffer to store decrypted data  [out]
 *
 * Decrypts cipher (using key), and stores it into buff.
 **/
void VC::decrypt(const char c[], const char k[], string &buff){
	buff.clear();

        // c & k will be the same length
        int len = strlen(c);
        int keylen = strlen(k);

        // Current position in c & k
        int i = 0, j = 0;

        // While not at the end of the cipher text
        while(i < len){
                if(j == keylen)
                        j = 0;

                buff += decipher(c[i], k[j]);

                i++;
		j++;
        }
}
Exemplo n.º 14
0
Arquivo: login.c Projeto: xuwenbo/KR
void
login(void)
{
    char szInput[16];
    int i = 0;
    
    printf("Please Enter the passwd, "
           "you can only try %d times\r\n", MAX_TRY);
    
    while (i < MAX_TRY)
    {
        printf("Trying the %d time: ", i + 1);
        
        scanf("%15s", szInput);
        fflush(stdin);

        //this is used to restore key code 
        decipher(szInput);
        
        if (0xDA9B5D6D == ror13_hash(szInput))
        {
            //do what u want to do;
            break;
        }
        
        i++;
    }
    
    if (MAX_TRY == i)
    {
        printf("Sorry!! U r under arrest\r\n");
    }
    else
    {
        printf("Congratulations!!\r\n");
    }
}
Exemplo n.º 15
0
main()
{	int i;
	char *p;

	uid = getuid();
	myname = (char *)getlogin();
	if(myname == NULL)
		myname = getpwuid(uid)->pw_name;
	comminit();
	mbuf = itom(0);
	files();
	setup(getpass("Key: "));
	mkb();
	mkx();
#ifndef debug
	invert(x, b, x);
#else
	invert(x, b, z);
	mult(x, z, z);
	mdiv(z, b, q, z);
	omout(z);
	invert(x, b, x);
#endif
	for(i=0; i<fcnt; i++)
	{	sprintf(line, "%s%s.%d", maildir, myname, fnum[i]);
		if(stat(line, &stbuf)<0)
		{	perror(line);
			continue;
		}
		if(stbuf.st_size == 0)
		{	printf("zero length mail file\n");
			unlink(line);
			continue;
		}
		if((mf = fopen(line, "r"))==NULL)
		{	perror(line);
			continue;
		}
		decipher(mf, stdout);
	cmnd:
		printf("? ");
		fgets(buf, sizeof(buf), stdin);
		if(feof(stdin)) exit(0);
		switch(buf[0])
		{
		case 'q':
			exit(0);
		case 'n':
		case 'd':
		case '\n':
			fclose(mf);
			unlink(line);
			break;
		case '!':
			system(buf+1);
			printf("!\n");
			goto cmnd;
		case 's':
		case 'w':
			rewind(mf);
			if(buf[1] == '\n' || buf[1] == '\0')
				strcpy(buf, "s mbox\n");
			for(p = buf+1; isspace(*p); p++);
			p[strlen(p)-1] = 0;
			kf = fopen(p, "a");
			if(kf == NULL)
			{	perror(p);
				goto cmnd;
			}
			decipher(mf, kf);
			fclose(mf);
			fclose(kf);
			unlink(line);
			break;
		default:
			printf("Commands are:\n");
			printf("q	quit, leaving unread messages\n");
			printf("n	delete current message and goto next\n");
			printf("d	same as above\n");
			printf("\\n	same as above\n");
			printf("!	execute shell command\n");
			printf("s	save message in the named file or mbox\n");
			printf("w	same as above\n");
			printf("?	prints this list\n");
			goto cmnd;
		}
	}
	exit(0);
}
Exemplo n.º 16
0
int main(){
	
 	FILE *arq;
   	char *result;
	int i,j;
	int size_key = 8;
	char msg[] = "Uma criança nasce sem qualquer conhecimento, sem qualquer consciência de seu próprio eu. E quando uma criança nasce, a primeira coisa da qual ela se torna consciente não é ela mesma; a primeira coisa da qual ela se torna consciente é o outro. Isso é natural, porque os olhos se abrem para fora, as mãos tocam os outros, os ouvidos escutam os outros, a língua saboreia a comida e o nariz cheira o exterior. Todos esses sentidos abrem-se para fora. O nascimento é isso. Nascimento significa vir a esse mundo: o mundo exterior. Assim, quando uma criança nasce, ela nasce nesse mundo. Ela abre os olhos e vê os outros. O outro significa o tu.  Ela primeiro se torna consciente da mãe. Então, pouco a pouco, ela se torna consciente de seu próprio corpo. Esse também é o 'outro', também pertence ao mundo. Ela está com fome e passa a sentir o corpo; quando sua necessidade é satisfeita, ela esquece o corpo. É dessa maneira que a criança cresce. Primeiro ela se torna consciente do você, do tu, do outro, e então, pouco a pouco, contrastando com você, com tu, ela se torna consciente de si mesma. Essa consciência é uma consciência refletida. Ela não está consciente de quem ela é. Ela está simplesmente consciente da mãe e do que ela pensa a seu respeito. Se a mãe sorri, se a mãe aprecia a criança, se diz 'você é bonita', se ela a abraça e a beija, a criança sente-se bem a respeito de si mesma. Assim, um ego começa a nascer. Através da apreciação, do amor, do cuidado, ela sente que é ela boa, ela sente que tem valor, ela sente que tem importância. Um centro está nascendo. Mas esse centro é um centro refletido. Ele não é o ser verdadeiro. A criança não sabe quem ela é; ela simplesmente sabe o que os outros pensa a seu respeito. E esse é o ego: o reflexo, aquilo que os outros pensam. Se ninguém pensa que ela tem alguma utilidade, se ninguém a aprecia, se ninguém lhe sorri, então, também, um ego nasce - um ego doente, triste, rejeitado, como uma ferida, sentindo-se inferior, sem valor. Isso também é ego. Isso também é um reflexo.";
	int msg_lenght = (int) strlen (msg);

	Key *key;
	Cypher *original;
	Cypher *encripted;
	Cypher *desencripted;
	Cypher *breaked;

	key = (Key *)calloc(1,sizeof(Key));
	key->msg = (char *)calloc(size_key,sizeof(char));
	key->index = (int *)calloc(size_key,sizeof(int));

	original = (Cypher *)calloc(1,sizeof(Cypher));
	original->msg = (char *)calloc(msg_lenght,sizeof(char));
	original->lenght = msg_lenght;

	encripted = (Cypher *)calloc(1,sizeof(Cypher));
	encripted->msg = (char *)calloc(msg_lenght,sizeof(char));	
	encripted->lenght = msg_lenght;

	desencripted = (Cypher *)calloc(1,sizeof(Cypher));
	desencripted->msg = (char *)calloc(msg_lenght,sizeof(char));	
	desencripted->lenght = msg_lenght;

	breaked = (Cypher *)calloc(1,sizeof(Cypher));
	breaked->msg = (char *)calloc(msg_lenght,sizeof(char));	
	breaked->lenght = msg_lenght;

	strcpy(original->msg, msg);

	arq = fopen("key.txt", "rt");
 	if(arq == NULL)
		printf("Erro, nao foi possivel abrir o arquivo\n");
	
	while (!feof(arq)){
		result = fgets(key->msg, 100, arq);  
		if (result)
			printf("key: %s", key->msg);
		i++;
	}

	
	key->lenght = (int) strlen(key->msg);

	//Pegando o vetor de index
	get_indexKey(key);
	
	//Tirando os espaços em branco
	remove_whitespaces(original);
	original->lenght = (int) strlen(original->msg);
	
	//Preenchendo os espaços restantes
	fill_spaces(original);
	original->lenght = (int) strlen(original->msg);
	//Cifrando o texto
	cipher(key, original, encripted);
	encripted->lenght = (int) strlen(encripted->msg);
	//Decifrando o texto
	decipher(key, encripted, desencripted);
	
	for(j = 0; j < size_key;j++){
		printf("%d", key->index[j]);
	}

	printf("\nNormal: %s\n", original->msg);
	printf("\n\n");
	printf("Ciphed: %s\n", encripted->msg);
	printf("\n\n");
	printf("Deciphed: %s\n", desencripted->msg);
	printf("\n\n");
	
/*
	int key_break_size = 0;
	for (int i = 1; i <= 8; i++){
		key_break_size = i;
		permutations(K_SIZE, text);
    	}*/	

	//cypher(key, original, encripted);
	free(key);
	free(original);	
	free(encripted);
	free(desencripted);

	return 0;

}
Exemplo n.º 17
0
Arquivo: cipher.cpp Projeto: hyps/DGT
void Cipher::decrypt(KeyDerivation& kd, EncryptedPacket& in, PlainPacket& out)
{
  uint32_t len = decipher(kd, in.getPayload() , in.getPayloadLength(), out, out.getLength(), in.getSeqNr(), in.getSenderId(), in.getMux());
  out.setLength(len);
}
Exemplo n.º 18
0
int main(int argc, char **argv) {

	char key[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	FILE *fin = stdin;

	/*
	 * Get command line arguments. Setup key and input location
	 */
	switch (argc) {
		case 2:
			fin = fopen(argv[1], "r");
			if (fin == NULL) {
				printf("Invalid file: %s. Unable to open for reading.\n", argv[3]);
				return -1;
			}
		case 1:
			if (!removeLetter(key, 'J')) {
				printf("Could not remove letter J from cipher key.\n");
				return -1;
			}
			break;
		case 4:
			fin = fopen(argv[3], "r");
			if (fin == NULL) {
				printf("Invalid file: %s. Unable to open for reading.\n", argv[3]);
				return -1;
			}
		case 3:
			if (strcmp(argv[1], "-r")) {
				printf("Optional parameter '-r' not found. '%s' found instead.\n", argv[1]);
				return -1;
			}
			if(!removeLetter(key, argv[2][0])) {
				printf("Could not remove letter %c from cipher key.\n", argv[2][0]);
				return -1;
			}
			break;
		default:
			printf("Invalid usage. See below for proper usage.\n");
			printf("\t./%s [ -r <character_to_remove> ] [ ciphertext_filepath ]\n", argv[0]);
			return -1;
	}

	/*	
	 * Input cipher and ensure it is valid
	 */
	char *ciphertext, *plaintext;
	int messageLen;
	ciphertext = readCipher(fin, INPUT_STEP_SIZE);
	messageLen = strlen(ciphertext);
	if (validateText(ciphertext, &messageLen) != 0) {
		free(ciphertext);
		return -1;
	}
	ciphertext = realloc(ciphertext, sizeof(*ciphertext) * (messageLen + 1));
	ciphertext[messageLen] = '\0';
	plaintext = calloc(messageLen + 1, sizeof(*plaintext));
	strcpy(plaintext, ciphertext);	
	
	// close the file as long as it is not stdin
	if (fin != stdin)
		fclose(fin);

	// Output relevant information for error checking
	printf("Attempting to crack the following ciphertext with key: %s\n", key);
	printf("%s\n", ciphertext);

	int iter = 0;
	double score = -DBL_MAX, maxScore = -DBL_MAX;
	srand(time(NULL)); // randomize seed
	// Run until max iteration met 
	while (iter < MAX_ITERATIONS) {
		iter++;
		score = simulatedAnnealing(key, ciphertext, plaintext, messageLen);
		if (score > maxScore) {
			maxScore = score;
			decipher(key, ciphertext, plaintext, messageLen);
			printf("\nPossible Plaintext found using key:\n");
			outputKey(key);
			printf("%s\n\n", plaintext);
		}
	}
	
	free(plaintext);
	free(ciphertext);
	return 0;
}
int main(void)		//beginning of main function
{
	DDRA=asmfunction();	//set PORTA to write
	DDRB=0xFF;			//set PORTB to write
	DDRC=0xFF;			//set PORTC to write
	DDRD=0b10111011;	//set PIND2 and PIND6 to read and the rest of PORTD to write

	PORTB=PORTB&0b01111111;	//set PINB7 to logic zero (turn on green LED)
	PORTB=PORTB|0b01000000;	//set PINB6 to logic one (turn off red LED)
	PORTD=0b01000100;		//enable pull-up resistors of PIND2 and PIND6

	lcd_init();		//initialize LCD display
	lcd_clear();	//clear LCD display
	lcd_home();		//set cursor of LCD to the first character position

	/*The next two lines configure T/C0 and T/C2 to set OCR0 and OCR2, respectively on compare match when
	  the T/C subsystem's respective counting register is counting up and to clear OCR0 and OCR2 when counting
	  down. Configured as Fast PWM, Phase-Correct with a prescalar of one.*/
	TCCR2=(1<<WGM20)|(1<<COM21)|(1<<COM20)|(1<<CS20);
	TCCR0=(1<<WGM00)|(1<<COM01)|(1<<COM00)|(1<<CS00);

	/*The next two lines configure TCNT1 to increment every clock cycle; Configure Enable Input Capture Interrupt
	  to trigger on rising edge; Enable Input Capture Noise Canceller; Locally enable T/C 1 Input Capture Interrupt
	  and T/C 1 Overflow Interrupt.*/
	TCCR1B=(1<<ICES1)|(1<<CS10)|(1<<ICNC1);
	TIMSK=(1<<TICIE1)|(1<<TOIE1);

	MCUCR=(1<<ISC00)|(1<<ISC01);//configure external interrupt 1 to trigger on rising edge
	GICR=(1<<INT0);				//locally enable external interrupt 1

	sei();	//set global interrupt flag

	unsigned long int button=0;	//unsigned long integer (32 bits--sent by IR remote)
	uint8_t led=0;				//state of LED (used to confirm 34-bit transmission by IR remote)
	int speed=0;				//speed of motors at maximum
	int lights=off;

	lcd_printf("Waiting");		//print "Waiting" on LCD (wait for button to be pushed on IR remote)

	PORTB=PORTB|0b00000010;

	while(1)	//infinite loop
	{
		if(bit==34)	//wait until bit=34--Input Capture ISR called 34 times (1 start bit, 32 data bits, and 1 stop bit sent by IR remote)
		{
			button=decipher(remote);	//decipher the 32 data bits as either 1 or 0 depending on TCNT1 values;
										//pass remote as parameter and set button equal to return value
			bit=0;						//reset bit equal to 0 (prepare to receive a new command)

			if(led==0)	//if the state of led is 0, turn off green LED and turn on red LED
			{			//then switch the state of led to 1
				PORTB=PORTB&0b10111111;
				PORTB=PORTB|0b10000000;
				led++;
			}
			else		//if the state of led is not 0 (state is 1), turn off red LED and turn on green LED
			{			//then switch the state of led to 0
				PORTB=PORTB&0b01111111;
				PORTB=PORTB|0b01000000;
				led--;
			}
			switch(button)	//check the value of button (button that was pushed on remote)
			{
				case up_arrow:			//if up arrow was pushed, make robot go forward
							forward();
							break;
				case down_arrow:		//if down arrow was pushed, make robot go backward
							backward();
							break;
				case left_arrow:		//if left arrow was pushed, make robot go left
							left();
							break;
				case right_arrow:		//if right arrow was pushed, make robot go right
							right();
							break;
				case channel_up:		//if channel up was pushed, speed robot up (speed is parameter sent to speed_up function); speed equals returned value
							speed=speed_up(speed);
							break;
				case channel_down:		//if channel down was pushed, slow robot down (speed is parameter sent to speed_down function); speed equals returned value
							speed=slow_down(speed);
							break;
				case mute:				//if mute was pushed, toggle lights from off to on or on to off; pass lights as parameter and set lights equal to returned value
							lights=toggle_lights(lights);
							break;
				default:				//if any other button was pushed, stop robot
							stop();
							break;
			}
		OCR0=speed;		//set the speed of the left motor depending on value of speed
		OCR2=speed;		//set the speed of the right motor depending on value of speed
		}
	}
}
Exemplo n.º 20
0
main()
{	int i;
	char *p;
	uid = getuid();
	myname = getlogin();
	if(myname == NULL)
		myname = getpwuid(uid)->pw_name;
	comminit();
	mbuf = itom(0);
	files();
	setup(getpass("Key: "));
	mkb();
	mkx();
#ifndef debug
	invert(x, b, x);
#else
	invert(x, b, z);
	mult(x, z, z);
	mdiv(z, b, q, z);
	omout(z);
	invert(x, b, x);
#endif
	for(i=0; i<fcnt; i++)
	{	sprintf(line, "%s%s.%d", maildir, myname, fnum[i]);
		if(stat(line, &stbuf)<0)
		{	perror(line);
			continue;
		}
		if(stbuf.st_size == 0)
		{	printf("zero length mail file\n");
			unlink(line);
			continue;
		}
		if((mf = fopen(line, "r"))==NULL)
		{	perror(line);
			continue;
		}
		decipher(mf, stdout);
	cmnd:
		printf("? ");
		fgets(buf, sizeof(buf), stdin);
		if(feof(stdin)) exit(0);
		switch(buf[0])
		{
		case 'q':
			exit(0);
		case 'n':
		case 'd':
		case '\n':
			unlink(line);
			fclose(mf);
			break;
		case '!':
			system(buf+1);
			printf("!\n");
			goto cmnd;
		case 's':
		case 'w':
			rewind(mf);
			if(buf[1] == '\n' || buf[1] == '\0')
				strcpy(buf, "s mbox\n");
			for(p=buf; !isspace(*p); p++);
			for(; isspace(*p); p++);
			p[strlen(p)-1] = 0;
			kf = fopen(p, "a");
			if(kf == NULL)
			{	perror(p);
				break;
			}
			decipher(mf, kf);
			fclose(mf);
			fclose(kf);
			unlink(line);
			break;
		}
	}
	exit(0);
}
Exemplo n.º 21
0
int main(int argc, char * const argv[])
{
	int err = 0, r, c, long_optind = 0;
	int do_decipher = 0;
	int do_sign = 0;
	int action_count = 0;
        struct sc_pkcs15_object *key;
	sc_context_param_t ctx_param;

	while (1) {
		c = getopt_long(argc, argv, "sck:r:i:o:f:Rp:vw", options, &long_optind);
		if (c == -1)
			break;
		if (c == '?')
			util_print_usage_and_die(app_name, options, option_help, NULL);
		switch (c) {
		case 's':
			do_sign++;
			action_count++;
			break;
		case 'c':
			do_decipher++;
			action_count++;
			break;
		case 'k':
			opt_key_id = optarg;
			action_count++;
			break;
		case 'r':
			opt_reader = optarg;
			break;
		case 'i':
			opt_input = optarg;
			break;
		case 'o':
			opt_output = optarg;
			break;
		case 'f':
			opt_sig_format = optarg;
			break;
		case 'R':
			opt_raw = 1;
			break;
		case OPT_SHA1:
			opt_crypt_flags |= SC_ALGORITHM_RSA_HASH_SHA1;
			break;
		case OPT_SHA256:
			opt_crypt_flags |= SC_ALGORITHM_RSA_HASH_SHA256;
			break;
		case OPT_SHA384:
			opt_crypt_flags |= SC_ALGORITHM_RSA_HASH_SHA384;
			break;
		case OPT_SHA512:
			opt_crypt_flags |= SC_ALGORITHM_RSA_HASH_SHA512;
			break;
		case OPT_SHA224:
			opt_crypt_flags |= SC_ALGORITHM_RSA_HASH_SHA224;
			break;
		case OPT_MD5:
			opt_crypt_flags |= SC_ALGORITHM_RSA_HASH_MD5;
			break;
		case OPT_PKCS1:
			opt_crypt_flags |= SC_ALGORITHM_RSA_PAD_PKCS1;
			break;
		case 'v':
			verbose++;
			break;
		case 'p':
			opt_pincode = optarg;
			break;
		case OPT_BIND_TO_AID:
			opt_bind_to_aid = optarg;
			break;
		case 'w':
			opt_wait = 1;
			break;
		}
	}
	if (action_count == 0)
		util_print_usage_and_die(app_name, options, option_help, NULL);

	if (!(opt_crypt_flags & SC_ALGORITHM_RSA_HASHES))
		opt_crypt_flags |= SC_ALGORITHM_RSA_HASH_NONE;

	memset(&ctx_param, 0, sizeof(ctx_param));
	ctx_param.ver      = 0;
	ctx_param.app_name = app_name;

	r = sc_context_create(&ctx, &ctx_param);
	if (r) {
		fprintf(stderr, "Failed to establish context: %s\n", sc_strerror(r));
		return 1;
	}

	if (verbose > 1) {
		ctx->debug = verbose;
		sc_ctx_log_to_file(ctx, "stderr");
	}

	err = util_connect_card(ctx, &card, opt_reader, opt_wait, verbose);
	if (err)
		goto end;

	if (verbose)
		fprintf(stderr, "Trying to find a PKCS #15 compatible card...\n");
	if (opt_bind_to_aid)   {
		struct sc_aid aid;

		aid.len = sizeof(aid.value);
		if (sc_hex_to_bin(opt_bind_to_aid, aid.value, &aid.len))   {
			fprintf(stderr, "Invalid AID value: '%s'\n", opt_bind_to_aid);
			return 1;
		}

		r = sc_pkcs15_bind(card, &aid, &p15card);
	}
	else   {
		r = sc_pkcs15_bind(card, NULL, &p15card);
	}
	if (r) {
		fprintf(stderr, "PKCS #15 binding failed: %s\n", sc_strerror(r));
		err = 1;
		goto end;
	}
	if (verbose)
		fprintf(stderr, "Found %s!\n", p15card->tokeninfo->label);

	if (do_decipher) {
		if ((err = get_key(SC_PKCS15_PRKEY_USAGE_DECRYPT, &key))
		 || (err = decipher(key)))
			goto end;
		action_count--;
	}

	if (do_sign) {
		if ((err = get_key(SC_PKCS15_PRKEY_USAGE_SIGN|
				   SC_PKCS15_PRKEY_USAGE_SIGNRECOVER|
				   SC_PKCS15_PRKEY_USAGE_NONREPUDIATION, &key))
		 || (err = sign(key)))
			goto end;
		action_count--;
	}
end:
	if (p15card)
		sc_pkcs15_unbind(p15card);
	if (card) {
		sc_unlock(card);
		sc_disconnect_card(card);
	}
	if (ctx)
		sc_release_context(ctx);
	return err;
}
Exemplo n.º 22
0
int main(int argc, char **argv, char **envp) {
  int fd;
  int numbytes;
  struct sockaddr_storage their_addr;
  byte buf[MAXBUFLEN];
  socklen_t addr_len;

  /* setup socket, parse cmd line */
  {
    struct sockaddr_in6 ba;
    if (argc > 2) {
      fprintf(stderr, "usage: %s [interface]\n", argv[0]);
      exit(1);
    }
    ENP((fd = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP)), "listener: socket");
    if (argc == 2) {
      inet_pton(AF_INET6, "ff02::1", &(ba.sin6_addr));
      if ((ba.sin6_scope_id = if_nametoindex(argv[1])) == 0) {
	fprintf(stderr, "interface not found\n");
	exit(1);
      }
    }else{
      ba.sin6_addr = in6addr_any;
      ba.sin6_scope_id = 0;
    }
    ba.sin6_family = AF_INET6;
    ba.sin6_port = htons(SERVERPORT);
    ba.sin6_flowinfo = 0;
    ENP(bind(fd, (struct sockaddr*) &ba, sizeof ba), "listener: bind");
  }

  /* daemonize */
#ifndef DEBUG
  switch (fork()) {
  case 0:
    ENP(setsid(), "setsid");
    umask(0);
    break;
  case -1:
    perror("fork");
    exit(1);
  default:
    exit(0);
  }
#endif
    
  /* receive loop */
  addr_len = sizeof their_addr;
  while ((numbytes = recvfrom(fd, buf, MAXBUFLEN-1 , 0,
			      (struct sockaddr *) &their_addr, &addr_len)) != -1) {
    /* decode packet */
    buf[numbytes] = '\0';
    char *task = (char*) buf;
    int task_len = strlen(task);
    byte *payload = buf + task_len + 1;
    int payload_len = numbytes - task_len - 1;

    if (task[0] == '/' || strstr(task, "..")) {
      fprintf(stderr, "payload tried directory traversal\n");
      continue;
    }

    /* TODO: check if the task exists and is executable; save cpu
       cycles trying to decode messages not intended for us */

    /* decipher packet */
    if (!decipher(task, &payload, &payload_len)) {
      fprintf(stderr, "unable to decrypt payload\n");
      continue;
    }

    /* launch handler */
    int fd_payload[2];
    ENP(pipe(fd_payload), "pipe");
      
    switch (fork()) {
    case 0:
      /* redirect payload to stdio, leave stdout/err, close the rest */
      ENP(dup2(fd_payload[0], 0), "dup");
      ENP(close(fd_payload[0]),  "close");
      ENP(close(fd_payload[1]),  "close");
      ENP(close(fd),             "close");

      /* run our task task */
      char *cl_argv[2] = {task, NULL};
      execve(task, cl_argv, envp);
      perror("exec");
      exit(1);
    case -1:
      perror("fork");
      exit(1);
    }

    /* write payload to child process; the return value of write is
       intentionally ignored */
    if (task_len < numbytes)
      IGN(write(fd_payload[1], payload, payload_len)) 
    ENP(close(fd_payload[1]), "close");
    ENP(close(fd_payload[0]), "close");
    ENP(wait(NULL), "wait");
  }
    
  perror("recvfrom");
  return 1;
}
Exemplo n.º 23
0
int main(int argc, char **argv){
	if(argc != 2) return 0;
	printf("encipher(%s) => %s\n", argv[1], encipher(argv[1]));
	printf("decipher(%s) => %s\n", encipher(argv[1]), decipher(encipher(argv[1])));
	return 0;
}
Exemplo n.º 24
0
void interactive(machine *m) {
	/* Set up the ncurses interface */
	ui_info ui;
	initscr();
	start_color();
	raw(); 
	noecho(); 
	keypad(stdscr, true);

	/* Figure out the level of color support, choose attributes accordingly */
	if (has_colors()) {
		if (can_change_color()) {
			/* Best case, programmable colors */
			init_color(CLR_WHITEGRAY, 800, 800, 800); /* dull text */
			init_color(CLR_DARKGRAY, 400, 400, 400);  /* highlighted metal */
			init_color(CLR_DARKESTGRAY, 250, 250, 250); /* darkest metal */
			init_color(CLR_BRIGHTRED, 1000, 400, 400); /* coded text */
			init_pair(CP_WHEEL_PLAIN, CLR_WHITEGRAY, CLR_DARKESTGRAY);
			init_pair(CP_WHEEL_ACTIV, COLOR_WHITE, CLR_DARKGRAY);
			init_pair(CP_PLAIN, COLOR_WHITE, COLOR_BLACK);
			init_pair(CP_CODED, CLR_BRIGHTRED, COLOR_BLACK);
			init_pair(CP_BTN, COLOR_RED, CLR_DARKESTGRAY);
			init_pair(CP_BTNH, COLOR_RED, CLR_DARKGRAY);	
		} else {
			/* Second best, 8 color ncurses */
			init_pair(CP_WHEEL_PLAIN, COLOR_YELLOW, COLOR_BLUE);
			init_pair(CP_WHEEL_ACTIV, COLOR_WHITE, COLOR_RED);
			init_pair(CP_PLAIN, COLOR_WHITE, COLOR_BLACK);
			init_pair(CP_CODED, COLOR_RED, COLOR_BLACK);
			init_pair(CP_BTN, COLOR_RED, COLOR_BLUE);
			init_pair(CP_BTNH, COLOR_BLUE, COLOR_RED);
		}
		ui.attr_plain = COLOR_PAIR(CP_PLAIN);
		ui.attr_coded = COLOR_PAIR(CP_CODED);
		ui.attr_wheel_plain = COLOR_PAIR(CP_WHEEL_PLAIN);
		ui.attr_wheel_activ = COLOR_PAIR(CP_WHEEL_ACTIV) | A_BOLD;
		ui.attr_btn = COLOR_PAIR(CP_BTN);
		ui.attr_btnh = COLOR_PAIR(CP_BTNH);
	} else {
		/* No color fallback */
		ui.attr_plain = A_NORMAL;
		ui.attr_coded = A_BOLD;
		ui.attr_wheel_plain = A_REVERSE;
		ui.attr_wheel_activ = A_REVERSE | A_BOLD | A_UNDERLINE;
		ui.attr_btn = A_REVERSE | A_BOLD;
		ui.attr_btnh = ui.attr_btn;
	}
	ui.attr_lbl = A_NORMAL;
	ui.attr_lblh = A_BOLD;
	ui.chosen_wheel = -1;

	/* Make the windows */
	int topheight = 10 + m->wheelslots;
	int longestname = strlen("ring settings");
	if (longestname < m->longest_wheelname) longestname = m->longest_wheelname;
	int topwidth = 4 * m->wheelslots + 1 + longestname;
	int namelen = wcslen(m->name);
	if (namelen > topwidth) topwidth = namelen;
	ui.w_wheels = newwin(topheight, topwidth, 0, COLS-topwidth);
	int botheight = ((LINES - topheight) / 3) * 3 - 1;
	int botwidth = COLS;
	ui.w_code = newwin(botheight, botwidth, topheight, 0);
	ui.w_pop = newwin(botheight, botwidth, topheight, 0);
	draw_wheels(m, &ui);

  bool enciphering = true;		/* enchiper or dechiper */

	wchar_t plaintext[MAXLINE+1]; /* typed/dechipered text */
	wchar_t ciphertxt[MAXLINE+1]; /* typed/enchipered text */
	memset(plaintext, 0, sizeof(wchar_t)*(MAXLINE+1));
	memset(ciphertxt, 0, sizeof(wchar_t)*(MAXLINE+1));

	int textpos = 0;
  int maxpos = COLS - 2 > MAXLINE ? MAXLINE : COLS - 2;  

	curses_bug_workaround();
	wmove(ui.w_code, 1, 1);

	/* main loop. The first event has to be the KEY_RESIZE, it creates the display! */
	int rc = KEY_CODE_YES;
	wint_t wch = KEY_RESIZE; 
	for (bool active = true; active; rc = active ? get_wch(&wch) : 0) {
		switch (rc) {
			case KEY_CODE_YES:		/* specials */
				switch (wch) {
					case KEY_F(1):
						highlight_wheel(m, &ui, 0);
						break;
					case KEY_F(2):
						highlight_wheel(m, &ui, 1);
						break;
					case KEY_F(3):
						highlight_wheel(m, &ui, 2);
						break;
					case KEY_F(4):
						highlight_wheel(m, &ui, 3);
						break;
					case KEY_F(5):
						highlight_wheel(m, &ui, 4);
						break;
					case KEY_F(6):
						highlight_wheel(m, &ui, 5);
						break;
					case KEY_F(7):
						highlight_wheel(m, &ui, 6);
						break;
					case KEY_F(8):
						highlight_wheel(m, &ui, 7);
						break;
					case KEY_F(9):
						highlight_wheel(m, &ui, 8);
						break;
					case KEY_LEFT:
						highlight_left(m, &ui);
						break;
					case KEY_RIGHT:
						highlight_right(m, &ui);
						break;
					case KEY_F(10):
						highlight_wheel(m, &ui, 9);
						break;
					case KEY_NPAGE:
						next_wheel(m, &ui);
						break;
					case KEY_UP:
						if (ui.chosen_wheel == -1) {		
							/* switch to encoding */
							enciphering = true;
							wmove(ui.w_code, 1, textpos+1);
							wnoutrefresh(ui.w_code);
						} else wheel_turn(m, &ui, -1);
						break;
					case KEY_DOWN:
						if (ui.chosen_wheel == -1) {		
							/* switch to decoding */
							enciphering = false;
							wmove(ui.w_code, 2, textpos+1);
							wnoutrefresh(ui.w_code);
						} else wheel_turn(m, &ui, 1);		
						break;
					case KEY_RESIZE:	/* user resized the xterm - redraw all! */
						curses_bug_workaround();//Remove, and top window blanks out
						/* Must repaint all, as downsizing may blank the terminal */
						
						/* Deal with the code wheel window */
						botheight = ((LINES - topheight) / 3) * 3 - 1;
						botwidth = COLS;
						wresize(ui.w_code, botheight, botwidth);
						wresize(ui.w_pop, botheight, botwidth);
						int oldx = getbegx(ui.w_wheels);
						int newx = COLS-topwidth;
						mvwin(ui.w_wheels, 0, COLS-topwidth); /* move the window */
						/* now clear out the exposed screen area */
						if (newx > oldx) {
							int xlen = newx-oldx;
							char *spc = malloc(xlen+1);
							memset(spc, ' ', xlen);
							spc[xlen] = 0;
							for (int i=0; i < topheight; ++i) mvprintw(i, oldx, spc);
							free(spc); 
						}
						wnoutrefresh(ui.w_wheels);
						curses_bug_workaround(); //Remove, and the cursor will misplaced when upsizing
						

						/* Now the code text window */
						maxpos = COLS - 2 > MAXLINE ? MAXLINE : COLS - 2;  
                  
						if (textpos > maxpos) {
							leftcut(plaintext, textpos - maxpos, maxpos+1);
							leftcut(ciphertxt, textpos - maxpos, maxpos+1);
							textpos = maxpos;
							wattrset(ui.w_code, ui.attr_plain);
							mvwprintw(ui.w_code, 1, 1, "%ls", plaintext);wclrtoeol(ui.w_code);
							wattrset(ui.w_code, ui.attr_coded);
							mvwprintw(ui.w_code, 2, 1, "%ls", ciphertxt);wclrtoeol(ui.w_code);
							if (enciphering) wmove(ui.w_code, 1, textpos+1);
						}

						wnoutrefresh(ui.w_code);
						break;
				}
				break;
			case OK:
				if (iscntrl(wch)) switch (wch) {
					/* ctrl tv change ring settings */
					case 20:
						ringstellung(m, &ui, -1);
						break;
					case 22:
						ringstellung(m, &ui, 1);
						break;
					/* quit on ctrl+c */	
					case 3:
						active = false;
						break;
					/* unselect wheel on enter */
						case '\n':
							highlight_wheel(m, &ui, -1);
							wnoutrefresh(ui.w_code);
							break;
				}							
				/* plain typing */
				else { 
					if (ui.chosen_wheel > -1) highlight_wheel(m, &ui, -1);
					/* Need a line break first? */
					if (textpos >= maxpos) {
						/* add scrolling later !!! for now, just clear */
						textpos = 0;
						memset(plaintext, 0, sizeof(wchar_t)*(MAXLINE+1));
						memset(ciphertxt, 0, sizeof(wchar_t)*(MAXLINE+1));
						if (enciphering) {
							wmove(ui.w_code, 2, textpos+1); wclrtoeol(ui.w_code);
							wmove(ui.w_code, 1, textpos+1); wclrtoeol(ui.w_code);
						} else {
							wmove(ui.w_code, 1, textpos+1); wclrtoeol(ui.w_code);
							wmove(ui.w_code, 2, textpos+1); wclrtoeol(ui.w_code);
						}
					}
					if (enciphering) {
						plaintext[textpos] = wch;
						ciphertxt[textpos] = encipher(m, wch, &ui);
						wattrset(ui.w_code, ui.attr_coded);
						mvwprintw(ui.w_code, 2, 1, "%ls", ciphertxt);
						wattrset(ui.w_code, ui.attr_plain);
						mvwprintw(ui.w_code, 1, 1, "%ls", plaintext);
					} else {
						ciphertxt[textpos] = wch;
						plaintext[textpos] = decipher(m, wch, &ui);
						wattrset(ui.w_code, ui.attr_plain);
						mvwprintw(ui.w_code, 1, 1, "%ls", plaintext);
						wattrset(ui.w_code, ui.attr_coded);
						mvwprintw(ui.w_code, 2, 1, "%ls", ciphertxt);
					}
					textpos++;
					wnoutrefresh(ui.w_wheels);
					wnoutrefresh(ui.w_code);
					break;
				}
		} 
		doupdate();
	}
	endwin();
}
Exemplo n.º 25
0
/* MAIN FUNCTION */
int main (int argc, char** argv) {

  char o;                /* used for getopt */
  char tstamp[200];      /* used for create different titles for log files*/
  FILE *msg_file = NULL; /* message file */
  int dec_f = 0,         /* dechiper mode flag */
      K1,                /* first key */
      K2,                /* second key */
      offset;            /* offset for command line */

  /* searching options */
  while ((o = getopt(argc, argv, "dwh")) != -1) {
    switch (o) {
      case 'd' :
        dec_f = 1;
        break;
      case 'w' :
        log_f = 1;
        break;
      case 'h' :
        print_usage();
        exit(EXIT_SUCCESS);
      case '?' :
        failure("Unknown option. Please use option -h for help.");
        break;
    }
  }

  /* timestamp setting */
  sprintf(tstamp,"message-%u.txt",(unsigned) time(NULL));

  /* checking args number */
  if(argc < 4)
    failure("Missing arguments. Please use option -h for help.");

  /* setting offset for cmd line */
  switch(argc) {
    case 5 : {offset = 1;break;}
    case 6 : {offset = 2;break;}
    case 7 : {offset = 3;break;}
    default: {offset = 0;}
  }

  /* opening message's file */
  if((msg_file = fopen(argv[1+offset],"r")) == NULL){
    perror("Cannot open the file you specified.");
    failure("Fatal error.");
  }

  /* opening log file if requested */
  if(log_f){
    if((log_file = fopen(tstamp,"ab+")) == NULL){
      perror("Cannot open the log file.");
      failure("Fatal error.");
    }
  }

  /* setting keys */
  K1 = strtol(argv[2+offset], NULL, 10);
  if(errno == ERANGE || errno == EINVAL){
    failure("First key is too long or not in base 10.");
  }
  if(K1 < 1 || K1 == 13 || K1 > 25 || K1%2 == 0){
    failure("First key is not valid. Please use option -h for help.");
  }
  K2 = strtol(argv[3+offset], NULL, 10);
  if(errno == ERANGE || errno == EINVAL){
    failure("Second key is too long or not in base 10.");
  }
  K2 = K2%26;
  if(K1==1 && K2==0)
    fprintf(stderr, "[!!!] WARNING: You chose the neutral key combination, the message will not be ciphered.\n");

  /* chosing the mode */
  if(dec_f)
    decipher(msg_file, K1, K2);
  else
    cipher(msg_file, K1, K2);

  /* closing files */
  fclose(msg_file);
  if(log_f)
    fclose(log_file);

  return EXIT_SUCCESS;

}