-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebserver.java
More file actions
283 lines (221 loc) · 8.43 KB
/
Webserver.java
File metadata and controls
283 lines (221 loc) · 8.43 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
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
// Java implementation for a client
// Save file as Client.java
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.*;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
import java.io.*;
import java.text.*;
import java.util.*;
import java.net.*;
import java.math.*;
import java.util.Scanner;
import javax.crypto.spec.SecretKeySpec;
import java.net.SocketTimeoutException;
import javax.swing.*;
import java.awt.*;
// Client class
public class Webserver
{
private static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCgFGVfrY4jQSoZQWWygZ83roKXWD4YeT2x2p41dGkPixe73rT2IW04glagN2vgoZoHuOPqa5and6kAmK2ujmCHu6D1auJhE2tXP+yLkpSiYMQucDKmCsWMnW9XlC5K7OSL77TXXcfvTvyZcjObEz6LIBRzs6+FqpFbUO9SJEfh6wIDAQAB";
private static long N1 = Long.parseLong(nonceGenerator());
//Necessities for AES Encryption
static Cipher cipher;
public static void main(String[] args) throws IOException {
BigInteger clientKey = new BigInteger("1");
String VoterID = "";
try
{
Scanner scn = new Scanner(System.in);
// getting localhost ip
InetAddress ip = InetAddress.getByName("localhost");
// establish the connection with server port 5056
Socket s = new Socket(ip, 5056);
// obtaining input and out streams
DataInputStream dis = new DataInputStream(s.getInputStream());
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
// the following loop performs the exchange of
// information between Webserver and S1 server
while (true)
{
// 2-Factor authentication
String res = Login.authenticate(dis,dos);
//Diffie Hellman Exchange
if(res.equals("rejected"))
{
MyFrame4 Frame4 = new MyFrame4("You have already voted. Contact Election Commissioner for cross checking."); // Frame displaying secret
Frame4.display();
break;
}
else
{
VoterID = res.substring(8);
System.out.println(VoterID);
clientKey = DHClient.fetchClientKey(dis, dos);
}
SecretKey SharedKey = getSecretKey(clientKey);
//PACKET 1 and 2
//Packet 1 generation
String packet1 = getmessagePacket1(VoterID, SharedKey);
//Packet 1 sent to S1
System.out.println("----------------------------Sending packet 1----------------------------------------");
dos.writeUTF(packet1);
//recieve the candidate table in the form of a hash
// Hash map Form :
// C0 : <candidate id>
// you can get the unique id of candidate using CandidateTable.get("C0")
ObjectInputStream mapdis = new ObjectInputStream(dis);
HashMap<String, String> CandidateTable = (HashMap) mapdis.readObject();
//Print Candidates
// printMenu(CandidateTable);
//casting the vote
String CID;
do{
MyFrame3 Frame3 = new MyFrame3(CandidateTable); // GUI displaying candidate list
Frame3.display();
String Vote = Frame3.getOutput();
if(CandidateTable.containsKey(Vote)){
CID = CandidateTable.get(Vote);
break;
}
}while(true);
// recieving packet 2
String received = dis.readUTF();
String packet2_temp = received;
System.out.println("\n----------------------------Received Packet2------------------------------");
//decrypts the packet 2
String packet2 = EncryptionDecryptionAES.decrypt(received, SharedKey);
String[] msgList = packet2.split("\\s+");
String UID = msgList[0];
long N1_mod = Long.parseLong(msgList[1]);
long N2 = Long.parseLong(msgList[2]);
String secret = msgList[3];
//Check if nonce 1 is correct
if ((N1_mod != N1-1)){
MyFrame4 Frame4 = new MyFrame4("Nonce Wrong. Fake packet. Connection closed. "); // Frame displaying secret
Frame4.display();
break;
}
//PACKET 3
// sending packet 3
System.out.println("----------------------------Sending Packet3----------------------------------------");
String tosend = getmessagePacket3(CID, secret, UID, N2, SharedKey);
dos.writeUTF(tosend);
//polling for response
s.setSoTimeout(5000); //polling for 5 secs for response
String testStr = "Initial";
do{
try{
testStr = dis.readUTF();
if (testStr == packet2_temp){
System.out.println("Failed to send packet2, RESENDING.");
dos.writeUTF(tosend); //resending packet 3
}
}
catch (Exception e){
System.out.println("Packet3 successfully sent.");
break;
}
}while(true);
s.setSoTimeout(0);
MyFrame4 Frame4 = new MyFrame4("The secret key is : " + secret); // Frame displaying secret
Frame4.display();
break;
}
// closing resources
scn.close();
dis.close();
dos.close();
}catch(Exception e){
e.printStackTrace();
}
}
//External Functions .....
public static String getmessagePacket3(String CID, String secret, String UID, long N2, SecretKey SharedKey) throws SignatureException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException{
String Msg = "";
String Msgpart = "";
try{
Msg = CID + " " + secret;
Msgpart = Base64.getEncoder().encodeToString(rsa.encrypt(Msg, publicKey));
Msg = Msgpart+ " " + UID;
N2 = N2 - 1;
Msg = EncryptionDecryptionAES.encrypt(Msg + " " + Base64.getEncoder().encodeToString(digSignatureRSA(Msg)) + " " + Long.toString(N2), SharedKey);
}catch(Exception e){
e.printStackTrace();
}
return Msg;
}
public static PublicKey getPublicKeyRSA(String base64PublicKey){
PublicKey publicKey = null;
try{
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes()));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
publicKey = keyFactory.generatePublic(keySpec);
return publicKey;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}
return publicKey;
}
public static byte[] digSignatureRSA(String Msg) throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException, SignatureException{
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
//Initializing the key pair generator
keyPairGen.initialize(2048);
//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();
//Getting the private key from the key pair
PrivateKey privKey = pair.getPrivate();
//Creating a Signature object
Signature sign = Signature.getInstance("SHA256withDSA");
//Initialize the signature
sign.initSign(privKey);
byte[] bytes = Msg.getBytes();
//Adding data to the signature
sign.update(bytes);
//Calculating the signature
byte[] signature = sign.sign();
return signature;
}
public static String getmessagePacket1(String VoterID, SecretKey SharedKey) throws SignatureException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException{
String packet = "";
try{
String msg = "I_want_to_vote";
packet = EncryptionDecryptionAES.encrypt(msg + " " + VoterID + " " + Long.toString(N1), SharedKey);
}catch(Exception e){
e.printStackTrace();
}
return packet;
}
public static SecretKey getSecretKey(BigInteger clientKey){
String key = clientKey.toString();
int length = key.length();
int i = 0;
String keyStr = "012345678901234567890123456789XY";
for(i= length; i < keyStr.length();i++){
char x = keyStr.charAt(i);
key = key + String.valueOf(x);
}
byte[] decodedKey = Base64.getMimeDecoder().decode(key);
SecretKey secretKey = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
return secretKey;
}
public static String nonceGenerator(){
SecureRandom secureRandom = new SecureRandom();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < 15; i++){
stringBuilder.append(secureRandom.nextInt(10));
}
String randomNumber = stringBuilder.toString();
return randomNumber;
}
}