Beispiel #1
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;
}
Beispiel #2
0
const char *
vmod_decrypt(struct sess *sp, const char *text, const char *key)
{
	char *p;
	unsigned u, v;
	unsigned char decrypt[TAILLE];

	memset (decrypt, 0, TAILLE );

	u = WS_Reserve(sp->wrk->ws, 0); /* Reserve some work space */
	p = sp->wrk->ws->f;		/* Front of workspace area */
	
        decryption ((char*)key, (unsigned char*) decrypt, (unsigned char*) text);	

	v = snprintf(p, u, "%s", decrypt);
	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);
}
Beispiel #3
0
/*
 * Class:     Cypher
 * Method:    desDecryption
 * Signature: ([B[B[B)V
 */
JNIEXPORT void JNICALL Java_Cypher_desDecryption
  (JNIEnv *env, jobject obj,
   jbyteArray message, jbyteArray cypher) {
	  char* cypher_tmp = (char*)(*env)->GetByteArrayElements(env, cypher, 0);
	  char message_tmp[8];
	  decryption(cypher_tmp, message_tmp);
	  (*env)->SetByteArrayRegion(env, message, 0, 8,  message_tmp);
	  (*env)->ReleaseByteArrayElements(env, cypher, cypher_tmp, 0);
  }
Beispiel #4
0
int main()
{
        accept();
        generateKey();
        encryption();
        decryption();
        getch();
        return 0;
}
// This function will test the Decryption algorithm. It is set the exact same way as the encryption algorithm so commenting will be limited.
void testDecryption(void){
	// Initialization of variables.
	FILE *outfile;
	char testStr[] = { "TESTA" }, *pHolder = '\0', *nHolder = '\0';
	char strHold[] = "QBPQX";
	char strNold[] = "UFTUB";
	int positiveKey = 0, negativeKey = 0;

	outfile = fopen("Test_File_PA1_decryption", "w"); // Creating the output file were the results of this test will be placed.

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

	// Hardcoding the key for testing purposes.
	positiveKey = 2;
	negativeKey = -2;

	// Call and assign the decrytpion function to the place holder strings.
	pHolder = decryption(testStr, positiveKey);
	nHolder = decryption(testStr, negativeKey);

	// If all string characters match the decryption literal string then the function has successfully been performed.
	if ((pHolder[0] == strHold[0]) && (pHolder[1] == strHold[1]) && (pHolder[2] == strHold[2]) && (pHolder[3] == strHold[3]) && (pHolder[4] == strHold[4])){
		fprintf(outfile, "The Decrytped Phrase: %s\nDecryption passed the positive key.\n", pHolder);
	}
	else {
		// Otherwise this statement will be passed to the output file.
		fprintf(outfile, "Decryption did not pass the positive key correctly.\n");
	}

	// Again, the exact same as before where the string place holders should match the string lieteral.
	if ((nHolder[0] == strNold[0]) && (nHolder[1] == strNold[1]) && (nHolder[2] == strNold[2]) && (nHolder[3] == strNold[3]) && (nHolder[4] == strNold[4])){
		fprintf(outfile, "The Decrytped Phrase: %s\nDecryption passed the negative key.\n", nHolder);
	}
	else{
		// If not, this message will be displayed.
		fprintf(outfile, "Decryption did not pass the negative key correctly.\n");
	}

	fclose(outfile); // Close the outfile.
}
Beispiel #6
0
static PyObject *tripledescbc_decrypt(tripledescbc *self, PyObject *args) {
	//	std::cout << "hello dec 0" << std::endl; std::cout.flush();
	PyObject *result = NULL;
	byte *plaintext = 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");
		}
		CBC_CTS_Mode<DES_XEX3>::Decryption decryption(self->key, 24, iv);
		plaintext = new byte[textlength];
		if (plaintext == NULL) {
			throw MemoryException();
		}
		StreamTransformationFilter decryptor(decryption, new ArraySink(plaintext, textlength));
		decryptor.PutMessageEnd(text, textlength);
		result = Py_BuildValue("s#", plaintext, textlength);
		if(result == NULL) {
			throw MemoryException();
		}
		xdeletear(plaintext);
		return result;
	}
	catch(CryptoPP::Exception &e) {
		if(result != NULL) {
			PyMem_DEL(result);
		}
		xdeletear(plaintext);
		PyErr_SetString(TripleDESCBCError, e.what());
		return NULL;
	}
	catch(MemoryException &e) {
		if(result != NULL) {
			PyMem_DEL(result);
		}
		xdeletear(plaintext);
		PyErr_SetString(PyExc_MemoryError, "Can't allocate memory to do decryption");
		return NULL;
	}
}
Beispiel #7
0
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;

}
Beispiel #8
0
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;
}
Beispiel #9
0
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;
}
Beispiel #10
0
int message :: recv_message(int sock){
	char buf[SIZE_MESSAGE];
	int bytes_read ;
	bytes_read = recv (sock, buf, SIZE_MESSAGE, 0);
	if (bytes_read <= 0)
		return 1;
	buf[bytes_read] = '\0';
	strcpy (buf, decryption (buf));
	MessageType = buf[0];
	string str(buf);
	if (MessageType == 'u'){
		size_UserName = buf[1];
		UserName = str.substr(2,size_UserName);
		text = str.substr(size_UserName+2, str.size());
	}
	if (MessageType == 'a'){
		text = str.substr(2);
		size_UserName = '******';
		UserName.clear();
	}
	return 0;
}
Beispiel #11
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;
}
Beispiel #12
0
// 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
	}
}
int main(){
  int welcomeSocket, newSocket;
  char bufferMes[MAX_SIZE];
  char bufferHash[HASH_SIZE];
  char bufferHash2[HASH_SIZE];
  char bufferSig[HASH_SIZE];
  char bufferOut[MAX_SIZE];
  struct sockaddr_in serverAddr;
  struct sockaddr_storage serverStorage;
  socklen_t addr_size;

  // Create socket
  welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);
  
  /*---- Configure settings of the server address struct ----*/
  // Address family = Internet
  serverAddr.sin_family = AF_INET;
  // Set port number, using htons function to use proper byte order 
  serverAddr.sin_port = htons(9876);
  // Set IP address to localhost 
  serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  // Set all bits of the padding field to 0 
  memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

  // Bind address struct to socket
  bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));

  //Keeps server running until manual shut down, so multiple instances of client can be ran
  while(1){
    // Listen to socket
    if(listen(welcomeSocket,5)==0)
      printf("Listening\n");
    else
      printf("Error\n");

    // Accept call creates a new socket for the incoming connection
    addr_size = sizeof serverStorage;
    newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);

    int num;

    //Recieve message from client
    if ((num = recv(newSocket, bufferMes, MAX_SIZE,0))== -1) {
          perror("recv");
          exit(1);
    }   
    else if (num == 0) {
          printf("Connection closed\n");
          return 0;
    }

    //Recieve sig from client
    if ((num = recv(newSocket, bufferSig, MAX_SIZE,0))== -1) {
        perror("recv");
        exit(1);
    }   
    else if (num == 0) {
        printf("Connection closed\n");
        return 0;
    }

    //Hash the orignal message
    hash(bufferMes, bufferHash);
    //decrypted the signature
    decryption(bufferSig, KEY, bufferHash2);

    //check if hash + decryption are equal or not
    char toSend[MAX_SIZE];
    clear(toSend);

    if(strcmp(bufferHash, bufferHash2) == 0)
      strcpy(toSend, "True\n");
    else
      strcpy(toSend, "False\n");

    toSend[MAX_SIZE] = '\0';

    // Send message to client
    if((send(newSocket,toSend,strlen(toSend),0)) == -1) {
      fprintf(stderr, "Failure Sending Message\n");
      close(newSocket);
      exit(1);
    }
  }

  printf("Closed\n");
  close(newSocket);
  return 0;
}
void Client_Receive_Decrypt(mpz_t valueReturn, mpz_t KPri[3])
{
    decryption(valueReturn, valueReturn, KPub, KPri);
}
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;
}
Beispiel #16
0
int main(){
	mpz_init( p);
	mpz_init( q);
	mpz_init( n);
	mpz_init( lambda);
	mpz_init( g);
	mpz_init( nn); // n squared 
	mpz_init( initNbMpz);
	mpz_init( gcdResult);
	mpz_init( lcmResult);
	mpz_init( tmpI);
	mpz_init( tmpII);
	mpz_init( p_1);
	mpz_init( q_1);

	//[Declaration]//mpz_t  r; // this is how to declare int in gmp
	//[initiallization]// mpz_init (r); // this is how i initialize the variables 
	//[Print]//gmp_printf ("%Zd\n", r); // this is how i print'em 
	//[set x = string]//mpz_set_str : https://gmplib.org/manual/Assigning-Integers.html#Assigning-Integers
	//[*]//void mpz_mul (mpz_t rop, const mpz_t op1, const mpz_t op2) 
	//[Quotient]//void mpz_cdiv_q (mpz_t q, const mpz_t n, const mpz_t d)
	//[Reminder]//void mpz_cdiv_r (mpz_t r, const mpz_t n, const mpz_t d)
	//[Exponentiation] //void mpz_powm (mpz_t rop, const mpz_t base, const mpz_t exp, const mpz_t mod)

	//[GCD]void mpz_gcd (mpz_t rop, const mpz_t op1, const mpz_t op2)
	//void mpz_lcm (mpz_t rop, const mpz_t op1, const mpz_t op2)

	//void mpz_nextprime (mpz_t rop, const mpz_t op)
	// int mpz_probab_prime_p (const mpz_t n, int reps) // which uses Miller-Rabin probabilistic primality tests. 
	
	
	//printf("%s\n", initNb);
	
	

	/*****************PROMBLEM**************************/
	/*No matter how many times I apply the algo it seems to be not sure if it's Prime */
	/**********************************/
	       /******************/
	           /**********/
	             /*****/
	              /**/ 
	
	
	srand((unsigned) time(&t));
	keysGeneration();
	printf("what are you doin  dude!!\n");

	encrypt(6034);
	//IMPORTANT
	//I have to make sure that (m; which i want to encrypt) is smaller than n
	decryption();
	mpz_clear(p);
	mpz_clear(q);
	mpz_clear(n);
	mpz_clear(nn);
	mpz_clear(lambda);
	mpz_clear(g);
	mpz_clear(initNbMpz);
	mpz_clear(p_1);
	mpz_clear(q_1);
	mpz_clear(tmpI);
	mpz_clear(gcdResult);
	mpz_clear(lcmResult);
	mpz_clear(r);
	mpz_clear(c);

	return 0;
}