package be.demmel.jgws.test;

import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.demmel.jgws.utils.GeneralUtils;
import be.demmel.jgws.utils.encryption.EncryptionUtils;

public class TestMain {
	private static final Logger LOG = LoggerFactory.getLogger(TestMain.class);
	
	private static final byte[] SERVER_PRIVATE_KEY_ARRAY = { 0x62, (byte) 0x96, 0x7D, 0x5E, 0x45, 0x6D, (byte) 0x8F, (byte) 0xF3, (byte) 0xA8, 0x66,
		(byte) 0xB8, (byte) 0xDD, (byte) 0xD1, (byte) 0xF7, (byte) 0xD0, (byte) 0xEA, 0x7D, 0x54, 0x12, (byte) 0x8F, 0x4C, 0x4F, 0x0F, 0x33, 0x3F, 0x58,
		0x7E, 0x44, 0x09, 0x70, (byte) 0xFF, (byte) 0xC1, (byte) 0xB7, (byte) 0x9D, 0x3B, (byte) 0xE7, 0x5F, 0x66, (byte) 0xB6, 0x2D, 0x6E, (byte) 0xA9,
		0x0D, (byte) 0xD2, 0x2B, 0x76, 0x53, (byte) 0xC8, 0x6E, 0x39, 0x23, (byte) 0xDD, (byte) 0xB7, (byte) 0xF1, 0x02, (byte) 0xC6, 0x63, 0x42,
		(byte) 0xF1, 0x1E, (byte) 0x83, 0x6E, 0x33, 0x21 }; // LITTLE_ENDIAN
	
	private static final byte[] PRIME_ARRAY = { 0x00, (byte) 0xEB, 0x74, 0x42, 0x1E, (byte) 0x8C, 0x7F, (byte) 0xEE, (byte) 0xB7, (byte) 0xD8, 0x0A,
		(byte) 0xEF, 0x07, 0x7B, (byte) 0x94, 0x1D, 0x6D, (byte) 0xFA, (byte) 0xD3, (byte) 0x96, 0x59, 0x1C, (byte) 0x9C, (byte) 0xC0, 0x7A, 0x45, 0x3E,
		0x7E, (byte) 0xC9, 0x0C, (byte) 0xA5, (byte) 0xA1, (byte) 0xD7, (byte) 0x90, 0x5D, 0x29, (byte) 0x8E, 0x4D, 0x6D, (byte) 0xA4, (byte) 0xF4,
		(byte) 0x91, 0x61, (byte) 0xBD, 0x3B, (byte) 0xDB, (byte) 0x8C, (byte) 0xD6, 0x5C, 0x42, 0x55, (byte) 0x99, (byte) 0x99, 0x20, (byte) 0xD8,
		(byte) 0xDD, (byte) 0xA7, 0x78, 0x1B, 0x07, (byte) 0xD4, (byte) 0x97, (byte) 0xC0, (byte) 0xF6, (byte) 0xBB }; // BIG_ENDIAN
	
	private static final byte[] SERVER_PUBLIC_KEY_ARRAY = { (byte)0xC3, (byte)0xA2, 0x0C, (byte)0xE0, 0x72, 0x21, (byte)0xAE, (byte)0xF5, (byte)0xAE, 0x1A, 0x36, 
		(byte)0xD5, 0x35, 0x23, (byte)0xC3, 0x0D, 0x74, 0x21, 0x15, 0x06, 0x63, (byte)0x8F, 0x38,
		0x6B, (byte)0x83, 0x7E, 0x6A, 0x3C, (byte)0xFE, 0x51, (byte)0xD0, 0x13, 0x69, 0x40, (byte)0xE9, 0x3E, 0x49, (byte)0x80, 0x37, (byte)0x8B, (byte)0xF4,
		(byte)0x88, (byte)0x86, 0x48, 0x59, 0x64, (byte)0x86,
		0x3D, 0x43, (byte)0xD0, 0x7A, 0x59, (byte)0xE5, 0x58,(byte)0x91, 0x24, (byte)0x8D, 0x23, 0x2C, 0x4C, 0x28, (byte)0x8F, (byte)0xAF, (byte)0xA1, 0x00 }; // LITTLE_ENDIAN
	
