You are on page 1of 3

Experiment 3: RSA algorithm

/*CODE:*/ import java.math.*; import java.math.BigInteger; import java.util.*; import java.io.*; import java.lang.*; public class RSA1 { private static int bitlength = 1024; public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter the message"); String msg1 = br.readLine(); char msg[]=msg1.toCharArray(); char decrypt2[]=new char[msg.length]; long finalmsg[]=new long[msg.length]; String decrypt1=""; for(int i=0;i<msg.length;i++) { finalmsg[i]=(long)msg[i]; } Random r = new Random(); Random r1 = new Random(); BigInteger p = BigInteger.probablePrime(8,r); BigInteger q = BigInteger.probablePrime(8, r1); BigInteger modulos = p.multiply(q); BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE)); System.out.println("Modulos:"+modulos); System.out.println("Enter your public key"); Random x=new Random(); BigInteger e = BigInteger.probablePrime(bitlength/2, r); while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0 ) { e.add(BigInteger.ONE); } // compute public key BigInteger publicKey = e.modInverse(phi); System.out.println("Public key is :"+publicKey); BigInteger privateKey = publicKey.modInverse(phi); System.out.println("Private key:"+privateKey);
1

Experiment 3: RSA algorithm


for(int j=0;j<finalmsg.length;j++) { System.out.println(); System.out.println("For character :"+msg[j]); BigInteger msges=BigInteger.valueOf(finalmsg[j]); BigInteger encrypt=msges.modPow(publicKey, modulos); BigInteger decrypt=encrypt.modPow(privateKey, modulos); System.out.println("encrypted message:"+encrypt); System.out.println("decrypted message:"+decrypt); decrypt1=String.valueOf(decrypt); int n = Integer.parseInt(decrypt1); decrypt2[j]=(char)n; } System.out.println(); System.out.println("Decrypted message is:"+decrypt1+"\n In Alphabets: "); for(int k=0;k<decrypt2.length;k++) System.out.print(decrypt2[k]); } }

Experiment 3: RSA algorithm


/*OUTPUT:

*/

You might also like