int main(int argc, char*argv[]){
       BigInt  cipher, deciphered,message;
        unsigned long int *a;
        unsigned long int arr[10];
        a=&arr[0];
        BigInt pubkey, privatekey;
        BigInt gnm;
		
		//message=1000;
       message = int(((double)(std::rand())/RAND_MAX)*RAND_LIMIT32);
        
        for(int i=1;i<=10;i++)
     {
      sleep(1);
      std::cout<<std::endl<<"RSA "<<i<<std::endl;     
      RSA newrsa;    // default , no args, program generates its own p and q
      std::cout<<"Public Key ";
      pubkey= newrsa.getPublicKey();
      pubkey.toULong(a,4);
       std::cout<<*a<<std::endl;
       privatekey=newrsa.getPrivateKey();
       privatekey.toULong(a,4);
       std::cout<<"Private Key : "<<*a<<std::endl;
       gnm = newrsa.getModulus();
       std::cout<<"N  is "<<gnm.toHexString()<<std::endl;
        
       cipher = newrsa.encrypt(message);
       deciphered = newrsa.decrypt(cipher);

       std::cout<<"message: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<std::endl<<std::endl;     
     }
     
     
}
예제 #2
0
int main(){
/* Implementation of task1*/

std::cout<<"\n\n************Task1***********"<<std::endl;
srand(time(NULL));
/* Subtask1 */
std::cout<<"\n************Subtask1************"<<std::endl;
RSA objRSA[10];
//char * messages[]={"One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten"};
int msg=int(((double)rand()/RAND_MAX)*LIMIT_RAND);  //generation of random message
BigInt result(0);
for(int i=0;i<10;i++){
        printf("\nEncrypting the message %d \n", msg);
        result=objRSA[i].encrypt(msg);                //Encryption of message
        std::cout<<"Encryption result : "<<result.toHexString()<<std::endl;
}
/* Subtask 2 */
std::cout<<"\n***********Subtask2**************"<<std::endl;
RSA * objRSA_onearg[5]={NULL};
std::cout<<"\nEncrypting the message "<<msg<<std::endl;
int primep[10]={0};
generate_prime(primep,10);//prime number generation
for(int i=0;i<5;i++){
objRSA_onearg[i] = new RSA (primep[i]);
result = objRSA_onearg[i]->encrypt(msg); // encrypt message
std::cout<<"\nEncryption result using the prime p as "<<primep[i]<<" is "<<result.toHexString()<<std::endl;
result = objRSA_onearg[i]->decrypt(result);//decrypt message
std::cout<<"Decryption result : "<<result.toHexString()<<std::endl;
}

/* Subtask 3 */
std::cout<<"\n***********Subtask3**************"<<std::endl;
RSA * objRSA_twoarg[5]={NULL};
std::cout<<"\nEncrypting the message "<<msg<<std::endl;
for(int i=0;i<5;i++){
objRSA_onearg[i] = new RSA (primep[i],primep[5+i]);
result = objRSA_onearg[i]->encrypt(msg);//encrypting the message
std::cout<<"\nEncryption result using the prime p and q as  "<<primep[i]<<" "<<primep[5+i]<<" is "<<result.toHexString()<<std::endl;
result = objRSA_onearg[i]->decrypt(result);//decrypting the message
std::cout<<"Decryption result : " << result.toHexString()<<std::endl;
}
/* Subtask 4 */
std::cout<<"\n***********Subtask4**************"<<std::endl;
RSA * objRSA_twononprimearg[5]={NULL};
int nprime[10]={0};
generate_nonprime(nprime,10);//generate non prime numbers
std::cout<<"\nEncrypting the message "<<msg<<std::endl;
for(int i=0;i<5;i++){
objRSA_onearg[i] = new RSA (nprime[i],nprime[5+i]);
result = objRSA_onearg[i]->encrypt(msg);//encrypting the message
std::cout<<"\nEncryption result using the non prime p and q as  "<<nprime[i]<<" "<<nprime[5+i]<<" is "<<result.toHexString()<<std::endl;
result = objRSA_onearg[i]->decrypt(result);//decrypt message
std::cout<<"Decryption result : "<<result.toHexString()<<std::endl;
if(result==objRSA_onearg[i]->encrypt(msg)){//check if encrypted and decrypted messages are same
std::cout<<"This case is an out of ordinary case "<<std::endl;
}
}
/*Implementation of task3*/
/*********Task2********/
std::cout<<"\n\n***************Task2*********"<<std::endl;
RSA RSAObj1;
RSA RSAObj2;
unsigned long result_long[2];
int size_result_array=2;
result=RSAObj1.getPublicKey();
RSAObj2.setPublicKey(result);
RSAObj2.setN(RSAObj1.getModulus());
//int rno=rand();
BigInt rno=int(((double)rand()/RAND_MAX)*LIMIT_RAND);//random message 
 std::cout<<"\noriginal message="<<rno.toHexString()<<std::endl;
result=RSAObj2.encrypt(rno);
std::cout<<"encrypted message="<<result.toHexString()<<std::endl;
result=RSAObj1.decrypt(result);
std::cout<<"decrypted message="<<result.toHexString()<<std::endl;
//converttoint(result,result_long,size_result_array);
if(result==rno){//check if values match
 std::cout<<"Original message and decrypted messages match , hence verified "<<std::endl;
}

/*Implementation of task3*/
/************Task3********/
std::cout<<"\n\n*****************Task3***************"<<std::endl;

RSA Bobobj;
BigInt pk= Bobobj.getPublicKey();
BigInt mod= Bobobj.getModulus();
//Bob sends public key and modN to Alice
BigInt msgAlice=sendtoAlice(pk,mod);
//Bob decrypts the message received from Alice 
BigInt decmessage= Bobobj.decrypt(msgAlice);
//send the decrypted message to Alice again
sendtoAlice2(decmessage,pk,mod);
}
예제 #3
0
void ProtocolAdmin::parsePacket(NetworkMessage& msg)
{
	if (g_game.getGameState() == GAME_STATE_SHUTDOWN) {
		getConnection()->closeConnection();
		return;
	}

	uint8_t recvbyte = msg.GetByte();

	OutputMessagePool* outputPool = OutputMessagePool::getInstance();

	OutputMessage_ptr output = outputPool->getOutputMessage(this, false);

	if (!output) {
		return;
	}

	switch (m_state) {
		case ENCRYPTION_NO_SET: {
			if (g_adminConfig->requireEncryption()) {
				if ((time(NULL) - m_startTime) > 30000) {
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "encryption timeout");
					return;
				}

				if (recvbyte != AP_MSG_ENCRYPTION && recvbyte != AP_MSG_KEY_EXCHANGE) {
					output->AddByte(AP_MSG_ERROR);
					output->AddString("encryption needed");
					outputPool->send(output);
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "wrong command while ENCRYPTION_NO_SET");
					return;
				}

				break;
			} else {
				m_state = NO_LOGGED_IN;
			}
		}

		case NO_LOGGED_IN: {
			if (g_adminConfig->requireLogin()) {
				if ((time(NULL) - m_startTime) > 30000) {
					//login timeout
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "login timeout");
					return;
				}

				if (m_loginTries > 3) {
					output->AddByte(AP_MSG_ERROR);
					output->AddString("too many login tries");
					outputPool->send(output);
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "too many login tries");
					return;
				}

				if (recvbyte != AP_MSG_LOGIN) {
					output->AddByte(AP_MSG_ERROR);
					output->AddString("you are not logged in");
					outputPool->send(output);
					getConnection()->closeConnection();
					addLogLine(this, LOGTYPE_WARNING, 1, "wrong command while NO_LOGGED_IN");
					return;
				}

				break;
			} else {
				m_state = LOGGED_IN;
			}
		}

		case LOGGED_IN: {
			//can execute commands
			break;
		}

		default: {
			getConnection()->closeConnection();
			return;
		}
	}

	m_lastCommand = time(NULL);

	switch (recvbyte) {
		case AP_MSG_LOGIN: {
			if (m_state == NO_LOGGED_IN && g_adminConfig->requireLogin()) {
				std::string password = msg.GetString();

				if (g_adminConfig->passwordMatch(password)) {
					m_state = LOGGED_IN;
					output->AddByte(AP_MSG_LOGIN_OK);
					addLogLine(this, LOGTYPE_EVENT, 1, "login ok");
				} else {
					m_loginTries++;
					output->AddByte(AP_MSG_LOGIN_FAILED);
					output->AddString("wrong password");
					addLogLine(this, LOGTYPE_WARNING, 1, "login failed.(" + password + ")");
				}
			} else {
				output->AddByte(AP_MSG_LOGIN_FAILED);
				output->AddString("can not login");
				addLogLine(this, LOGTYPE_WARNING, 1, "wrong state at login");
			}

			break;
		}

		case AP_MSG_ENCRYPTION: {
			if (m_state == ENCRYPTION_NO_SET && g_adminConfig->requireEncryption()) {
				uint8_t keyType = msg.GetByte();

				if (keyType == ENCRYPTION_RSA1024XTEA) {
					RSA* rsa = g_adminConfig->getRSAKey(ENCRYPTION_RSA1024XTEA);

					if (!rsa) {
						output->AddByte(AP_MSG_ENCRYPTION_FAILED);
						addLogLine(this, LOGTYPE_WARNING, 1, "no valid server key type");
						break;
					}

					if (RSA_decrypt(rsa, msg)) {
						m_state = NO_LOGGED_IN;
						uint32_t k[4];
						k[0] = msg.GetU32();
						k[1] = msg.GetU32();
						k[2] = msg.GetU32();
						k[3] = msg.GetU32();

						//use for in/out the new key we have
						enableXTEAEncryption();
						setXTEAKey(k);

						output->AddByte(AP_MSG_ENCRYPTION_OK);
						addLogLine(this, LOGTYPE_EVENT, 1, "encryption ok");
					} else {
						output->AddByte(AP_MSG_ENCRYPTION_FAILED);
						output->AddString("wrong encrypted packet");
						addLogLine(this, LOGTYPE_WARNING, 1, "wrong encrypted packet");
					}
				} else {
					output->AddByte(AP_MSG_ENCRYPTION_FAILED);
					output->AddString("no valid key type");
					addLogLine(this, LOGTYPE_WARNING, 1, "no valid client key type");
				}
			} else {
				output->AddByte(AP_MSG_ENCRYPTION_FAILED);
				output->AddString("can not set encryption");
				addLogLine(this, LOGTYPE_EVENT, 1, "can not set encryption");
			}

			break;
		}

		case AP_MSG_KEY_EXCHANGE: {
			if (m_state == ENCRYPTION_NO_SET && g_adminConfig->requireEncryption()) {
				uint8_t keyType = msg.GetByte();

				if (keyType == ENCRYPTION_RSA1024XTEA) {
					RSA* rsa = g_adminConfig->getRSAKey(ENCRYPTION_RSA1024XTEA);

					if (!rsa) {
						output->AddByte(AP_MSG_KEY_EXCHANGE_FAILED);
						addLogLine(this, LOGTYPE_WARNING, 1, "no valid server key type");
						break;
					}

					output->AddByte(AP_MSG_KEY_EXCHANGE_OK);
					output->AddByte(ENCRYPTION_RSA1024XTEA);
					char RSAPublicKey[128];
					rsa->getPublicKey(RSAPublicKey);
					output->AddBytes(RSAPublicKey, 128);
				} else {
					output->AddByte(AP_MSG_KEY_EXCHANGE_FAILED);
					addLogLine(this, LOGTYPE_WARNING, 1, "no valid client key type");
				}
			} else {
				output->AddByte(AP_MSG_KEY_EXCHANGE_FAILED);
				output->AddString("can not get public key");
				addLogLine(this, LOGTYPE_WARNING, 1, "can not get public key");
			}

			break;
		}

		case AP_MSG_COMMAND: {
			if (m_state != LOGGED_IN) {
				addLogLine(this, LOGTYPE_ERROR, 1, "recvbyte == AP_MSG_COMMAND && m_state != LOGGED_IN !!!");
				// We should never reach this point
				break;
			}

			uint8_t command = msg.GetByte();

			switch (command) {
				case CMD_BROADCAST: {
					const std::string message = msg.GetString();
					addLogLine(this, LOGTYPE_EVENT, 1, "broadcast: " + message);
					g_dispatcher.addTask(createTask(boost::bind(&Game::broadcastMessage, &g_game, message, MSG_STATUS_WARNING)));
					output->AddByte(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_CLOSE_SERVER: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandCloseServer, this)));
					break;
				}

				case CMD_PAY_HOUSES: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandPayHouses, this)));
					break;
				}

				case CMD_OPEN_SERVER: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandOpenServer, this)));
					break;
				}

				case CMD_SHUTDOWN_SERVER: {
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandShutdownServer, this)));
					getConnection()->closeConnection();
					return;
				}

				case CMD_KICK: {
					const std::string name = msg.GetString();
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandKickPlayer, this, name)));
					break;
				}

				case CMD_SETOWNER: {
					const std::string param = msg.GetString();
					g_dispatcher.addTask(createTask(boost::bind(&ProtocolAdmin::adminCommandSetOwner, this, param)));
					break;
				}

				default: {
					output->AddByte(AP_MSG_COMMAND_FAILED);
					output->AddString("not known server command");
					addLogLine(this, LOGTYPE_WARNING, 1, "not known server command");
					break;
				}
			}

			break;
		}

		case AP_MSG_PING: {
			output->AddByte(AP_MSG_PING_OK);
			break;
		}

		default: {
			output->AddByte(AP_MSG_ERROR);
			output->AddString("not known command byte");
			addLogLine(this, LOGTYPE_WARNING, 1, "not known command byte");
			break;
		}
	}

	if (output->getMessageLength() > 0) {
		outputPool->send(output);
	}
}
예제 #4
0
int main(int argc, char*argv[])
{
	RSA* _RSA_obj[10];
	BigInt _message, _encrypt, _decrypt;
	int _primeNumber[] = { 40343,40351,40357,40361,40387,40423,40427,40429,40433,40459,40471,40483,40487,40493,40499,40507,40519,40529,40531};
	int _nonPrimeNumber[] = {36782,36792,36792,36802,36822,36832,36842,36852,36872,36872,37692,37692,37692,37722,37742,37712,37782,37792,37812,37814};


cout << "1)------------------Encryption and Decryption using RSA----------------------"<<"\n";

//------------No arguments RSA --------------------------------------------
	   cout << "a) 10 instances of RSA routine(argument-less) encryption-decryption"<<"\n";
	for (int i = 0; i < 10; i++)
	{
		_RSA_obj[i] = new RSA();
		usleep(21000);
		_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
		_encrypt = _RSA_obj[i]->encrypt(_message);
		_decrypt = _RSA_obj[i]->decrypt(_encrypt);

    cout << "Message: " << _message.toHexString() << "\t\tEncrypted: " << _encrypt.toHexString() << "\t\tDecrypted: " << _decrypt.toHexString()<<"\n";
	}
	cout<<"\n";
//------------1 prime number RSA --------------------------------------------
	   cout << "b) 5 RSA instances(1 prime number(>30,000) as argument) encryption-decryption "<<"\n";
	for (int i = 0; i < 5; i++)
	{
		_RSA_obj[i] = new RSA(_primeNumber[i]);
		usleep(450000);
		_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
		_encrypt = _RSA_obj[i]->encrypt(_message);
		_decrypt = _RSA_obj[i]->decrypt(_encrypt);

    cout << "Message: " << _message.toHexString() << "\t\tEncrypted: " << _encrypt.toHexString() << "\t\tDecrypted: " << _decrypt.toHexString()<<"\n";
	}
	cout<<"\n";
//------------2 prime numbers RSA --------------------------------------------
   cout << "c) 5 RSA instances(2 prime numbers(>30,000) as arguments) encryption-decryption "<<"\n";
	 for (int i = 0; i < 5; i++)
 	{
 		_RSA_obj[i] = new RSA(_primeNumber[i], _primeNumber[10-i]);
 		usleep(450000);
 		_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
 		_encrypt = _RSA_obj[i]->encrypt(_message);
	_decrypt = _RSA_obj[i]->decrypt(_encrypt);
 		 cout << "Message: " << _message.toHexString() << "\tEncrypted: " << _encrypt.toHexString() << "\tDecrypted: " << _decrypt.toHexString()<<"\n";
 	}
	cout<<"\n";

//--------------2 non prime numbers RSA-------------------------------------
cout << "d) 5 RSA instances(2 non prime numbers(>30,000) as arguments) encryption-decryption "<<"\n";
for (int i = 0; i < 10; i++)
{
 _RSA_obj[i] = new RSA(_nonPrimeNumber[i], _nonPrimeNumber[10-i]);
 usleep(50000);
 _message = int(((double) rand() / RAND_MAX)*RAND_GEN32);
 _encrypt = _RSA_obj[i]->encrypt(_message);
 _decrypt = _RSA_obj[i]->decrypt(_encrypt);
	cout << "Message: " << _message.toHexString() << "\tEncrypted: " << _encrypt.toHexString() << "\tDecrypted: " << _decrypt.toHexString()<<"\n";
}
cout<<"\n";

//--------------challenge response scheme---------------------------------------
cout << "2)--------------------Challenge response scheme--------------------" <<  "\n";
RSA obj1, obj2;

BigInt rsaPK = obj1.getPublicKey();
BigInt rsaN = obj1.getModulus();

obj2.setPublicKey(rsaPK);
obj2.setN(rsaN);

//random message
_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);

BigInt encrypt = obj2.encrypt(_message);
BigInt decrypt = obj1.decrypt(encrypt);

cout << "Plain Text:" << _message.toHexString() << "\tDecrypted Text:" << decrypt.toHexString() <<  "\n";
if (_message.operator==(decrypt))
	cout << "Challenge response scheme is Successful" <<  "\n";
else
	cout << "Challenge response scheme is Unsuccessful" <<  "\n";
cout <<  "\n";


//--------------Blind signature---------------------------------------

cout << "3)------------------Blind signature---------------------" <<  "\n";
RSA obj;
BigInt bobN = obj.getModulus();
BigInt bobPK = obj.getPublicKey();

// Generate random number and its inverse
double AliceRandomNo = double(((double) rand() / RAND_MAX)*RAND_GEN32);
BigInt rnd(AliceRandomNo);
BigInt AliceRandomNoInverse = RSAUtil::modInverse(rnd, bobN);

//random message
_message = int(((double) rand() / RAND_MAX)*RAND_GEN32);

BigInt encryptRandom = RSAUtil::modPow(rnd, bobPK, bobN);

BigInt messageToRSAobj = encryptRandom.operator*(_message).operator%(bobN);

BigInt messageFromRSAobj = getDecryptedMessageFromRSA_obj(messageToRSAobj, obj);

