-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path11.RSA.java
More file actions
70 lines (51 loc) · 2.05 KB
/
11.RSA.java
File metadata and controls
70 lines (51 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
*/
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Scanner;
class RSA {
static BigInteger p, q, n, phi_n, e, d;
static SecureRandom secureRandom;
static int bitLength = 64;
static String encrypt(String msg) {
return new BigInteger(msg.getBytes()).modPow(e, n).toString();
}
static String decrypt(String cipher) {
BigInteger bi = new BigInteger(cipher).modPow(d, n);
return new String(bi.toByteArray());
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
secureRandom = new SecureRandom();
p = BigInteger.probablePrime(bitLength, secureRandom);
q = BigInteger.probablePrime(bitLength, secureRandom);
n = p.multiply(q);
phi_n = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitLength / 2, secureRandom);
while (e.gcd(phi_n).compareTo(BigInteger.ONE) != 0 && e.compareTo(phi_n) < 0) {
e = e.add(BigInteger.ONE);
}
d = e.modInverse(phi_n);
System.out.println("P assigned as: " + p);
System.out.println("Q assigned as: " + q);
System.out.println("N assigned as: " + n);
System.out.println("PHI_N assigned as: " + phi_n);
System.out.println("\nEnter Message");
String msg = scanner.nextLine();
String encryptedMessage = encrypt(msg);
System.out.println("Encrypted Message: " + encryptedMessage);
String decryptedMessage = decrypt(encryptedMessage);
System.out.println("Decrypted Message: " + decryptedMessage);
}
}
////////////
// Output
// P assigned as: 18331937448746061757
// Q assigned as: 14660384846134004581
// N assigned as: 268753257973873229081240359403146908817
// PHI_N assigned as: 268753257973873229048248037108266842480
// Enter Message
// Hello World
// Encrypted Message: 185814656462362097147843651345248330194
// Decrypted Message: Hello World