-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrsa.java
More file actions
88 lines (72 loc) · 3.04 KB
/
rsa.java
File metadata and controls
88 lines (72 loc) · 3.04 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.HashMap;
import java.util.Map;
import java.util.Scanner;
public class rsa{
private static BigInteger p,q,factor,totient,publicKey,privateKey;
private static Map<BigInteger,Character> map = new HashMap<>();
static void setup(){
p = new BigInteger("61");
q = new BigInteger("53");
factor = p.multiply(q);
totient = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
/*boolean flag = false;
for(int i = 2;!flag;i++)
{
BigInteger tmp = BigInteger.valueOf(i);
BigInteger g = tmp.gcd(totient);
if(g.compareTo(BigInteger.ONE) == 0)
{
publicKey = tmp;
flag = true;
}
}
privateKey = ((BigInteger.valueOf(15)).multiply(totient)).add( BigInteger.ONE );
privateKey = publicKey.divide(publicKey);*/
publicKey = BigInteger.valueOf(17);
privateKey = BigInteger.valueOf(2753);
}
static void _status(){
System.out.println("\np = " + p + "\nq = " + q + " \nfactor = " + factor + "\ntotient = " + totient);
System.out.println("\npublicKey = " + publicKey + "\nprivateKey = " + privateKey);
}
private static void map_setup(Map<BigInteger,Character> map){
for(int i = 32;i < 127;i++) map.put(BigInteger.valueOf(i),(char)i);
//for(int i = 32;i < 127;i++) System.out.println("map ( " + i + " ) = " + map.get(BigInteger.valueOf(i)));
}
public static BigInteger [] encrypt(String message){
BigInteger [] array = new BigInteger [message.length()];
map_setup(map);
for(int i = 0;i < message.length();i++){
BigInteger tmp = BigInteger.valueOf((int)message.charAt(i));
tmp = tmp.modPow(publicKey, factor);
array[i] = tmp;
}
System.out.println("\nThe Cipher Text :");
for(int i = 0;i < array.length;i++) System.out.print(array[i] + " ");
System.out.println();
return array;
}
public static void decrypt(BigInteger [] array){
Character [] arr = new Character [array.length];
for(int i = 0;i < array.length;i++){
BigInteger tmp = array[i].modPow(privateKey, factor);
arr[i] = map.get(tmp);
}
System.out.println("\nThe Recovered Plain Text :");
for(int i = 0;i < array.length;i++) System.out.print(arr[i]);
System.out.println();
}
public static void main(String [] args){
Scanner bt = new Scanner( System.in );
setup();
//_status();
System.out.print("Give the message : ");
String message = bt.nextLine();
BigInteger [] array = new BigInteger [message.length()];array = encrypt(message);
System.out.println("\n\nDo you want to decrypt the message (1/0)");
int choice = bt.nextInt();
if(choice == 1) decrypt(array);
bt.close();
}
}