BigInt sign = messageFromRSAobj.operator*(AliceRandomNoInverse).operator%(bobN);

BigInt flag = RSAUtil::modPow(sign, bobPK, bobN);

cout << "message: " << _message.toHexString() << "\tsignature: " << sign.toHexString() << "\tdecrypted: " << flag.toHexString() <<  "\n";

cout << "\nBlind signature: ";
if(_message.operator==(flag))
	cout << "Blind signature Successful" <<"\n";
else
	cout << "Blind signature Unsuccessful" << "\n";

//--------------------------------------end of main--------------------
cout<<"\n";
return 0;
}
예제 #5
0
int main(int argc, char*argv[]){    
  
	/*
	TASK 1: Perform encryption and Decryption each using the RSA routines provided here. They don’t necessarily have to be part of the same code
	*/
	int count = 10;
	int i=0;
	std::string result;
	BigInt randMessage[10];
	
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1a: Create 10 instances of the RSA class without giving arguments, generate random message or assign messages, and perform encryption through each of the 10 classes. "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	//initializing at once as everytime RSA is called srand is called internally and reseting the random function
	for(i=0;i<count;i++)
	{
	   randMessage[i] = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
	}
	for(i=0;i<count;i++)
	{
	  RSA myRSA;
	  BigInt message, cipher, deciphered;
	  message = randMessage[i];
	
	  //encrypting
	  cipher = myRSA.encrypt(message);
	  //decrypting
	  deciphered = myRSA.decrypt(cipher);
	  
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	}
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1b: Create 5 instances of the RSA class by passing a large prime number [p](> 30,000), and perform encryption decryption. "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	count =  5;
	//Initializing some primes and non-primes to be used by following tasks.
	unsigned long int setOfLargePrimes[] = {103919, 103951, 103963, 103967,103969, 104677 ,104681 ,104683 ,104693 ,104701 ,104707 ,104711 ,104717 ,104723 ,104729};
	unsigned long int setOfNonPrimes[] = {40000, 31000, 42000, 45000, 50000, 48000,60000,80000,70000,90000,99000};
	
	
	//iterating 5 time for question 1b
	for(i=0;i<count;i++)
	{
	  //giving one primenumber as input to the RSA
	  RSA rsaInstance(setOfLargePrimes[i]);
	  BigInt message, cipher, deciphered;
	  message = randMessage[i];
	 
	  //decrypting and encrypting 
	  cipher = rsaInstance.encrypt(message);
	  deciphered = rsaInstance.decrypt(cipher);
	  
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1c: Create 5 instances of the RSA class by passing 2 large prime numbers [p,q] (> 30,000) and perform encryption decryption "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	for(i=0;i<count;i++)
	{
	  //Intializing RSA with two primenumbers
	  RSA rsaInstance(setOfLargePrimes[2*i], setOfLargePrimes[2*i+1]);
	  BigInt message, cipher, deciphered;
	  
	  message = randMessage[i];
	  
	  //encrypting and decrypting
	  cipher = rsaInstance.encrypt(message);
	  deciphered = rsaInstance.decrypt(cipher);
	 
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<"TASK 1d: Create 10 instances of the RSA class by passing 2 large non prime numbers (> 30,000) and perform encryption decryption. In most of the cases the message should not get decrypted correctly.  "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	for(i=0;i<10;i++)
	{
	  //Creating RSA with non primes. 
	  RSA rsaInstance(setOfNonPrimes[i], setOfNonPrimes[i+1]);
	  BigInt message, cipher, deciphered;
	  
	  message = randMessage[i];
	   //encrypting and decrypting
	  cipher = rsaInstance.encrypt(message);
	  deciphered = rsaInstance.decrypt(cipher);
	 
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	/*
	TASK 2: Challenge Response: Scheme 0
	*/
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<" TASK 2: Challenge Response Scheme 0 "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	{
	  RSA RSA1, RSA2;
	  
	  //Assigning RSA1 public key and Modulus to RSA2 
	  BigInt publicKey = RSA1.getPublicKey();
	  BigInt modulus = RSA1.getModulus();
	  RSA2.setPublicKey(publicKey);
	  RSA2.setN(modulus);
	  
	  //generating random message
	  BigInt message, cipher, deciphered;
	  message = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
	  
	  
	  //encrypting with RSA2 i.e RSA1's public key
	  cipher = RSA2.encrypt(message);
	  //decrypting with RSA1 i.e RSA1's private key
	  deciphered = RSA1.decrypt(cipher);
	  
	 //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    result = "success";
	  }
	  else
	  {
	    result = "failed";
	  }
	  
	  std::cout<<"Instance:"<<i<<"\tmessage: "<<message.toHexString()<<"\tcipher: "<<cipher.toHexString()<<"\tdeciphered: "<<deciphered.toHexString()<<"\tverification-result:"<<result<<std::endl;
	
	}
	
	/*
	TASK 3: Blind Signature
	*/
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	std::cout<<" TASK 3: Blind Signature  "<<std::endl;
	std::cout<<"********************************************************************************************************************************************************************"<<std::endl;
	
	{
	  //Random message requester want to send with signers signature
	  BigInt message = int(((double)std::rand()/RAND_MAX)*RAND_LIMIT32);
	  
	  //Passing signers public key to the requester so that he can generate the blind factor
	  BigInt signedMessage =  Requester(message, signersRSA.getPublicKey(), signersRSA.getModulus());
	  BigInt deciphered = signersRSA.encrypt(signedMessage);
	  
	  std::cout<<"Signed Message without blindfactor:" << signedMessage.toHexString() <<std::endl;
	  
	  std::cout<<" Message Decrypted:" << deciphered.toHexString() <<std::endl;
	  
	  //Checking if the decrypted value is equal to original value 
	  if(message == deciphered)
	  {
	    std::cout<<"Blind Signature successfully implemented"<<std::endl;
	  }
	  else
	  {
	    std::cout<<"Blind Signature implementation failed"<<std::endl;
	  }
	  
	 
	}
	

}
예제 #6
0
파일: admin.cpp 프로젝트: 081421/otxserver
void ProtocolAdmin::parsePacket(NetworkMessage& msg)
{
	if(g_game.getGameState() == GAMESTATE_SHUTDOWN)
	{
		getConnection()->close();
		return;
	}

	uint8_t recvbyte = msg.get<char>();
	OutputMessage_ptr output = OutputMessagePool::getInstance()->getOutputMessage(this, false);
	if(!output)
		return;

	TRACK_MESSAGE(output);
	switch(m_state)
	{
		case ENCRYPTION_NO_SET:
		{
			if(Admin::getInstance()->isEncypted())
			{
				if((time(NULL) - m_startTime) > 30000)
				{
					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "encryption timeout");
					return;
				}

				if(recvbyte != AP_MSG_ENCRYPTION && recvbyte != AP_MSG_KEY_EXCHANGE)
				{
					output->put<char>(AP_MSG_ERROR);
					output->putString("encryption needed");
					OutputMessagePool::getInstance()->send(output);

					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "wrong command while ENCRYPTION_NO_SET");
					return;
				}
			}
			else
				m_state = NO_LOGGED_IN;

			break;
		}

		case NO_LOGGED_IN:
		{
			if(g_config.getBool(ConfigManager::ADMIN_REQUIRE_LOGIN))
			{
				if((time(NULL) - m_startTime) > 30000)
				{
					//login timeout
					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "login timeout");
					return;
				}

				if(m_loginTries > 3)
				{
					output->put<char>(AP_MSG_ERROR);
					output->putString("too many login tries");
					OutputMessagePool::getInstance()->send(output);

					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "too many login tries");
					return;
				}

				if(recvbyte != AP_MSG_LOGIN)
				{
					output->put<char>(AP_MSG_ERROR);
					output->putString("you are not logged in");
					OutputMessagePool::getInstance()->send(output);

					getConnection()->close();
					addLogLine(LOGTYPE_EVENT, "wrong command while NO_LOGGED_IN");
					return;
				}
			}
			else
				m_state = LOGGED_IN;

			break;
		}

		case LOGGED_IN:
			break;

		default:
		{
			getConnection()->close();
			addLogLine(LOGTYPE_EVENT, "no valid connection state!!!");
			return;
		}
	}

	m_lastCommand = time(NULL);
	switch(recvbyte)
	{
		case AP_MSG_LOGIN:
		{
			if(m_state == NO_LOGGED_IN && g_config.getBool(ConfigManager::ADMIN_REQUIRE_LOGIN))
			{
				std::string pass = msg.getString(), word = g_config.getString(ConfigManager::ADMIN_PASSWORD);
				_encrypt(word, false);
				if(pass == word)
				{
					m_state = LOGGED_IN;
					output->put<char>(AP_MSG_LOGIN_OK);
					addLogLine(LOGTYPE_EVENT, "login ok");
				}
				else
				{
					m_loginTries++;
					output->put<char>(AP_MSG_LOGIN_FAILED);
					output->putString("wrong password");
					addLogLine(LOGTYPE_EVENT, "login failed.("+ pass + ")");
				}
			}
			else
			{
				output->put<char>(AP_MSG_LOGIN_FAILED);
				output->putString("cannot login");
				addLogLine(LOGTYPE_EVENT, "wrong state at login");
			}

			break;
		}

		case AP_MSG_ENCRYPTION:
		{
			if(m_state == ENCRYPTION_NO_SET && Admin::getInstance()->isEncypted())
			{
				uint8_t keyType = msg.get<char>();
				switch(keyType)
				{
					case ENCRYPTION_RSA1024XTEA:
					{
						RSA* rsa = Admin::getInstance()->getRSAKey(ENCRYPTION_RSA1024XTEA);
						if(!rsa)
						{
							output->put<char>(AP_MSG_ENCRYPTION_FAILED);
							addLogLine(LOGTYPE_EVENT, "no valid server key type");
							break;
						}

						if(RSA_decrypt(rsa, msg))
						{
							m_state = NO_LOGGED_IN;
							uint32_t k[4]= {msg.get<uint32_t>(), msg.get<uint32_t>(), msg.get<uint32_t>(), msg.get<uint32_t>()};

							//use for in/out the new key we have
							enableXTEAEncryption();
							setXTEAKey(k);

							output->put<char>(AP_MSG_ENCRYPTION_OK);
							addLogLine(LOGTYPE_EVENT, "encryption ok");
						}
						else
						{
							output->put<char>(AP_MSG_ENCRYPTION_FAILED);
							output->putString("wrong encrypted packet");
							addLogLine(LOGTYPE_EVENT, "wrong encrypted packet");
						}

						break;
					}

					default:
					{
						output->put<char>(AP_MSG_ENCRYPTION_FAILED);
						output->putString("no valid key type");

						addLogLine(LOGTYPE_EVENT, "no valid client key type");
						break;
					}
				}
			}
			else
			{
				output->put<char>(AP_MSG_ENCRYPTION_FAILED);
				output->putString("cannot set encryption");
				addLogLine(LOGTYPE_EVENT, "cannot set encryption");
			}

			break;
		}

		case AP_MSG_KEY_EXCHANGE:
		{
			if(m_state == ENCRYPTION_NO_SET && Admin::getInstance()->isEncypted())
			{
				uint8_t keyType = msg.get<char>();
				switch(keyType)
				{
					case ENCRYPTION_RSA1024XTEA:
					{
						RSA* rsa = Admin::getInstance()->getRSAKey(ENCRYPTION_RSA1024XTEA);
						if(!rsa)
						{
							output->put<char>(AP_MSG_KEY_EXCHANGE_FAILED);
							addLogLine(LOGTYPE_EVENT, "no valid server key type");
							break;
						}

						output->put<char>(AP_MSG_KEY_EXCHANGE_OK);
						output->put<char>(ENCRYPTION_RSA1024XTEA);

						char RSAPublicKey[128];
						rsa->getPublicKey(RSAPublicKey);

						output->put<char>s(RSAPublicKey, 128);
						break;
					}

					default:
					{
						output->put<char>(AP_MSG_KEY_EXCHANGE_FAILED);
						addLogLine(LOGTYPE_EVENT, "no valid client key type");
						break;
					}
				}
			}
			else
			{
				output->put<char>(AP_MSG_KEY_EXCHANGE_FAILED);
				output->putString("cannot get public key");
				addLogLine(LOGTYPE_EVENT, "cannot get public key");
			}

			break;
		}

		case AP_MSG_COMMAND:
		{
			if(m_state != LOGGED_IN)
			{
				addLogLine(LOGTYPE_EVENT, "recvbyte == AP_MSG_COMMAND && m_state != LOGGED_IN !!!");
				break;
			}

			uint8_t command = msg.get<char>();
			switch(command)
			{
				case CMD_SAVE_SERVER:
				case CMD_SHALLOW_SAVE_SERVER:
				{
					uint8_t flags = (uint8_t)SAVE_PLAYERS | (uint8_t)SAVE_MAP | (uint8_t)SAVE_STATE;
					if(command == CMD_SHALLOW_SAVE_SERVER)
						flags |= SAVE_PLAYERS_SHALLOW;

					addLogLine(LOGTYPE_EVENT, "saving server");
					Dispatcher::getInstance().addTask(createTask(boost::bind(&Game::saveGameState, &g_game, flags)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_CLOSE_SERVER:
				{
					addLogLine(LOGTYPE_EVENT, "closing server");
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&Game::setGameState, &g_game, GAMESTATE_CLOSED)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_OPEN_SERVER:
				{
					addLogLine(LOGTYPE_EVENT, "opening server");
					g_game.setGameState(GAMESTATE_NORMAL);

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_SHUTDOWN_SERVER:
				{
					addLogLine(LOGTYPE_EVENT, "shutting down server");
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&Game::setGameState, &g_game, GAMESTATE_SHUTDOWN)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				case CMD_PAY_HOUSES:
				{
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandPayHouses, this)));
					break;
				}

				case CMD_RELOAD_SCRIPTS:
				{
					const int8_t reload = msg.get<char>();
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandReload, this, reload)));
					break;
				}

				case CMD_KICK:
				{
					const std::string param = msg.getString();
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandKickPlayer, this, param)));
					break;
				}

				case CMD_SEND_MAIL:
				{
					const std::string xmlData = msg.getString();
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&ProtocolAdmin::adminCommandSendMail, this, xmlData)));
					break;
				}

				case CMD_BROADCAST:
				{
					const std::string param = msg.getString();
					addLogLine(LOGTYPE_EVENT, "broadcasting: " + param);
					Dispatcher::getInstance().addTask(createTask(boost::bind(
						&Game::broadcastMessage, &g_game, param, MSG_STATUS_WARNING)));

					output->put<char>(AP_MSG_COMMAND_OK);
					break;
				}

				default:
				{
					output->put<char>(AP_MSG_COMMAND_FAILED);
					output->putString("not known server command");
					addLogLine(LOGTYPE_EVENT, "not known server command");
				}
			}
			break;
		}

		case AP_MSG_PING:
			output->put<char>(AP_MSG_PING_OK);
			break;

		case AP_MSG_KEEP_ALIVE:
			break;

		default:
		{
			output->put<char>(AP_MSG_ERROR);
			output->putString("not known command byte");

			addLogLine(LOGTYPE_EVENT, "not known command byte");
			break;
		}
	}

	if(output->size() > 0)
		OutputMessagePool::getInstance()->send(output);
}
예제 #7
0
int main() {


    int pprimes[18] = { 30839, 30841, 30851, 30853, 30859, 30869, 30871, 30881, 30893, 30911, 30931, 30937, 30941
            , 30949, 30971, 30977, 30983, 31013 };


    string str = "1";


    //Create 10 instances of the RSA class without giving arguments, generate random message or assign messages,
    // and perform encryption through each of the 10 classes.
    for (int i=0; i < 10; i++) {

        RSA* rsa = new RSA();
        str = str + "0";
        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part a message was:" << decmsg << endl;

        delete rsa;
    }

    //Create 5 instances of the RSA class by passing a large prime number [p](> 30,000), and perform encryption decryption
    for (int j=0; j < 5; j++) {

        RSA* rsa = new RSA(pprimes[j]);
        str = str + "1";

        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part b (1 prime) message was:" << decmsg << endl;

        delete rsa;
    }

    //Create 5 instances of the RSA class by passing 2 large prime numbers [p,q] (> 30,000) and perform encryption decryption
    for (int j=0; j < 5; j++) {

        RSA* rsa = new RSA(pprimes[j], pprimes[j+1]);
        str = str + "0";

        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part c (2 primes) message was:" << decmsg << endl;

        delete rsa;
    }

    //Create 10 instances of the RSA class by passing 2 large non prime numbers (> 30,000) and perform encryption decryption.
    // In most of the cases the message should not get decrypted correctly.
    for (int j=0; j < 10; j++) {
        //add one to the prime number to make it non-prime
        RSA* rsa = new RSA(pprimes[j] + 1, pprimes[j+1] + 1);
        str = str + "1";

        bitset<96> mssg (str);

        BigInt* msg = new BigInt(mssg);

        BigInt encrypted = rsa->encrypt(*msg);

        BigInt decrypted = rsa->decrypt(encrypted);

        string decmsg = decrypted.toString();

        cout << "part d (nonprimes) message was:" << decmsg << endl;

        delete rsa;
    }


    RSA* RSA1 = new RSA();
    RSA* RSA2 = new RSA();
    BigInt pub1 = RSA1->getPublicKey();
    BigInt n = RSA1->getModulus();
    BigInt* randmsg = new BigInt(rand());

    cout << "\n PART 2 " << endl;

    cout << "\nrandom message before encryption: " << randmsg->toString() << endl;

    RSA2->setPublicKey(pub1);
    RSA2->setN(n);

    BigInt encr = RSA2->encrypt(*randmsg);

    BigInt decr = RSA1->decrypt(encr);

    cout << "random message after encryption: " << decr.toString() << endl;

    //PART 3

    cout << "\n PART 3" << endl;

    //a. Alice obtains the public key and Modulus N of the person (Bob) who is to sign the message
    RSA* bob = new RSA();
    RSA* alice = new RSA();

    BigInt bpubkey = bob->getPublicKey();
    BigInt bmod = bob->getModulus();

    alice->setN(bmod);
    alice->setPublicKey(bpubkey);


    //b. Obtain a random number and its inverse with respect to the Modulus [Not phi] of Bob
    BigInt* randnum = new BigInt(rand());
    BigInt inverse = randnum->operator%(bob->getModulus());

    //c. Alice obtains/generates a message to be signed.
    BigInt* rmssg = new BigInt(rand());
    cout << "\nrandom message before encryption: " << rmssg->toString() << endl;

    //d. Alice encrypts the random number with the public key.
    BigInt emessg = alice->encrypt(*rmssg);

    //e. Alice multiplies this value by the message
    BigInt newval = emessg.operator*(*rmssg);

    //f. Alice then takes a modulus over N
    BigInt newmod = newval.operator%(alice->getModulus());

    //g. Alice sends it to Bob
    //h. Bob simply decrypts the received value with the private key

    BigInt bobdecrypt = bob->decrypt(newmod);

    //i. Bob sends it back to Alice
    //j. Alice then multiplied the received value with the inverse and takes a modulus over N.

    BigInt alicemult = bobdecrypt.operator*(inverse);
    BigInt alicemod = alicemult.operator%(alice->getModulus());

    //k. The value obtained above is the signed message. To obtain the original message from it, again encrypt it with Bob’s Public Key.
    BigInt original = alice->encrypt(alicemod);
    cout << "\n Alice decrypted message:  " << original.toString() << endl;

    return 0;
}