document.write('<script type="text/javascript" src="/scripts/BigInt.js"></script>');
document.write('<script type="text/javascript" src="/scripts/Barrett.js"></script>');

// Class: rsa
function rsa(bitSize) {
	this.encryptionKey=rsa_encryptionKey;
	this.decryptionKey=rsa_decryptionKey;
	this.encrypt=rsa_encrypt;
	this.test=rsa_test;
	setMaxDigits(bitSize);
}
function rsa_test() {
	alert("RSA Running.");
}
function rsa_encryptionKey(encrypt,modulus) {
	this.e=biFromHex(encrypt);
	rsa_baseKeySetup(this,modulus);
}
function rsa_decryptionKey(decrypt,modulus) {
	this.d=biFromHex(decrypt);
	rsa_baseKeySetup(this,modulus);
}
function rsa_baseKeySetup(o,modulus) {
	o.m=biFromHex(modulus);
	o.digitSize=2*biHighIndex(o.m)+2;
	o.chunkSize=o.digitSize-11;
	o.radix=16;
	o.barrett=new BarrettMu(o.m);
}
function rsa_encrypt(msg) {
	if (this.chunkSize>this.digitSize-11) return "Error (failed rules of RSA)";
	var a = new Array();
	var sl = msg.length;
	var i = 0;
	while (i<sl) {
		a[i]=msg.charCodeAt(i);
		i++;
	}
	var al=a.length;
	var result="";
	var j,k,block,x,msgLen,paddedSize,crypt;
	for (i = 0; i < al; i += this.chunkSize) {
		block = new BigInt();
		j = 0;
		msgLen = (i+this.chunkSize)>al ? al%this.chunkSize : this.chunkSize;
		var b = new Array();
		for (x=0; x<msgLen; x++) {
		    b[x] = a[i+msgLen-1-x];
		}
		b[msgLen] = 0;
		paddedSize = Math.max(8, this.digitSize - 3 - msgLen);
		for (x=0; x<paddedSize; x++) {
			b[msgLen+1+x] = Math.floor(Math.random()*254)+1;
		}
		b[this.digitSize-2] = 2;
		b[this.digitSize-1] = 0;
		for (k = 0; k < this.digitSize; ++j) {
		    block.digits[j] = b[k++];
		    block.digits[j] += b[k++] << 8;
		}
		crypt = this.barrett.powMod(block, this.e);
		result += biToHex(crypt) + " ";
	}
	return result.substring(0, result.length - 1);
}
function rsa_decrypt(msg) {
	//Needs some work.
}
/*function decryptedString(key, s)
{
	var blocks = s.split(" ");
	var result = "";
	var i, j, block;
	for (i = 0; i < blocks.length; ++i) {
		var bi;
		if (key.radix == 16) {
			bi = biFromHex(blocks[i]);
		}
		else {
			bi = biFromString(blocks[i], key.radix);
		}
		block = key.barrett.powMod(bi, key.d);
		for (j = 0; j <= biHighIndex(block); ++j) {
			result += String.fromCharCode(block.digits[j] & 255,
			                              block.digits[j] >> 8);
		}
	}
	// Remove trailing null, if any.
	if (result.charCodeAt(result.length - 1) == 0) {
		result = result.substring(0, result.length - 1);
	}
	return result;
}*/