	public static void main(String... args) {
		ArrayUtils.reverse(SERVER_PRIVATE_KEY_ARRAY);
		ArrayUtils.reverse(SERVER_PUBLIC_KEY_ARRAY);
		BigInteger PRIME = new BigInteger(PRIME_ARRAY);
		BigInteger SERVER_PRIVATE_KEY = new BigInteger(SERVER_PRIVATE_KEY_ARRAY);
		BigInteger SERVER_PUBLIC_KEY = new BigInteger(SERVER_PUBLIC_KEY_ARRAY);

		LOG.debug("Prime to be used: {}", PRIME);
		LOG.debug("Server private key to be used: {}", SERVER_PRIVATE_KEY);
		LOG.debug("Server public key to be used: {}", SERVER_PUBLIC_KEY);
		
		//BigInteger calculatedPublicKey = BigInteger.valueOf(4).modPow(SERVER_PRIVATE_KEY, PRIME);
		//LOG.debug("Server public calculated: {}", calculatedPublicKey);
		
		// CLIENT
		// generate random bytes to generate a client private key
		byte[] clientPrivateKeyBytes = new byte[64];
		new SecureRandom().nextBytes(clientPrivateKeyBytes);
		BigInteger clientPrivateKey = new BigInteger(1, clientPrivateKeyBytes);
		
		// calculate the public key
		BigInteger clientPublicKey = BigInteger.valueOf(4).modPow(clientPrivateKey, PRIME);
		LOG.debug("Client public key: {}", clientPublicKey);
		
		// calculate the shared key
		BigInteger clientSharedKey = SERVER_PUBLIC_KEY.modPow(clientPrivateKey, PRIME);
		LOG.debug("Client shared key: {}", clientSharedKey);
		
		// SERVER
		// do as if we receive the packet: unsigned bytes
		byte[] clientPublicKeyBytes = GeneralUtils.getBytesFromBigInteger(clientPublicKey);
		
		// now put that in a short array
		short[] shortsForPacket = GeneralUtils.bytesToShorts(clientPublicKeyBytes);
		// end weird stuff
		
		byte[] bytes = GeneralUtils.shortsToBytes(shortsForPacket);

		ArrayUtils.reverse(bytes); // the client's public key is received in LITTLE_ENDIAN
		BigInteger publicClientKey = new BigInteger(1, bytes);
		LOG.debug("Public client key: {}", publicClientKey);

		// Diffie-Hellman: generate a shared key (publicClientKey ^ SERVER_PRIVATE_KEY % PRIME).
		BigInteger sharedKey = publicClientKey.modPow(SERVER_PRIVATE_KEY, PRIME);
		byte[] sharedKeyBytes = GeneralUtils.getBytesFromBigInteger(sharedKey);
		LOG.debug("Server shared key: {} ({} bytes)", sharedKey, sharedKeyBytes.length);
		// END Diffie-Hellman

		// START generate a hashed and XORed seed
		byte[] randomBytes = new byte[20];
		new SecureRandom().nextBytes(randomBytes);

		byte[] finalRC4Key = EncryptionUtils.hash(randomBytes);
		LOG.debug("RC4 Key: {}", Arrays.toString(finalRC4Key));
		byte[] xoredKey = EncryptionUtils.XOR(randomBytes, sharedKeyBytes);
		// convert back to shorts to send to the client
		short[] shortsForClient = GeneralUtils.bytesToShorts(xoredKey);
		LOG.debug("XORed key: {}", Arrays.toString(shortsForClient));
		// END generate a hashed seed

		//RC4Tool.setRC4Key(hashedSeed);

//		ServerSeed serverSeed = new ServerSeed();
//		serverSeed.setSeed(shortsForClient);
//		actionsAndOutgoingPackets.addOutgoingPacket(serverSeed);
		
		// CLIENT - part 2
		byte[] keyBytesFromServer = GeneralUtils.shortsToBytes(shortsForClient);
		
		byte[] clientSharedKeyBytes = GeneralUtils.getBytesFromBigInteger(clientSharedKey);
		
		byte[] clientRandomBytes = EncryptionUtils.XOR(keyBytesFromServer, clientSharedKeyBytes);
		LOG.debug("Client random bytes: {}", Arrays.toString(clientRandomBytes));
		
		byte[] finalClientRC4Key = EncryptionUtils.hash(clientRandomBytes);
		LOG.debug("Client RC4 Key: {}", Arrays.toString(finalClientRC4Key));
		
		try {
			SecretKeySpec rc4Key = new SecretKeySpec(finalClientRC4Key, "RC4");
			
			Cipher rc4Encrypt = Cipher.getInstance("RC4");
			rc4Encrypt.init(Cipher.ENCRYPT_MODE, rc4Key);

			Cipher rc4Decrypt = Cipher.getInstance("RC4");
			rc4Decrypt.init(Cipher.DECRYPT_MODE, rc4Key);
			
			byte[] tobeencrypted = {0x01,0x02};
			byte[] encryptedBytes = rc4Encrypt.update(tobeencrypted);
			byte[] decryptedBytes = rc4Decrypt.update(encryptedBytes);
			LOG.debug("{},{}",decryptedBytes[0],decryptedBytes[1]);
			
		} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
			throw new RuntimeException(e);
		}
		
		byte[] res = EncryptionUtils.XOR(new byte[]{(byte)128}, new byte[]{10});
		LOG.debug("Result: {}", res[0] & 0xFF);
	}
}
