-
Notifications
You must be signed in to change notification settings - Fork 0
/
User_A_Deffi_Hel.java
141 lines (109 loc) · 3.22 KB
/
User_A_Deffi_Hel.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package cyberSecurity;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;
public class User_A_Deffi_Hel {
static boolean isprime(int x){
for(int i=2;i<= Math.sqrt(x);i++){
if (x % i == 0)
return false;
}
return true;
}
static int moduloOf(int num,int pow,int n)
{
int result=1;
while(pow>0)
{
if(pow%2==1)
{
result=(result*num)%n;
}
num=(num*num)%n;
pow=pow/2;
}
return result%n;
}
static void find_Prime_factors(Set<Integer> st, int n)
{
while (n % 2 == 0)
{
st.add(2);
n = n / 2;
}
for (int i = 3; i <= Math.sqrt(n); i = i + 2)
{
while (n % i == 0)
{
st.add(i);
n = n / i;
}
}
if (n > 2)
{
st.add(n);
}
}
static int choose_primitive(int n)
{
Set<Integer> s = new HashSet<Integer>();
if (isprime(n) == false)
{
return -1;
}
int phi = n - 1;
find_Prime_factors(s, phi);
for (int root = 2; root <= phi; root++)
{
boolean flag = false;
for (Integer a : s)
{
if (moduloOf(root, phi / (a), n) == 1)
{
flag = true;
break;
}
}
if (flag == false)
{
return root;
}
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try{
Socket s=new Socket("localhost",6767);
int prime;
System.out.println("Enter public prime number (P): ");
prime= scanner.nextInt();
while(!isprime(prime)){
System.out.println("You must enter a prime Number : ");
prime=scanner.nextInt();
}
int g =choose_primitive(prime);
System.out.println("Choosen primitive root of "+prime+" is :"+g);
System.out.println("User A enter your Secret key (a):");
int A = scanner.nextInt();
int x = moduloOf(g,A,prime);
System.out.println("User A your calculated public key (X) is:"+x);
System.out.println();
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF(String.valueOf(x));
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("Recieved Public key of User B is (Y) :"+str);
System.out.println();
System.out.println("Ka : " + moduloOf(Integer.parseInt(str),A,prime));
dout.flush();
dout.close();
s.close();
scanner.close();
}catch(Exception e){System.out.println(e);}
}
}