예제 #1
0
/**
 * Quick usage demonstration
*/
int main(int argc, char**argv) {
	size_t scheme;

	if(argc != 3) {
		return -1;
	}

	if(!(scheme = atoi(argv[1]))) {
		return -1;
	}


	encryption(argv[2], scheme, cypher);
	printf("===============\n"
		"Encrypted text\n\n"
		"%s\n"
		"==============\n", argv[2]);

	printf("\n");

	encryption(argv[2], scheme, decypher);
	printf("==============\n"
		"Decrypted text\n\n"
		"%s\n"
		"==============\n", argv[2]);
	
	
	return 0; 
}
void Client_Send_Encrypt(mpz_t tab_cli[MAX_GRID_SIZE], int col)
{
    for (int i = 0; i < MAX_GRID_SIZE; i++)
    {
        mpz_init_set_ui(tab_cli[i], 0);
        encryption(tab_cli[i], tab_cli[i], KPub);
    }

    mpz_set_ui(tab_cli[col], 1);
    encryption(tab_cli[col], tab_cli[col], KPub);
}
// Function to test encryption algorithm.
void testEncryption(void){
	// Initialization of variables.
	FILE *outfile;
	char testStr[] = { "TESTA" }, *pHolder = { '\0' }, *nHolder = { '\0' };
	char strHold[] = "VGUVC"; // For first Hold
	char strNold[] = "RCQRY"; // For second Hold
	int positiveKey = 0, negativeKey = 0;

	outfile = fopen("Test_File_PA1_encryption", "w"); // Create an output file that will display the results of the test.
													  // this prevents interruption from the user while they complete the main program.

	// If the output file was not able to be created - this error message will be displayed to the user.
	if (outfile == NULL){
		printf("ERROR OUTPUT - the output file was not able to be created\n");
	}

	// Hard code of the key used in the encryption process.
	// This is for testing purposes to show the encryption algorithm can handle the key.
	positiveKey = 2;
	negativeKey = -2;

	// Call and assign results from the encryption algorithm to the char pointers to be checked in the test.
	pHolder = encryption(testStr, positiveKey);
	nHolder = encryption(testStr, negativeKey);

	// The check is performed here to determine if the place holder matches the literal string.
	// This check could have been done in a for-loop but I decided to do one large if statement as I did not want to print
	// to the output 5 times.
	if ((pHolder[0] == strHold[0]) && (pHolder[1] == strHold[1]) && (pHolder[2] == strHold[2]) && (pHolder[3] == strHold[3]) && (pHolder[4] == strHold[4])){
		fprintf(outfile, "The Encrytped Phrase: %s\nEncryption passed the positive key.\n", pHolder);
	}
	else {
		// Should the encryption not equal the place holder then this else statement is executed.
		fprintf(outfile, "Encryption did not pass the positive key correctly.\n");
	}

	// Again, the place holder string should equal the literal string and will pass the sentence to the output file that
	// the string ecryption was completed sucessfully.
	if ((nHolder[0] == strNold[0]) && (nHolder[1] == strNold[1]) && (nHolder[2] == strNold[2]) && (nHolder[3] == strNold[3]) && (nHolder[4] == strNold[4])){
		fprintf(outfile, "The Encrytped Phrase: %s\nEncryption passed the negative key.\n", nHolder);
	}
	else{
		// If the strings do not match then this sentence will be pushed to the output.
		fprintf(outfile, "Encryption did not pass the negative key correctly.\n");
	}

	fclose(outfile); // Close the outfile.
}
예제 #4
0
파일: 2.c 프로젝트: imdxt/homework_practice
int main(int argc, const char *argv[])
{
    int i,flag=1,a,b;
    char c[256];
    char d;
    while(flag)
    {
        printf("1.decimal to binary\n");
        printf("2.x*y\n");
        printf("3.low or up exchange\n");
        printf("4.encryption\n");
        printf("5.Exit\n");
        printf("Please choose [1-5]:");
        scanf("%d",&i);
        getchar();
        switch(i)
        {
            case 1:
                printf("***********************************\n");
                printf("Input a number:");
                scanf("%d",&a);
                getchar();
                get_num_bit(a);
                printf("\n*******Input Enter continue********\n");
                getchar();
                break;
            case 2:
                printf("***********************************\n");
                printf("Please input x y:");
                scanf("%d %d",&a,&b);
                getchar();
                printf("%d  *  %d  = %d\n", a, b, mul(a,b));
                printf("******Input Enter continue********\n");
                getchar();
                break;
            case 3:
                printf("*************************************\n");
                printf("Please input a string :");
                scanf("%s",c);
                getchar();
                exchange(c);
                printf("******Input Enter continue********\n");
                getchar();
                break;
            case 4:
                printf("*************************************\n");
                printf("Please input a char:");
                scanf("%c",&d);
                getchar();
                encryption(b);
                printf("******Input Enter continue*********\n");
                getchar();
                break;
            case 5:
                flag=0;
                break;
        }
    }
    return 0;
}
예제 #5
0
void main(){
/*
	char ptext[48] = {'M', 'E', 'E', 'T', 'M', 'E', 'A', 'T', 'T', 'H', 'E', 'U', 'S', 'U', 'A', 'L', 'P', 'L', 'A', 'C', 'E', 'A', 'T', 'T', 'E', 'N', 'R', 'A', 'T', 'H', 'E', 'R', 'T', 'H', 'A', 'N', 'E', 'I', 'G', 'H', 'T', 'O', 'C', 'L', 'O', 'C', 'K', 'X'};
	char ctext[48];
	
	int c1 = 0;
	int c2 = 0;
	int i;
	for(i=0;i<48;i+=2){
		c1 = (c_value(ptext[i])*key[0][0] + c_value(ptext[i+1])*key[1][0])%26;
		c2 = (c_value(ptext[i])*key[0][1] + c_value(ptext[i+1])*key[1][1])%26;
		ctext[i] = c1+'A';
		ctext[i+1] = c2 + 'A';
		printf("[%c %c]\t[%d %d]\t[%d %d]\t[%c%c]\n",ptext[i],ptext[i+1],c_value(ptext[i]),c_value(ptext[i+1]),c1,c2,ctext[i],ctext[i+1]);
	}
	for(i=0;i<48;i++){
		printf("%c",ctext[i]);
	}
	printf("\n");

	
*/
	encryption();
	init_inverse_key();
	decryption();

	return;
}
예제 #6
0
파일: vmod_pj.c 프로젝트: rapidoo/vmod_pj
const char *
vmod_encrypt(struct sess *sp, const char *text, const char *key )
{
	char *p;
	unsigned u, v;

	unsigned char crypt64[TAILLE];
	unsigned char ciphertext_buffer[TAILLE];
	unsigned char *ciphertext_string = &ciphertext_buffer[0];
	int ciphertext_len = 0;

	memset (crypt64, 0, TAILLE );
	memset (ciphertext_buffer, 0, TAILLE );

	u = WS_Reserve(sp->wrk->ws, 0); /* Reserve some work space */
	p = sp->wrk->ws->f;		/* Front of workspace area */
	
	encryption ((char*)key,(unsigned char*) text, (unsigned char*) ciphertext_string, (unsigned char*) crypt64, &ciphertext_len);
	
	v = snprintf(p, u, "%s", crypt64);
	v++;
	if (v > u) {
		/* No space, reset and leave */
		WS_Release(sp->wrk->ws, 0);
		return (NULL);
	}
	/* Update work space with what we've used */
	WS_Release(sp->wrk->ws, v);
	return (p);
}
예제 #7
0
파일: aes.c 프로젝트: rutvik11/nslab
int main()
{
        accept();
        generateKey();
        encryption();
        decryption();
        getch();
        return 0;
}
예제 #8
0
파일: launch.c 프로젝트: spjasen/Learning
main(int argc,char * const * argv)
{
	char text[80];
	char c=getopt(argc,argv,"ed");
	switch(c)
	{
		case 'e':
		encryption(text);
		break;
		
		case 'd':
		decryption(text);
		break;
		
		default:
		encryption(text);
	}
	return 0;
}
예제 #9
0
int test_encryption()
{
	int plainText64Bit[64]={0,0,0,0,0,0,0,1,0,0,1,0,0,0,1,1,0,1,0,0,0,1,0,1,0,1,1,0,0,1,1,1,1,0,0,0,1,0,0,1,1,0,1,0,1,0,1,1,1,1,0,0,1,1,0,1,1,1,1,0,1,1,1,1};
	int pc1Output56BitKey[56]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0};
	int cipher64Bit[64];
	encryption(plainText64Bit,pc1Output56BitKey,cipher64Bit);
	printArray(plainText64Bit,56, "plainText64Bit");
	printArray(pc1Output56BitKey,56, "pc1Output56BitKey");
	printArray(cipher64Bit,56, "cipher64Bit");

	return 0;
}
예제 #10
0
파일: Cypher.c 프로젝트: LanderlYoung/zasv
/*
 * Class:     Cypher
 * Method:    desEncryption
 * Signature: ([B[B[B)V
 */
