Advertisement
FahimFaisal

RSA

Nov 1st, 2019
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /*
  2. * To change this license header, choose License Headers in Project Properties.
  3. * To change this template file, choose Tools | Templates
  4. * and open the template in the editor.
  5. */
  6.  
  7. /**
  8. *
  9. * @author user
  10. */
  11. import java.util.*;
  12. import java.math.*;
  13.  
  14. public class RSA {
  15.  
  16. public static void main(String args[])
  17. {
  18. Scanner sc=new Scanner(System.in);
  19. int p,q,n,z,d=0,e,i;
  20. System.out.println("Enter the number to be encrypted and decrypted");
  21. int msg=sc.nextInt();
  22. double c;
  23. BigInteger msgback;
  24. System.out.println("Enter 1st prime number p");
  25. p=sc.nextInt();
  26. System.out.println("Enter 2nd prime number q");
  27. q=sc.nextInt();
  28.  
  29. n=p*q;
  30. z=(p-1)*(q-1);
  31. System.out.println("the value of z = "+z);
  32.  
  33. for(e=2;e<z;e++)
  34. {
  35. if(gcd(e,z)==1) // e is for public key exponent
  36. {
  37. break;
  38. }
  39. }
  40. System.out.println("the value of e = "+e);
  41. for(i=0;i<=9;i++)
  42. {
  43. int x=1+(i*z);
  44. if(x%e==0) //d is for private key exponent
  45. {
  46. d=x/e;
  47. break;
  48. }
  49. }
  50. System.out.println("the value of d = "+d);
  51. c=(Math.pow(msg,e))%n;
  52. System.out.println("Encrypted message is : -");
  53. System.out.println(c);
  54. //converting int value of n to BigInteger
  55. BigInteger N = BigInteger.valueOf(n);
  56. //converting float value of c to BigInteger
  57. BigInteger C = BigDecimal.valueOf(c).toBigInteger();
  58. msgback = (C.pow(d)).mod(N);
  59. System.out.println("Derypted message is : -");
  60. System.out.println(msgback);
  61.  
  62. }
  63.  
  64. public static int gcd(int e, int z)
  65. {
  66. if(e==0)
  67. return z;
  68. else
  69. return gcd(z%e,e);
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement