- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRSA.java
More file actions
Latest commit
73 lines (53 loc) · 2.49 KB
/
Copy pathRSA.java
File metadata and controls
73 lines (53 loc) · 2.49 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
importjava.io.*;
importjava.math.BigInteger;
importjava.util.Random;
publicclassRSA{
publicstaticvoidmain(String[] args) throwsIOException{
// BigInteger is used because of the huge values that will be generated
BigIntegerp, q, N, phi, e, d, cipherText, plainText, convertedInput;
intbitLength = 1024; // used to specify the length of the keys
// generate large prime numbers based on the bit length (1024)
p = BigInteger.probablePrime(bitLength, newRandom());
System.out.println("p is " + p);
System.out.println();
q = BigInteger.probablePrime(bitLength, newRandom());
System.out.println("q is " + q);
System.out.println();
// multiply both p and q
N = p.multiply(q);
System.out.println("N is " + N);
System.out.println();
// now calculate phi = (p-1)(q-1)
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
System.out.println("phi is " + phi);
System.out.println();
// now calculate e, which is less than and coprime to phi
do{
e = newBigInteger(2*bitLength, newRandom()); //execute this first
}
//and if its not less than, or coprime, do it again
while ((e.compareTo(phi) != -1)|| (e.gcd(phi).compareTo(BigInteger.valueOf(1)) != 0));
System.out.println("e is " + e);
System.out.println();
// now calculate d, the inverse of e mod phi
d = e.modInverse(phi);
System.out.println("d is " + d);
System.out.println();
// now we can get the input message
System.out.println("Please enter a message to encrypt.");
Stringinput = (newBufferedReader(newInputStreamReader(System.in))).readLine();
byte[] bytes = input.getBytes(); //converts input into its byte pattern for BigInteger
convertedInput = newBigInteger(bytes);
System.out.println("Message to be encrypted: " + input);
System.out.println();
// then encrypt it in the form (message^e mod N)
cipherText = convertedInput.modPow(e, N);
System.out.println("Encrypted message :" + cipherText);
System.out.println();
// Decrypt the message
plainText = cipherText.modPow(d, N);
// get the converted message from BigInteger and reassemble it as entered
StringconvertedPlainText = newString(plainText.toByteArray());
System.out.println("Decrypted message: " + convertedPlainText);
}//Main
}//RSA