-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathRSA.java
127 lines (64 loc) · 2.23 KB
/
RSA.java
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
import java.math.BigInteger;
import java.util.Random;
import java.io.*;
public class Main {
public BigInteger p;
public BigInteger q;
public BigInteger N;
public BigInteger phi;
public BigInteger e;
public BigInteger d;
public int bitlength = 1024;
public int blocksize = 256;
//blocksize in byte
private Random r;
public Main() {
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 Main(BigInteger e, BigInteger d, BigInteger N) {
this.e = e;
this.d = d;
this.N = N;
}
public static void main (String[] args) throws IOException {
Main rsa = new Main();
DataInputStream in=new DataInputStream(System.in);
String teststring ;
System.out.println("Enter the plain text:");
teststring=in.readLine();
//System.out.println("P="+p+"Q="+q+"N="+n);
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: " + bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
System.out.println("Encrypted String in Bytes: " + bytesToString(encrypted));
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypted String in Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}
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();
}
}