Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.io.IOException;
- import java.math.BigInteger;
- import java.util.Random;
- public class RSA_algorithm
- {
- public static void main(String[] args)//main method
- {
- BigInteger p,q,n,z,e,d;
- byte[] encrypted,decrypted =new byte[1000];
- int range=128;
- Random random = new Random();
- p = BigInteger.probablePrime(range, random);//find p randomly
- q = BigInteger.probablePrime(range, random);//find q randomly
- e = BigInteger.probablePrime(range, random);//find e randomly
- n = p.multiply(q);//n=p * q
- z = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));//z=(p-q)*(q-1)
- while (e.gcd(z).compareTo(BigInteger.ONE) > 0 && e.compareTo(z) < 0)//find e such that e & z are relatively prime
- {
- e = e.add(BigInteger.ONE);
- }
- d = e.modInverse(z);//find d such that (d*e)mod z=1
- long d1 = d.longValue();
- long n1 = n.longValue();
- System.out.println("d : "+Long.toHexString(d1) +"\nn : "+Long.toHexString(n1));//Print d and n
- Scanner in = new Scanner(System.in);
- System.out.println("Enter the Text:");//enter original text
- String text = in.nextLine();
- encrypted = encrypt_decrypt(text.getBytes(),e,n,true);//encrypt by passing original keyword,e,n
- decrypted = encrypt_decrypt(encrypted,d,n,false);//decrypt by passing cipher text,d,n
- System.out.println("Decrypted String: " + new String(decrypted));//Word after decryption
- }
- public static byte[] encrypt_decrypt(byte[] message,BigInteger e, BigInteger n,boolean t) // Encrypt/decrypt method
- {
- BigInteger c=new BigInteger(message).modPow(e,n);//encrypt/decrypt
- if(t) {
- long n1 = c.longValue();
- String hex = Long.toHexString(n1);
- System.out.println("Cipher Text : "+hex);//print cipher text
- }
- return c.toByteArray();//BigInteger to byte array conversion with return
- }
- }
Add Comment
Please, Sign In to add comment