insanetechvideos

rsa

Dec 2nd, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.io.IOException;
  3. import java.math.BigInteger;
  4. import java.util.Random;
  5. public class RSA_algorithm
  6. {
  7. public static void main(String[] args)//main method
  8. {
  9. BigInteger p,q,n,z,e,d;
  10. byte[] encrypted,decrypted =new byte[1000];
  11. int range=128;
  12. Random random = new Random();
  13. p = BigInteger.probablePrime(range, random);//find p randomly
  14. q = BigInteger.probablePrime(range, random);//find q randomly
  15. e = BigInteger.probablePrime(range, random);//find e randomly
  16. n = p.multiply(q);//n=p * q
  17. z = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));//z=(p-q)*(q-1)
  18. while (e.gcd(z).compareTo(BigInteger.ONE) > 0 && e.compareTo(z) < 0)//find e such that e & z are relatively prime
  19. {
  20. e = e.add(BigInteger.ONE);
  21. }
  22. d = e.modInverse(z);//find d such that (d*e)mod z=1
  23. long d1 = d.longValue();
  24. long n1 = n.longValue();
  25. System.out.println("d : "+Long.toHexString(d1) +"\nn : "+Long.toHexString(n1));//Print d and n
  26. Scanner in = new Scanner(System.in);
  27. System.out.println("Enter the Text:");//enter original text
  28. String text = in.nextLine();
  29. encrypted = encrypt_decrypt(text.getBytes(),e,n,true);//encrypt by passing original keyword,e,n
  30. decrypted = encrypt_decrypt(encrypted,d,n,false);//decrypt by passing cipher text,d,n
  31. System.out.println("Decrypted String: " + new String(decrypted));//Word after decryption
  32. }
  33.  
  34. public static byte[] encrypt_decrypt(byte[] message,BigInteger e, BigInteger n,boolean t) // Encrypt/decrypt method
  35. {
  36. BigInteger c=new BigInteger(message).modPow(e,n);//encrypt/decrypt
  37. if(t) {
  38. long n1 = c.longValue();
  39. String hex = Long.toHexString(n1);
  40. System.out.println("Cipher Text : "+hex);//print cipher text
  41. }
  42. return c.toByteArray();//BigInteger to byte array conversion with return
  43. }
  44. }
Add Comment
Please, Sign In to add comment