-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSA.java
More file actions
88 lines (81 loc) · 2.92 KB
/
Copy pathRSA.java
File metadata and controls
88 lines (81 loc) · 2.92 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import java.math.BigInteger;
import java.util.*;
class RSA {
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private Random r;
public RSA() {
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) {
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger N) {
this.e = e;
this.d = d;
this.N = N;
}
private static String bytesToString(byte[] encrypted) {
String test = "";
for (byte b : encrypted) {
test += Byte.toString(b);
}
return test;
}
// Encrypt message
public byte[] encrypt(byte[] message) {
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message) {
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
public static void main(String[] args) {
RSA rsa = new RSA();
String teststring = "";
byte[] encrypted = {};
Scanner in = new Scanner(System.in);
int cont = 1;
while (cont != 0) {
System.out.println(
"Enter your choice (Please select 1 before encrypt or decrypt)\n1.Text \n2.Encrypt\n3.Decrypt");
int choice = in.nextInt();
in.nextLine();
switch (choice) {
case 1:
System.out.println("Enter the plain text:");
teststring = in.nextLine();
break;
case 2:
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: " + bytesToString(teststring.getBytes()));
encrypted = rsa.encrypt(teststring.getBytes());
System.out.println(encrypted);
break;
case 3:
System.out.println("Decrypting : " + encrypted);
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
break;
default:
System.out.println("Wrong choice");
}
// sc.nextLine();
System.out.println("Do you want to continue?\nYes(1)\nNo(0)");
cont = in.nextInt();
in.nextLine();
}
}
}