Monday, December 24, 2007

The doRSA method

The doRSA method applies the RSA algorithm to an input string of numeric characters using a specified exponent exp and a specified modulus operator n. The input string is provided as the first input parameter to the method. The values of the exponent and the modulus operator are provided as the second and third input parameters.
This method can be used to encrypt or to decrypt the input string depending on whether the exponent is an encryption key or a decryption key.
The method is hard coded to apply the algorithm for a fixed block size of four characters. Thus, this is not a general-purpose RSA method that can be applied for different block sizes.
(I will provide a more general-purpose version of the method that allows for different block sizes in the next program.)
Let's see some code
Once again setting the main method aside temporarily, Listing 20 shows the beginning of the doRSA method.
String doRSA(String inputString,
BigInteger exp,BigInteger n){
BigInteger block;
BigInteger output;
String temp = "";
String outputString = "";

Listing 20
The code in Listing 20 declares and initializes some variables that will be used later.
Process one block at a time
Listing 21 shows the beginning of a for loop that iterates and processes the incoming string by subdividing the string into one block of four characters during each iteration.
for(int cnt = 0; cnt < inputString.length();
cnt += 4){
temp = inputString.substring(cnt,cnt + 4);
block = new BigInteger(temp);


Listing 21
The code in Listing 21 gets the next block of four characters and uses them to initialize a new BigInteger object that treats the four character substring as an integer.
(This is where the program gets into trouble and throws an exception if the length of the incoming string is not divisible by 4. In that case, the partial block at the end causes the invocation of the substring method to throw a StringIndexOutOfBoundsException.)

No comments: