-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRSA.java
More file actions
85 lines (68 loc) · 2.23 KB
/
RSA.java
File metadata and controls
85 lines (68 loc) · 2.23 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
package javaapplication;
import java.math.BigInteger;
import java.util.Random;
import java.io.*;
import java.math.BigInteger;
public class RSA {
public static BigInteger p;
public static BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 62;
private int blocksize = 256;
private Random r;
public RSA() {
long x=3053880317135553533L;
long y=3916702577991933803L;
long z=1678030687;
p = BigInteger.valueOf(x);
q = BigInteger.valueOf(y);
e= BigInteger.valueOf(z);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) {
e.add(BigInteger.ONE); //e=e+1
}
d = e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger N) {
this.e = e;
this.d = d;
this.N = N;
}
public static void main(String[] args) throws IOException {
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: " + bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encryptRSA(teststring.getBytes());
System.out.println("Encrypted String in Bytes: " + bytesToString(encrypted));
System.out.println("Encrypted String in Bytes: " + encrypted);
// decrypt
byte[] decrypted = rsa.decryptRSA(encrypted);
System.out.println("Decrypted String in Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
System.out.println("Decrypted String: " + decrypted);
}
public static String bytesToString(byte[] encrypted) {
String test = "";
for (byte b : encrypted) {
test += Byte.toString(b);
}
return test;
}
// Encrypt message
public byte[] encryptRSA(byte[] message) {
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decryptRSA(byte[] message) {
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}