RSA.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. Name: Ajinkya Arun Gurav
  3. Div : H Roll No:21
  4. GR No : 121237
  5. Subject : Network Security Lab
  6. Lab 5: Implement encryption and decryption using RSA Algorithm.
  7. */
  8. import java.math.BigInteger;
  9. import java.util.*;
  10. public class RSA {
  11. public static void main(String[] args) {
  12. // TODO code application logic here
  13. BigInteger p,q,phin,n,m,c,e,l,d=BigInteger.ONE;
  14. Integer k=0,y=0,res=0,res1=0;
  15. Scanner sc=new Scanner(System.in);
  16. System.out.println("Enter p");
  17. p=sc.nextBigInteger();
  18. System.out.println("Enter q");
  19. q=sc.nextBigInteger();
  20. n=BigInteger.valueOf(p.intValue()*q.intValue());
  21. phin=BigInteger.valueOf((p.intValue()-1)*(q.intValue()-1));
  22. System.out.println("phin is:"+phin+"\nEnter e");
  23. e=sc.nextBigInteger();
  24. if(e.intValue()>phin.intValue())
  25. System.out.println("Enter value of e lesser than "+phin);
  26. k=e.intValue();
  27. /*for(d=1;d<phin.intValue();(d)++)
  28. {
  29. y=d*k;
  30. l=BigInteger.valueOf(y);
  31. //if(((y)).mod(phin)==1)
  32. if(l.mod(phin).equals(BigInteger.ZERO))
  33. break;
  34. }*/
  35. // d=e.modInverse(phin);
  36. res=d.compareTo(phin);
  37. long temp;
  38. while(res==-1)
  39. {
  40. y=d.intValue()*k;
  41. l=BigInteger.valueOf(y);
  42. res1=((l).mod(phin)).compareTo(BigInteger.ONE);
  43. if(res1==0)
  44. break;
  45. temp=d.intValue();
  46. temp++;
  47. d=BigInteger.valueOf(temp);
  48. //d.add(new BigInteger("1"));
  49. res=d.compareTo(phin);
  50. }
  51. System.out.println("d is: "+d.intValue()+"\nEnter Plaintext");
  52. m=sc.nextBigInteger();
  53. c=(BigInteger)((m.pow(e.intValue())).mod(n));
  54. System.out.println("C is: "+c);
  55. m=(BigInteger)((c.pow(d.intValue())).mod(n));
  56. System.out.println("M is: "+m);
  57. }
  58. }
  59. /*
  60. * OUTPUT:
  61. Enter p
  62. 3
  63. Enter q
  64. 11
  65. phin is:20
  66. Enter e
  67. 7
  68. d is: 3
  69. Enter Plaintext
  70. 2
  71. C is: 29
  72. M is: 2
  73. */