JNIEXPORT void JNICALL Java_Cypher_desEncryption
  (JNIEnv *env, jobject obj,
   jbyteArray message, jbyteArray cypher) {
	  char* message_tmp =
		  (char*)(*env)->GetByteArrayElements(env, message, 0);
	  char cypher_tmp[8];

	  encryption(message_tmp, cypher_tmp);

	  (*env)->SetByteArrayRegion(env, cypher, 0, 8,  cypher_tmp);
	  (*env)->ReleaseByteArrayElements(env, message, message_tmp, 0);
  }
예제 #11
0
/*****************************************
 *Function: SetTimeDelay::buildPasswordSlot [slot]
 *Brief: 生成密码按键所绑定的slot判断输入的客户编
 *码,延长时间,延长/永久解锁的选项以及检测码格式是否
 *标准,并依此通过固定的加密函数生成一串用于机床延时/
 *解锁的密码
 *Param: void
 *Retval: void
 *Author: LiuBing
 *Data: 2013.11.25
*****************************************/
void SetTimeDelay::buildPasswordSlot()
{
    QString client_password = client_password_edit->text();
    QString unlock_code = unlock_code_edit->text();
    QString time_delay_day = time_delay_day_edit->text();
    QString time_delay_hour = time_delay_hour_edit->text();
    int day_str_length = time_delay_day.length();
    int hour_str_length = time_delay_hour.length();
    for(int i = 0;i < TIME_DELAY_DAY_LENGTH - day_str_length;i++){
        time_delay_day.insert(0,"0");
    }
    for(int i = 0;i < TIME_DELAY_HOUR_LENGTH - hour_str_length;i++){
        time_delay_hour.insert(0,"0");
    }
    QString time_delay = time_delay_day + time_delay_hour;
    QString state_code = "0";
    if(time_delay_radio->isChecked()){
        state_code = QString(TIME_DELAY_STATE_CODE);
    }else if(relieve_limit_time_radio->isChecked()){
        state_code = QString(RELIEVE_LIMIT_TIME_STATE_CODE);
    }
    int version = version_box->currentIndex();
    QString password;

    qDebug("%s,%s,%s,%s\n",unlock_code.toAscii().data(),client_password.toAscii().data(),time_delay.toAscii().data(),state_code.toAscii().data());

    if(client_password.isEmpty() || client_password.isNull()){
        QMessageBox::warning(this,"","请输入客户编码!");
        client_password_edit->setFocus();
    }else if(client_password.length() != CLIENT_PASSWORD_LENGTH){
        QMessageBox::warning(this,"","客户编码必须为8位!");
        client_password_edit->setFocus();
        client_password_edit->selectAll();
    }else if(unlock_code.isEmpty() || unlock_code.isNull()){
        QMessageBox::warning(this,"","请输入限时保护检测码!");
        unlock_code_edit->setFocus();
    }else if(unlock_code.length() != UNLOCK_CODE_LENGTH){
        QMessageBox::warning(this,"","限时保护检测码无效!");
        unlock_code_edit->setFocus();
        unlock_code_edit->selectAll();
    }else if(!encryption(version,unlock_code,client_password,time_delay,state_code,password)){
        QMessageBox::warning(this,"","密码生成失败!");
    }else{
        build_password_edit->setText(password);
        QMessageBox::information(this,"","密码生成成功!");
    }
}
예제 #12
0
파일: scytale1.c 프로젝트: pinaki1994/class
int main(){
	int n;
	char *cyphertext;
	char *str; 
	printf("%s\n", "enter a string");
	scanf("%s",str);
	printf("%s\n", "enter the key : ");
	scanf("%d", &n);

	cyphertext = encryption(str,n);

	printf("%s\n", cyphertext);
	printf("\n");
	decryption(cyphertext,n);
	
	return 0;

}
예제 #13
0
//密码流生成函数
//输入:S序列,plain原文
//输出:Z序列,code密文
int generate_key_stream(int *S, int *Z, int *plain, int *code)
{
	int i,j,k;
	i=0;
	j=0;
	k=0;
	int loop_times=0;
	
	while(loop_times<4)
	{
		i=(i+1)%4;

		j=(j+ S[i])%4;
		swap(&S[i], &S[j]);
		Z[loop_times]=S[(S[i]+S[j]) % 4];
#if 0
		printf("%d round\n", loop_times);
		for(k=0; k<4; k++)
		{
			printf("Z[%d]= %x ", k, Z[k]);
			printf("S[%d]= %x ", k, S[k]);
		}
		printf("\n");
#endif
		loop_times++;
	}

	for(i=0; i<4; i++)
	{
		code[i] = encryption(plain[i], Z[i]);
	}

#if 0
	printf("after generate \n");
	for(i=0; i<4; i++)
	{
		printf("S[%d]= %x ", i, S[i]);
		printf("Z[%d]= %x ", i, Z[i]);
	}
	printf("\n");
#endif

	return 0;
}
예제 #14
0
파일: main.c 프로젝트: Caoxiann/CCpp2016
int main(int argc, const char * argv[]) {
    // insert code here...
    printf("please enter your code\n");
    scanf("%s",code);
    
    encryption();
    printf("your code after encrypted:%s\n",code);
    
    printf("do you want to encry your code? y/n \n");
    if(decision()==1) {
        decryption();
        printf("your code after decryption:%s\n",code);
    }else{
        printf("欢迎再次使用本加密系统\n");
    }
    
    
    return 0;
}
예제 #15
0
int main(int argc, char const *argv[])
{
	int n;
	char *s,*cypher;
	printf("Enter the key for encryption\n");
	scanf("%d",&n);
	printf("Enter the plain text: \n");
	scanf("%s",s);
	cypher = encryption(s,n);
	printf("%s",cypher);
	printf("\n");
	decryption(cypher,n);

	// printf("Plain text is\n");
	// for(j = 0; j < COLUMN ; j++)
	// 	for (i = 0; i < ROW; i++)
	// 	 {
	// 	 	printf("%c",tolower(Matrix[i][j]) );
	// 	 } 
	// printf("\n");
	return 0;
}
예제 #16
0
void pack::GoPack()
{
    /*
    *    step1:    结构化文件索引
    *    step2:    保存资源并写入包(同时加密)
    *    step3:    保存索引文件
    */
	if(_wfopen_s(&fpOut, dir_out, _T("wb+"))==0)
	{
		TiXmlDocument xml;
        	xml.Parse("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
        	// 对文件夹进行遍历并复制内容到封包文件中
        	long size = PackFolder(dir_in, reinterpret_cast<TiXmlElement*>(&xml));
        	fclose(fpOut);
        	//完事,下边存索引
        	FILE* fpIndex;//一次性搞定
        	if (_wfopen_s(&fpIndex, dir_index, _T("wb+")) == 0)
	        {
	            xml.SaveFile(fpIndex);
	            // 加密索引文件
	            fseek(fpIndex, 0, SEEK_SET);
	            short ch;
	            while ((ch = fgetc(fpIndex)) != EOF)
	            {
	                // 逐字节取出,处理后送回
	                fseek(fpIndex, -1, SEEK_CUR); // 指针移动回来
	                encryption(ch); // 加密
	                fputc(ch, fpIndex);
	                fseek(fpIndex, 0, SEEK_CUR); // 刷新缓冲区,因为对于一个可写可读流,不能在一次读之后马上进行一次写,或者进行一次写之后马上进行一次读
	            }
	            fclose(fpIndex);
	        }
	        else
	        {throw 1;}
	else
	{throw 0;}
예제 #17
0
파일: Utils2.cpp 프로젝트: MFDonadeli/PMA
/**
\brief Criptografa ou descriptografa buffers
\details Utiliza algoritmo Blowfish
\param char * BufEnt - buffer a ser processado
\param char * BufSai - buffer processado
\param char* Senha - senha a ser utilizada
\param BOOL decrypt - default FALSE - se presente e TRUE operação é de descriptografar
\return número de bytes do buffer de saída.
*/
int CUtils2::CriptoBuffer(char * BufEnt, char * BufSai, char* Senha, int bufSize, BOOL decrypt)
{
	//char * pass = "******";
	const CStringA sW(CUtils2::GetPwd());

	BlowFishEnc encryption( sW );

	int encRet;
	if (decrypt)
	{
		encRet = encryption.decryptStream(BufEnt, (DWORD)bufSize, BufSai);
		int pos = 0;
		// removing trailing zeros - encrypted file must be x8 bytes.
		while ((pos < 8) && ((BufSai + (encRet-1) - pos)[0] == 0)) pos++;
		// if found trailing zeros - decreasing the writing buffer marker (not writing them).
		if (pos) encRet -= (pos);
	}
	else
	{
		encRet = encryption.encryptStream(BufEnt, (DWORD)bufSize, BufSai);
	}
	
	return encRet;
}
예제 #18
0
int main(int argc, const char *argv[])
{
    int flag=0;
    while(1)
    {
        info();
        scanf("%d",&flag);
        getchar();
        if(flag==1)
        {
            print_b();    
            continu();
        }
        if(flag==2)
        {
            mul();
            continu();
        }
        if(flag==3)
        {
            flag=0;
            exchange_s();
            continu();
        }
        if(flag==4)
        {
            encryption();
            continu();
        }
        if(flag==5)
        {
            break;
        }
    }
    return 0;
}
예제 #19
0
int main(int argc, char *argv[]){

  int target_port,local_port;
  char *target_ip,*local_ip;
  if(argc !=5){
	  printf("please enter arguments in format:./name target_ip,target_port,local_ip,local_port\n");
  }
  target_ip = argv[1]; // reserver ip information for future extension
  target_port = atoi(argv[2]);
  local_ip =argv[3];
  local_port = atoi(argv[4]);
  // printf("the target ip is :%s\nthe target port is:%d\n",target_ip,target_port);

  //start listening
  int args[2];
  args[0] = local_port;
  args[1] = target_port;
  pthread_t hear;
  Pthread_create(&hear,NULL,start_listen,(void*)args);
  Pthread_detach(hear);

  //create connectionfd with server
  int targetfd;
  targetfd = open_clientfd(target_ip,target_port);
  if(targetfd < 0){
    printf("targetfd error!\n");
    return EXIT_FAILURE;
   }
 
  char *cmd, *signature;
  //hand shake start

  //_____________send client hello infromation to server with protocol infromation_______________
  char content[MAXLINE];
  sprintf(content, "ClientHello,sslv2.0");
  rio_writen(targetfd,content,strlen(content));
  //receive response from server, confirm protocol
  int len;
  char answer[MAXLINE];
  len = rio_readp(targetfd,answer,MAXLINE);
  printf("content received from server is: %s\n",answer);
  if(strstr(answer,"ServerHello")!=NULL){
    printf("hello ends\n");
  }

  //______________________DH exchange___________________________
  int dh_g = 3;
  int dh_b = 7;
  int dh_a = 0;
  int *g_ptr = &dh_g;
  int *a_ptr = &dh_a;
  int *b_ptr = &dh_b;
  DH_change_client (targetfd, g_ptr, a_ptr,b_ptr);
  printf("After DH function: g is %d,a is %d,b is %d\n", dh_g, dh_a, dh_b);

 //receive ditial singature from server and authenticate
  len = rio_readp(targetfd,answer,MAXLINE);
    for(int i = 0;i<strlen(answer)-1;i++){
    answer[i] = answer[i]+dh_a;
  }
  cmd = strtok_r(answer,",",&signature);
  printf("signature is %s\n",signature);
  if(strcmp(signature,target_ip) == 0){
    printf("digital signature verified\n");
  }


  //create private key-public key pair and send public key to server uisng DH method
  int p = 11;
  int q = 19;
  int public_n;
  int public_e;
  int private_n;
  int private_d;
  int *public_n_ptr = &public_n;
  int *private_n_ptr = &private_n;
  int *public_e_ptr = &public_e;
  int *private_d_ptr = &private_d;
    
  RSA_generate(p,q,public_n_ptr,private_n_ptr,public_e_ptr,private_d_ptr);
  printf("public <n,e> = <%d,%d>\n", public_n, public_e);
  printf("private <n,d> = <%d,%d>\n", private_n, private_d);
  
  
   memset(content,0,sizeof(content));
  sprintf(content,"ClientKeyExchange,RSA %d %d,TLSv1",p,q);
  for (int i = 0; i<strlen(content);i++){
    content[i] = content[i]+dh_a;
  }
  rio_writen(targetfd,content,strlen(content));


  //__________________first talk______________________
  //receive infromation from server and decryption by RSA method
  memset(answer, 0, sizeof(answer));
  len = rio_readp(targetfd,answer,MAXLINE);
  char count_buffer[MAXLINE];
  memset(count_buffer, 0, sizeof(count_buffer));
  len = rio_readp(targetfd, count_buffer, MAXLINE);
  int word_count = atoi(count_buffer);
  printf("word count is: %d\n", word_count);
  char *decrypt = NULL;
  long long *ip2 = (long long *)answer;
  decrypt = decryption(ip2, word_count, private_n);
  printf("After decryption:%s\n", decrypt);



  //______________second talk_______________________
  memset(content,0,sizeof(content));
  sprintf(content,"ClientFinish");
  //encryption
  int ans_len = strlen(content);
  long long *ip = NULL;
  word_count = 0;
  int *word_count_ptr = &word_count;
  ip = encryption(content,ans_len, word_count_ptr, public_e, public_n);
  printf("Before encryption: %s\n", content);
  printf("After encryption,send:");
  char *ch = (char*)ip;
  printf("%s\n", ch);
//send content
  rio_writen(targetfd,ch,sizeof(ch)*word_count);
  //send word count
  memset(content, 0, sizeof(content));
  sprintf(content, "%d", word_count);
  printf("word count: %s\n", content);
  rio_writen(targetfd, content, sizeof(content));
  memset(content, 0, sizeof(content));
  printf("===============hand shake ends==================\n");
 
 
  printf("please input your message now\n\n");
  //start talking
  while (1){
    //send information to server
    printf("Client:");
    memset(content, 0, sizeof(content));
    scanf("%s", content);
    ans_len = strlen(content);
    ip = NULL;
    word_count = 0;
    word_count_ptr = &word_count;
    ip = encryption(content, ans_len, word_count_ptr, public_e, public_n);;
    char *ch = (char*)ip;
    //send content
    rio_writen(targetfd, ch, sizeof(ch)*word_count);
    //send word count
    memset(content, 0, sizeof(content));
    sprintf(content, "%d", word_count);
    rio_writen(targetfd, content, sizeof(content));
    memset(content, 0, sizeof(content));
    
    
    //receive information from server
    printf("Server:");
    memset(answer, 0, sizeof(answer));
    len = rio_readp(targetfd, answer, MAXLINE);
    if (strcmp(answer, "You end the talk. Sever disconnect.") == 0){
      printf("%s\n", answer);
      break;
    }
    memset(count_buffer, 0, sizeof(count_buffer));
    len = rio_readp(targetfd, count_buffer, MAXLINE);
    word_count = atoi(count_buffer);
    decrypt = NULL;
    ip2 = (long long *)answer;
    decrypt = decryption(ip2, word_count, private_n);
    printf("%s\n", decrypt);
  }
  close (targetfd);
  return EXIT_SUCCESS;
}
예제 #20
0
int process_handle(cvm_common_wqe_t * swp)
{
		int res = 1;
		list1_entry_t * list1 = list1_lookup(swp);
		if(list1 != NULL)
		{
				//printf("in list1 \n");
				//cvm_tcp_tcphdr_t is tcp head,defined in Cvm-tcp.h
				cvm_tcp_tcphdr_t *th;
				th = ((cvm_tcp_tcphdr_t *) & (swp->hw_wqe.packet_data[swp->l4_offset]));

				//如果为拆链接数据包,则需要删除相应规则列表项
				if(th->th_flags & 0x05)// fin is 0x01; rst is 0x04
				{			
											printf("find TCP rst or fin\n");
					    list1_discard_lookup_entry(swp);	
						list1 = NULL;	
						return res;
				}

				//非拆链接数据包
				http_data * http_entry = NULL;
				http_entry = http_parse(swp, list1->status);
				//检查是否为http协议数据包
				if(http_entry->is_http)
				{
						//服务器回复登录确认,说明用户成功登录			
						if(list1->status == S1)
						{
								if(http_entry->login_done == true)
								{
																			printf("login_done \n");
										hash_md5(list1->secret_key, (uint8_t*)list1->username, strlen(list1->username));

										uint8_t tmp[256];
										RC4_KEY rkey;
										int i=0;
										for(i=0;i<256;i++)
												tmp[i]=i;
										for(i=0;i<256;i++)
										{
												RC4_set_key (&rkey, 16, list1->secret_key);
												RC4 (&rkey, 1, tmp+i, list1->enc_map+i);						
										}					
										list1->status = S2;
								}
								cvm_common_free_fpa_buffer ((void*)http_entry, CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE / CVMX_CACHE_LINE_SIZE);
								http_entry = NULL;
								return res;
						}

						//用户发送上传数据命令put
						if(list1->status == S2)
						{
								//Clietn->Server
								if(http_entry->put_content == true)
								{
										printf("put content \n");
										list1->status = S3;//将list1结构体的状态设置为数据上传S3
										if(http_entry->there_is_data)//如果包含数据部分,则对数据进行加密,否则直接返回
										{
												printf("put content, encrypt first packet\n");
												encryption(list1->enc_map, swp, http_entry->pos);
												res = 0;
										}
								}
								//Server->Client
								else if(http_entry->get_content == true)
								{
										printf("get content \n");
										list1->status = S4;
										if(http_entry->there_is_data)
										{
												printf("get content, decrypt first packet\n");
												encryption(list1->enc_map, swp, http_entry->pos);
												res = 0;
										}
								}
								cvm_common_free_fpa_buffer ((void*)http_entry, CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE / CVMX_CACHE_LINE_SIZE);	
								http_entry = NULL;
								return res;	
						}


						//下载数据结束						//上传数据成功
						if((list1->status == S4 && http_entry->get_done == true) || (list1->status == S3 && http_entry->put_done))
						{
								printf("put or get done!\n");
								list1->status = S2;
								cvm_common_free_fpa_buffer ((void*)http_entry, CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE / CVMX_CACHE_LINE_SIZE);	
								http_entry = NULL;
								return res;
						}
						//printf("Waring\n");
				}
				else//在list1中,非拆链接数据包,也不带http头,应该为需要加解密的数据包,根据list1_entry.state状态机进行加解密
				{
						//数据上传过程,需要对数据进行加密	//数据下载过程,需要对数据进行解密	
						if(list1->status == S3 || list1->status == S4)
						{
								res = 0;
								//54 is the length of MAC+IP+TCP
								//printf("encryption! \n");
								encryption(list1->enc_map, swp, 54);
								//printf("after encryption\n");
								cvm_common_free_fpa_buffer ((void*)http_entry, CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE / CVMX_CACHE_LINE_SIZE);	
								http_entry = NULL;
								return res;
						}
				}
				if(http_entry != NULL)
						cvm_common_free_fpa_buffer ((void*)http_entry, CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE / CVMX_CACHE_LINE_SIZE);
				http_entry = NULL;
				return res;
		}
		else//链接不在规则列表中
		{
				//printf("not in list1\n");
				//是否为服务器与客户端之间的新建链接
				http_data * http_entry;
				http_entry = http_parse(swp, S2);
				if(http_entry->is_http == true)
				{
						if(http_entry->put_content == true)//PUT  test
						{
								printf("put test\n");
								list1_entry_t * list1 = make_list1_entry(swp);
								list1->tag1 = swp->hw_wqe.tag;
								memcpy(list1->username, "put test", 8);
								hash_md5(list1->secret_key, (uint8_t*)list1->username, strlen(list1->username));

								uint8_t tmp[256];
								RC4_KEY rkey;
								int i=0;
								for(i=0;i<256;i++)
										tmp[i]=i;
								for(i=0;i<256;i++)
								{
										RC4_set_key (&rkey, 16, list1->secret_key);
										RC4 (&rkey, 1, tmp+i, list1->enc_map+i);						
								}					


								//hash_md5(list1->secret_key, (uint8_t*)list1->username, strlen(list1->username));
								list1->status = S3;
								list1->inport = swp->hw_wqe.ipprt;
								if( list1->inport >= portbase + portnum)
										list1->outport = list1->inport - portnum;
								else
										list1->outport = list1->inport + portnum;
								if(http_entry->there_is_data)//如果包含数据部分,则对数据进行加密,否则直接返回
								{
										encryption(list1->enc_map, swp, http_entry->pos);
										res = 0;
								}

						}
						else if(http_entry->get_content == true)
						{

								printf("get test\n");
								list1_entry_t * list1 = make_list1_entry(swp);
								list1->tag1 = swp->hw_wqe.tag;
								memcpy(list1->username, "get test", 8);
								hash_md5(list1->secret_key, (uint8_t*)list1->username, strlen(list1->username));

								uint8_t tmp[256];
								RC4_KEY rkey;
								int i=0;
								for(i=0;i<256;i++)
										tmp[i]=i;
								for(i=0;i<256;i++)
								{
										RC4_set_key (&rkey, 16, list1->secret_key);
										RC4 (&rkey, 1, tmp+i, list1->enc_map+i);						
								}					


								//hash_md5(list1->secret_key, (uint8_t*)list1->username, strlen(list1->username));
								list1->status = S3;
								list1->inport = swp->hw_wqe.ipprt;
								if( list1->inport >= portbase + portnum)
										list1->outport = list1->inport - portnum;
								else
										list1->outport = list1->inport + portnum;
								if(http_entry->there_is_data)//如果包含数据部分,则对数据进行加密,否则直接返回
								{
										encryption(list1->enc_map, swp, http_entry->pos);
										res = 0;
								}

						}

				}
				cvm_common_free_fpa_buffer ((void*)http_entry, CVMX_FPA_PACKET_POOL, CVMX_FPA_PACKET_POOL_SIZE / CVMX_CACHE_LINE_SIZE);
				return res;
		}
} 
예제 #21
0
static PyObject *tripledescbc_encrypt(tripledescbc *self, PyObject *args) {
	//	std::cout << "hello enc 0" << std::endl; std::cout.flush();
	PyObject *result = NULL;
	byte *ciphertext = NULL;
	try {
		byte *iv;
		unsigned int ivlength;
		byte *text;
		unsigned int textlength;
		if(!PyArg_ParseTuple(args, "s#s#", &iv, &ivlength, &text, &textlength)) {
			throw Exception(Exception::INVALID_ARGUMENT, "wrong type of parameters passed in from Python");
		}
		if(ivlength != 8) {
			throw Exception(Exception::INVALID_ARGUMENT, "IV length must be 8");
		}
		//		std::cout << "hello enc 0.7" << std::endl; std::cout.flush();
		//		std::cout << "hello enc 0.7.1, self: " << self << std::endl; std::cout.flush();
		//		std::cout << "hello enc 0.7.2, self->key: ";
		//		std::cout << self->key;
		//		std::cout << std::endl;
		//		std::cout.flush();
		//	std::cout << "hello enc 0.7.3, iv: " << iv << std::endl; std::cout.flush();
		CBC_CTS_Mode<DES_XEX3>::Encryption encryption(self->key, 24, iv);
		//		std::cout << "hello enc 0.8" << std::endl; std::cout.flush();
		ciphertext = new byte[textlength];
		//		std::cout << "hello enc 0.9" << std::endl; std::cout.flush();
		if (ciphertext == NULL) {
			throw MemoryException();
		}
		//		std::cout << "hello enc 1" << std::endl; std::cout.flush();
		StreamTransformationFilter encryptor(encryption, new ArraySink(ciphertext, textlength));
		//		std::cout << "hello enc 2" << std::endl; std::cout.flush();
		encryptor.PutMessageEnd(text, textlength);
		//		std::cout << "hello enc 3" << std::endl; std::cout.flush();
		result = Py_BuildValue("s#", ciphertext, textlength);
		//		std::cout << "hello enc 4" << std::endl; std::cout.flush();
		if(result == NULL) {
			throw MemoryException();
		}
		//		std::cout << "hello enc 5" << std::endl; std::cout.flush();
		xdeletear(ciphertext);
		//		std::cout << "hello enc 6" << std::endl; std::cout.flush();
		return result;
	}
	catch(CryptoPP::Exception &e) {
		if(result != NULL) {
			PyMem_DEL(result);
		}
		xdeletear(ciphertext);
		PyErr_SetString(TripleDESCBCError, e.what());
		return NULL;
	}
	catch(MemoryException &e) {
		if(result != NULL) {
			PyMem_DEL(result);
		}
		xdeletear(ciphertext);
		PyErr_SetString(PyExc_MemoryError, "Can't allocate memory to do encryption");
		return NULL;
	}
	//	std::cout << "goodbye enc" << std::endl; std::cout.flush();
}
예제 #22
0
void message :: send_message(int sock){
	send(sock, encryption((char *)get_mass_char().c_str()) , strlen(get_mass_char().c_str()), 0);
	
}
예제 #23
0
파일: hw03(3).c 프로젝트: Alph4class/CSE240
// You should study and understand how this main function works.
// Do not modify it in any way, there is no implementation needed here.
void main()
{
	int selection; // used for program selection

	char input[32]; // used for encryption
	int encrypt; // used for encryption

	char strings[5][32]; // used for sorting

	int num; // used for multiplication table
	int mt[50][50]; // used for multiplication table

	printf("Select one of the following:\n"); // prompt for program selection integer
	printf("1: Encryption\n");
	printf("2. Sorting\n");
	printf("3. Multiplication Table\n");
	scanf("%d", &selection); // store program selection integer

	getchar(); // consume '\n' char; NOTE: If you are using GCC, you may need to comment out this line
	printf("\n"); // newline

	switch (selection)
	{
	case 1:

		printf("Enter a string up to 20 characters long: "); // prompt for string
		fgets(input, sizeof(input), stdin); // store string
		input[strlen(input) - 1] = '\0'; // discard '\n' char; NOTE: If you are using GCC, you may need to comment out this line

		printf("Enter an Integer value for Encryption: "); // prompt for integer
		scanf("%d", &encrypt); // store integer

		encryption(input, 2); // encrypt string
		printf("\nEncrypted String: %s\n", input); // print encrypted string

		decryption(input, 2); // encrypt string
		printf("Decrypted String: %s\n", input); // print decrypted string

		break;

	case 2:

		printf("Enter the first String: "); // prompt for string
		fgets(strings[0], sizeof(strings[0]), stdin); // store string

		printf("Enter the second String: ");
		fgets(strings[1], sizeof(strings[1]), stdin);

		printf("Enter the third String: ");
		fgets(strings[2], sizeof(strings[2]), stdin);

		printf("Enter the fourth String: ");
		fgets(strings[3], sizeof(strings[3]), stdin);

		printf("Enter the fifth String: ");
		fgets(strings[4], sizeof(strings[4]), stdin);

		sortStrings(strings); // call sorting function

		// print strings in sorted order
		printf("\nSorted Strings:\n%s%s%s%s%s", strings[0], strings[1], strings[2], strings[3], strings[4]);

		break;

	case 3:

		printf("Enter an integer 1-50 for a multiplication table: "); // prompt for integer
		scanf("%d", &num); // store integer

		multiplicationTable(mt, num); // create multiplication table
		printf("\n"); // newline
		printMultiplicationTable(mt, num); // print multiplication table
	}
}
예제 #24
0
//Brute Force Function
int bruteForce(int plainText64Bit[],int cipher64Bit[],unsigned long long int start,unsigned long long int end, int output56BitKey[], int worker_id) {
	int resultCipher64Bit[64];
	unsigned long long int i=0;
//	int shouldBeKey[56]=
//	//{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0};
//	{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
//	//{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
	time_t start_t, end_t;
	double diff_t;
	time(&start_t);
	for(i=start;i< end;i++ )
	{

		long long int a=1,j;
		int key[56];
		for(j=0;j<56;j++)
		{
			if((i&a)>0)
				key[55-j]=1;
			else
				key[55-j]=0;
			//printf("\ni&a : %ll \n",i&a);
			a=a<<1;
		}

		if(i%100000 == 0)
		{	printf("\nWorker %d and value of i is %llu\n",worker_id,i);
					printArray(key,56, "keyCombination");
		}
		encryption(plainText64Bit,key,resultCipher64Bit);
		if(!(memcmp(cipher64Bit, resultCipher64Bit, 64 * sizeof(int))))
		{
			time(&end_t);
			diff_t = difftime(end_t, start_t);
			int k=0;
			printf("\nKey Found!!! by worker_id : %d\n",worker_id);
			for(k=0; k<56;k++)
			{
				output56BitKey[k] = key[k];
			}
			printArray(output56BitKey,56, "key FOUND");


			system("rm key.txt");
			system("touch key.txt");
			FILE *f = fopen("key.txt", "w");
			if (f == NULL)
			{
			    printf("Error opening file!\n");
			    exit(1);
			}

			fprintf(f, "Key : %d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d by Worker : %d Time took : %le\n"
					,output56BitKey[0],output56BitKey[1],output56BitKey[2],output56BitKey[3],output56BitKey[4],
					output56BitKey[5],output56BitKey[6],output56BitKey[7],output56BitKey[8],output56BitKey[9],
					output56BitKey[10],output56BitKey[11],output56BitKey[12],output56BitKey[13],output56BitKey[14],
					output56BitKey[15],output56BitKey[16],output56BitKey[17],output56BitKey[18],output56BitKey[19],
					output56BitKey[20],output56BitKey[21],output56BitKey[22],output56BitKey[23],output56BitKey[24],
					output56BitKey[25],output56BitKey[26],output56BitKey[27],output56BitKey[28],output56BitKey[29],
					output56BitKey[30],output56BitKey[31],output56BitKey[32],output56BitKey[33],output56BitKey[34],
					output56BitKey[35],output56BitKey[36],output56BitKey[37],output56BitKey[38],output56BitKey[39],
					output56BitKey[40],output56BitKey[41],output56BitKey[42],output56BitKey[43],output56BitKey[44],
					output56BitKey[45],output56BitKey[46],output56BitKey[47],output56BitKey[48],output56BitKey[49],
					output56BitKey[50],output56BitKey[51],output56BitKey[52],output56BitKey[53],output56BitKey[54],
					output56BitKey[55],worker_id,diff_t);

			fclose(f);

			return (1);
		}
//		else if(!(memcmp(key, shouldBeKey, 56 * sizeof(int))))
//		{
//			printf("\n This should have been found. Something wrong!!! \n");
//		}
	}
	return (0);
}
예제 #25
0
파일: vigenere.c 프로젝트: anathemus/CS50
int main(int argc, string argv[])
{
    /* checks to make sure that the command line argument is not
    * NULL nor greater than 1
    */
    if (argv[1]!=NULL && argc <= 2)
    {
        string command = argv[1];
        int ring [strlen(command)];
        
        // a for iteration to make sure all characters are alpha
        for (int n = 0, m = strlen(command); n < m; n++)
        {
            if ((isalpha(command[n]))==0)
            {
                printf("\n");
                return 1;
            }
            
        }
        
        string decode = GetString();
                
        // creates integer to encrypt characters
        
        for (int i=0, n=0; i < strlen(decode); i++)
        {
            // if the encryption codeword has reached the end, start back at the beginning.
            n = n%(strlen(command));
            // if/else statement to set A and a to 0, B and b to 1, etc.
            if (isupper(command[n]))
            {
                ring[i] = (((int)command[n])-'A');
                
            }
            else
            {
                ring[i] = (((int)command[n])-'a');
                
            }
            
            // checks to see if it's capital.
            if (isalpha(decode[i]))
            {
                printf("%c", encryption(decode[i], ring[i]));
                n++;
            }
            else
            {
                printf("%c", decode[i]);
            }
             
        }
        printf("\n");
    }
    else
    {
        printf("\n");
        return 1;
    }
}