Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class RSAEncryption {
- RSAEncryption() {
- Scanner sc = new Scanner(System.in);
- System.out.print("Enter a prime number for p: ");
- int p = sc.nextInt();
- System.out.print("Enter a prime number for q: ");
- int q = sc.nextInt();
- int n = p * q;
- int phi = (p - 1) * (q - 1);
- int d, e;
- do {
- System.out.print("Enter value of public key e: ");
- e = sc.nextInt();
- } while (RSAEncryption.getGCD(e, phi) != 1);
- for (d = 1; d < phi; d++) {
- if ((e * d) % phi == 1) {
- break;
- }
- }
- System.out.print("Enter message: ");
- int message = sc.nextInt();
- int encrypted = RSAEncryption.modPow(e, n, message);
- System.out.println("Encrypted message:" + encrypted);
- int decrypted = RSAEncryption.modPow(d, n, encrypted);
- System.out.println("Decrypted message: " + decrypted);
- }
- static int getGCD(int a, int b) {
- while (b != 0) {
- int temp = b;
- b = a % b;
- a = temp;
- }
- return a;
- }
- static int modPow(int exp, int mod, int base) {
- int result = 1;
- base = base % mod;
- for (int i = 0; i < exp; i++) {
- result = (result * base) % mod;
- }
- return result;
- }
- public static void main(String[] args) {
- new RSAEncryption();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement