// Encryption/decryption helper.


var E_IS_NOT_VALID = "Encryption exponent has to be valid hex number.";
var D_IS_NOT_VALID = "Decryption exponent has to be valid hex number.";
var N_IS_NOT_VALID = "Modulus has to be valid hex number.";

function is_valid_hex_key(string)
{
    var hex_re = /^[0-9a-f]+/;

    var key = string.match(hex_re);

    if (key != string) {
	return false;
    }
    else {
	return true;
    }
}

function encrypt(msg, e, n, callback)
{
    var key_pair;

    setMaxDigits(Math.ceil(n.length / 2) + 5);
    init_starting_time();

    if (is_valid_hex_key(e)) {
	if (is_valid_hex_key(n)) {
	    RSAKeyPair(e, e, n,
		       function(key_pair)
		       {
			   encryptedString(key_pair, msg,
					   function(result)
					   {
					       callback(result);
					   }
					  );
		       }
		      );
	}
	else {
	    alert(N_IS_NOT_VALID);
	}
    }
    else {
	alert(E_IS_NOT_VALID);
    }
}

function decrypt(msg, d, n, callback)
{
    setMaxDigits(Math.ceil(n.length / 2) + 5);
    init_starting_time();

    if (is_valid_hex_key(d)) {
	if (is_valid_hex_key(n)) {
	    RSAKeyPair(d, d, n,
		       function(key_pair)
		       {
			   decryptedString(key_pair, msg,
					   function(result)
					   {
					       callback(result);
					   }
					  );
		       }
		      );
	}
	else {
	    alert(N_IS_NOT_VALID);
	}
    }
    else {
	alert(D_IS_NOT_VALID);
    }
}

