Advertisement
PadmaJS

RSA encryption code

May 9th, 2024
736
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 1.31 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class RSAEncryption {
  4.   RSAEncryption() {
  5.     Scanner sc = new Scanner(System.in);
  6.     System.out.print("Enter a prime number for p: ");
  7.     int p = sc.nextInt();
  8.     System.out.print("Enter a prime number for q: ");
  9.     int q = sc.nextInt();
  10.     int n = p * q;
  11.     int phi = (p - 1) * (q - 1);
  12.     int d, e;
  13.     do {
  14.       System.out.print("Enter value of public key e: ");
  15.       e = sc.nextInt();
  16.     } while (RSAEncryption.getGCD(e, phi) != 1);
  17.  
  18.     for (d = 1; d < phi; d++) {
  19.       if ((e * d) % phi == 1) {
  20.         break;
  21.       }
  22.     }
  23.  
  24.     System.out.print("Enter message: ");
  25.     int message = sc.nextInt();
  26.  
  27.     int encrypted = RSAEncryption.modPow(e, n, message);
  28.     System.out.println("Encrypted message:" + encrypted);
  29.  
  30.     int decrypted = RSAEncryption.modPow(d, n, encrypted);
  31.     System.out.println("Decrypted message: " + decrypted);
  32.   }
  33.  
  34.   static int getGCD(int a, int b) {
  35.     while (b != 0) {
  36.       int temp = b;
  37.       b = a % b;
  38.       a = temp;
  39.     }
  40.     return a;
  41.   }
  42.  
  43.   static int modPow(int exp, int mod, int base) {
  44.     int result = 1;
  45.     base = base % mod;
  46.     for (int i = 0; i < exp; i++) {
  47.       result = (result * base) % mod;
  48.     }
  49.     return result;
  50.   }
  51.  
  52.   public static void main(String[] args) {
  53.     new RSAEncryption();
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement