I'm currently working on a lab assignment for school, it involves with encrypting a text file with RSA encryption/decryption. Now the problem is I need to break the text file into block before encrypting it, so that the block size is not bigger than the size of the modulus value. My question is how would you break the file into several small block. The following is the code provided as reference to implement my code.
import java.math.BigInteger;
import java.io.*;
import java.util.Random;
class RSA {
static public void main(String args[]){
int KEY_SIZE = 128;
// Create a BigInteger constant for the integer ’1’.
BigInteger one = new BigInteger("1");
// Determine a modulus of sufficient size (based on the size of P and Q).
BigInteger p = new BigInteger(KEY_SIZE,20, new Random());
BigInteger q = new BigInteger(KEY_SIZE,20, new Random());
BigInteger n = p.multiply(q);
// Calculate PHI(n) for use in determining the public and private exponents.
BigInteger phi = p.subtract(one).multiply(q.subtract(one));
// Select a public exponent (repeat until GCD condition is met).
BigInteger e = new BigInteger(32,4, new Random());
BigInteger gcd = phi.gcd(e);
while (!gcd.equals(one)) {
e = new BigInteger(32,4, new Random());
gcd = phi.gcd(e);
}
// Calculate the private exponent.
BigInteger d = e.modInverse(phi);
// Print out all pertinent data:
System.out.println("Key Length = " + KEY_SIZE);
System.out.println();
System.out.println("P = " + p);
System.out.println("Q = " + q);
System.out.println("Modulus n = " + n);
System.out.println("PHI = " + phi);
System.out.println("Public Exponent e = " + e);
System.out.println("Private Exponent d = " + d);
System.out.println("d e mod phi = " + d.multiply(e).mod(phi));
// Create message to be encoded as a string!!
String messageString;
try{
messageString = args[0];
}
catch(ArrayIndexOutOfBoundsException error){
messageString = "RSA is cool";
}
// Create a simple BigInteger message using the constructor for Strings
// representing numbers.
byte[] byteArray = messageString.getBytes();
BigInteger messageAsBigInt = new BigInteger(byteArray);
// Encrypt and decrypt the message text.
BigInteger cypherAsBigInt = messageAsBigInt.modPow(e,n);
BigInteger decypherAsBigInt = cypherAsBigInt.modPow(d,n);
byte[] byteArrayBack = messageAsBigInt.toByteArray();
String messageStringBack = new String(byteArrayBack);
System.out.println("The messageString is : " + messageString);
System.out.println("The message as messageAsBigInt : " + messageAsBigInt);
System.out.println("The cyphertext cypherAsBigInt is : " + cypherAsBigInt);
System.out.println("The decrypted cipher decypherAsBigInt is: " + decypherAsBigInt);
System.out.println("The messageStringBack is : " + messageStringBack);
} // main()
} // RSA