fork download
  1. /* package whatever; // don't place package name! */
  2. //RSA ENCRYPTION AND DECRYPTION
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. int p,q,n,c,d,u,e,m,l,m1;
  13. String message = "hide";
  14. String ans="";
  15. String ctext="";
  16. int i=0;
  17. l = message.length();
  18. System.out.println("message is "+message);
  19. while(i <l)
  20. {
  21. m =message.charAt(i)-'a' ;
  22. i++;
  23.  
  24. p= 3;
  25. q = 7;
  26. e = 2;
  27. n = p*q;
  28. //System.out.println("value of n "+n);
  29. u = (p-1)*(q-1);
  30. // System.out.println("value of u "+u);
  31.  
  32.  
  33. while (e < u)
  34. {
  35.  
  36. if (gcd(e,u)==1)
  37. break;
  38. else
  39. e++;
  40. }
  41.  
  42.  
  43. //System.out.println("value of e "+e);
  44. d = solve(e,u);
  45.  
  46. if(d<0)
  47. d = (d+u)%u;
  48. //System.out.println("d value obtained is"+d);
  49.  
  50. c = ((int)Math.pow(m,d))%n;
  51. ctext += (char)(c+97);
  52. //System.out.println("encrypted text is"+c);
  53. m1 = ((int)Math.pow(c,e))%n;
  54. // System.out.println("decrypted text is"+m);
  55. ans += (char)(m1+97);
  56. }
  57. System.out.println("encrypted text is -"+ctext);
  58. System.out.println("decrypted text is -"+ans);
  59. int v = verifyalgo(ans,message);
  60. if(v == 1)
  61. System.out.println("Bob sent the message");
  62. else
  63. System.out.println("Alice sent the message");
  64.  
  65.  
  66. }
  67.  
  68. public static int solve(int a, int b)
  69. {
  70. int x = 0, y = 1, lastx = 1, lasty = 0, temp;
  71. while (b != 0)
  72. {
  73. int q = a / b;
  74. int r = a % b;
  75.  
  76. a = b;
  77. b = r;
  78.  
  79. temp = x;
  80. x = lastx - q * x;
  81. lastx = temp;
  82.  
  83.  
  84. }
  85. return lastx;
  86. }
  87.  
  88.  
  89. public static int verifyalgo(String m1 ,String m)
  90. {
  91.  
  92. //System.out.println(m1.compareTo(m));
  93. if(m1.compareTo(m)==0)
  94. return 1;
  95. else
  96. return 0;
  97. }
  98.  
  99.  
  100. public static int gcd(int a, int h)
  101. {
  102. int temp;
  103. while (true)
  104. {
  105. temp = a%h;
  106. if (temp == 0)
  107. return h;
  108. a = h;
  109. h = temp;
  110. }
  111. }
  112.  
  113.  
  114. }
Success #stdin #stdout 0.04s 4386816KB
stdin
Standard input is empty
stdout
message is  hide
encrypted text is   -himq
decrypted text is   -hide
Bob sent the message