· 8 years ago · May 23, 2017, 09:42 PM
1package seguranca02;
2
3import java.io.BufferedInputStream;
4import java.io.BufferedOutputStream;
5import java.io.BufferedReader;
6import java.io.BufferedWriter;
7import java.io.File;
8import java.io.FileInputStream;
9import java.io.FileNotFoundException;
10import java.io.FileOutputStream;
11import java.io.FileReader;
12import java.io.FileWriter;
13import java.io.IOException;
14import java.io.ObjectInputStream;
15import java.io.ObjectOutputStream;
16import java.io.PrintWriter;
17import java.io.UnsupportedEncodingException;
18import java.math.BigInteger;
19import java.net.Socket;
20import java.net.UnknownHostException;
21import java.nio.file.Files;
22import java.nio.file.Path;
23import java.nio.file.Paths;
24import java.nio.file.StandardOpenOption;
25import java.security.GeneralSecurityException;
26import java.security.InvalidAlgorithmParameterException;
27import java.security.InvalidKeyException;
28import java.security.Key;
29import java.security.KeyStore;
30import java.security.NoSuchAlgorithmException;
31import java.security.SecureRandom;
32import java.security.cert.Certificate;
33import java.security.spec.InvalidKeySpecException;
34import java.text.Format;
35import java.text.SimpleDateFormat;
36import java.util.ArrayList;
37import java.util.Arrays;
38import java.util.Date;
39import java.util.List;
40import java.util.Scanner;
41
42import javax.crypto.BadPaddingException;
43import javax.crypto.Cipher;
44import javax.crypto.CipherInputStream;
45import javax.crypto.CipherOutputStream;
46import javax.crypto.IllegalBlockSizeException;
47import javax.crypto.KeyGenerator;
48import javax.crypto.Mac;
49import javax.crypto.NoSuchPaddingException;
50import javax.crypto.SecretKey;
51import javax.crypto.SecretKeyFactory;
52import javax.crypto.spec.IvParameterSpec;
53import javax.crypto.spec.PBEKeySpec;
54import javax.crypto.spec.PBEParameterSpec;
55import javax.crypto.spec.SecretKeySpec;
56import javax.xml.bind.DatatypeConverter;
57
58import sun.misc.BASE64Decoder;
59import sun.misc.BASE64Encoder;
60
61import java.util.Collections;
62
63
64public class MyGitServerHandler {
65 private ObjectOutputStream outStream;
66 private ObjectInputStream inStream;
67 private String comando;
68 private static String passwordDoserver;
69 private static String passServer;
70 private static final String FILENAME = "Repositorio/utilizadores.txt";
71
72 private static final byte[] SALT = {
73 (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
74 (byte) 0xde, (byte) 0x33, (byte) 0x10, (byte) 0x12,
75 };
76
77 private static final byte[] ivBytes = {0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,
78 0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20};
79
80
81
82
83 public MyGitServerHandler(Socket serverSocket,String passwordDoserver, String passServer) throws IOException, ClassNotFoundException {
84 this.inStream=new ObjectInputStream(serverSocket.getInputStream());
85 this.outStream= new ObjectOutputStream(serverSocket.getOutputStream());
86 this.passwordDoserver=passwordDoserver;
87 this.passServer=passServer;
88
89 }
90
91
92 public String getCommand() {
93 return comando;
94 }
95
96 public void setCommand(String comando) {
97 this.comando=comando;
98 }
99
100
101 public ObjectOutputStream getOutputStream() {
102 return outStream;
103 }
104
105 public ObjectInputStream getInputStream() {
106 return inStream;
107 }
108 public void closeConnections() throws UnknownHostException, IOException{
109
110 getOutputStream().close();
111 getInputStream().close();
112 }
113
114 public String ReceberMensagem(){
115 try{
116 setCommand((String)getInputStream().readObject());
117 System.out.println("Mensagem recebida do cliente e "+ getCommand());
118 return getCommand();
119 }
120 catch (Exception e)
121 {
122 e.printStackTrace();
123 return null;
124 }
125 }
126
127
128 public void ReceiveToolsAndPull(){
129 try{
130
131 String user =(String) this.getInputStream().readObject();
132
133 String name =(String) this.getInputStream().readObject();
134 System.out.println(name);
135
136 long lastModified= (long) this.getInputStream().readObject();
137
138 File fichServidor = new File("Repositorio/"+name.split("\\.(?=[^\\.]+$)")[0]+".cif");
139 File fichServidor2 = new File("Repositorio/"+name.split("\\.(?=[^\\.]+$)")[0]+".sig");
140 byte [] chaveDecifradaPublica = DecifrarChavePublica(user,name);
141
142 this.getOutputStream().writeBoolean(fichServidor.exists());
143 if (fichServidor.exists()){
144
145
146
147 this.getOutputStream().writeObject(chaveDecifradaPublica);
148 this.getOutputStream().flush();
149
150
151 //verifica se é um ficheiro
152
153 this.getOutputStream().writeBoolean(fichServidor.isFile());
154 if(fichServidor.isFile()){
155 //verifica se o fich do servidor � mais recente
156 getOutputStream().writeBoolean(lastModified < fichServidor.lastModified());
157
158 if (lastModified < fichServidor.lastModified()){
159 //envia o last modified do servidor
160
161 this.getOutputStream().writeObject(fichServidor.lastModified());
162 getOutputStream().flush();
163
164 //envia ficheiro para o servidor
165
166
167 //Verifica_Recebe(user+"/"+name, lastModified, fichServidor, fichServidor.lastModified());
168 EnviarFicheiro(fichServidor, false);
169 EnviarFicheiro(fichServidor2, false);
170 }else{
171 System.out.println("O ficheiro local � mais recente que o do servidor");
172 }
173 }else{
174
175 this.getOutputStream().writeObject(listaNomesFicheiros(fichServidor));
176 this.getOutputStream().flush();
177
178
179// EnviarDiretoria(fichServidor);
180 }
181
182 }else{
183 System.out.println("O ficheiro nao existe no servidor");
184
185 }
186
187 }
188 catch (Exception e)
189 {
190 e.printStackTrace();
191 }
192 }
193// public void ReceiveToolsAndPull(){
194//
195// try{
196//
197// String user =(String) this.getInputStream().readObject();
198//
199// String name =(String) this.getInputStream().readObject();
200// System.out.println(name);
201//
202// long lastModified= (long) this.getInputStream().readObject();
203//
204//
205// File fichServidor0 = new File("Repositorio/"+name);
206// File fichServidor = new File("Repositorio/"+name.split("\\.(?=[^\\.]+$)")[0]+".cif");
207// System.out.println("Nome do fich--->"+fichServidor0.getPath());
208//
209// this.getOutputStream().writeBoolean(fichServidor0.exists());
210// this.getOutputStream().flush();
211//
212// System.out.println(fichServidor0.isDirectory());
213//
214// this.getOutputStream().writeObject("oi");
215// this.getOutputStream().flush();
216//
217// if (fichServidor.exists()){
218// //verifica se é um ficheiro
219// System.out.println("e ficheiro------>"+fichServidor.isFile());
220// this.getOutputStream().writeBoolean(fichServidor.isFile());
221// if(fichServidor.isFile()){
222// File fichServidor2 = new File("Repositorio/"+name.split("\\.(?=[^\\.]+$)")[0]+".sig");
223//
224// byte [] chaveDecifradaPublica = DecifrarChavePublica(name.split("\\.(?=[^\\.]+$)")[0]);
225// this.getOutputStream().writeObject(chaveDecifradaPublica);
226// this.getOutputStream().flush();
227//
228// //verifica se o fich do servidor e mais recente
229// getOutputStream().writeBoolean(lastModified < fichServidor.lastModified());
230//
231// if (lastModified < fichServidor.lastModified()){
232// //envia o last modified do servidor
233//
234// this.getOutputStream().writeObject(fichServidor.lastModified());
235// getOutputStream().flush();
236//
237// //envia ficheiro para o servidor
238//
239//
240// //Verifica_Recebe(user+"/"+name, lastModified, fichServidor, fichServidor.lastModified());
241// EnviarFicheiro(fichServidor, false);
242// EnviarFicheiro(fichServidor2, false);
243// }else{
244// System.out.println("O ficheiro local e mais recente que o do servidor");
245// }
246// }else{
247//
248// this.getOutputStream().writeObject(listaNomesFicheiros(fichServidor0));
249// this.getOutputStream().flush();
250//
251//
252// EnviarDiretoria(user, fichServidor0);
253// }
254//
255// }else{
256// System.out.println("O ficheiro nao existe no servidor");
257//
258// }
259//
260// }
261// catch (Exception e)
262// {
263// e.printStackTrace();
264// }
265//
266// }
267// }
268
269
270
271 public void ReceiveToolsAndPush(){
272 try{
273 ///ferramentas
274 String user =(String) this.getInputStream().readObject();
275
276 String name =(String) this.getInputStream().readObject();
277
278 boolean isFile = (boolean) this.getInputStream().readObject();
279
280 long lastModified= (long) this.getInputStream().readObject();
281 //ferramentas fim
282 System.out.println(name.split("\\.(?=[^\\.]+$)")[0]);
283 File fichServidor0 = new File("Repositorio"+File.separator+user+File.separator+name.split("\\.(?=[^\\.]+$)")[0]);
284 File fichServidor = new File("Repositorio"+File.separator+user+File.separator+name.split("\\.(?=[^\\.]+$)")[0]+".sig");
285 File fichServidor1 = new File("Repositorio"+File.separator+user+File.separator+name.split("\\.(?=[^\\.]+$)")[0]+".txt.key.server");
286 File fichServidor2 = new File("Repositorio"+File.separator+user+File.separator+name.split("\\.(?=[^\\.]+$)")[0]+".cif");
287
288
289 if (fichServidor.exists()){
290 System.out.println("Aqui miudo1");
291 if (isFile){
292 //tratar ficheiro parte 1
293 System.out.println("tratar ficheiro parte 1");
294 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".sig", lastModified, fichServidor, fichServidor.lastModified());
295 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".key", lastModified, fichServidor1, fichServidor1.lastModified());
296 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".cif", lastModified, fichServidor2, fichServidor2.lastModified());
297 CifrarChaveComChavePublica(user,name);
298 File fichKEY= new File(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".key");
299 fichKEY.delete();
300 }else{
301 //se � mais recente
302 getOutputStream().writeBoolean(lastModified > fichServidor.lastModified());
303 getOutputStream().flush();
304 List<String> listaNomes= null;
305
306 listaNomes = (List<String>) getInputStream().readObject();
307
308 TreatDirectory(name, lastModified, fichServidor0, listaNomes, user);
309 }
310
311 }else{
312 System.out.println("Aqui miudo2");
313 if (isFile){
314 //isto nao estava no trabalho e se nao estiver da Erro
315 System.out.println("tratar ficheiro parte 1");
316 File pastaUser = new File("Repositorio/"+user);
317 if (!(pastaUser.exists()))
318 pastaUser.mkdirs();
319 //O codigo que falta � at� aqui
320 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".sig", lastModified, fichServidor, Long.MIN_VALUE );
321 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".key", lastModified, fichServidor1, Long.MIN_VALUE );
322 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".cif", lastModified, fichServidor2, Long.MIN_VALUE );
323 CifrarChaveComChavePublica(user,name);
324 File fichKEY= new File(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+".key");
325 fichKEY.delete();
326
327 }else{
328 getOutputStream().writeBoolean(lastModified > fichServidor.lastModified());
329 getOutputStream().flush();
330 //se � mais recente
331 List<String> listaNomes =(List<String>) getInputStream().readObject();
332 TreatDirectory(name, lastModified, fichServidor0, listaNomes, user);
333 }
334 }
335 }
336
337 catch (Exception e)
338 {
339 e.printStackTrace();
340 }
341
342 }
343
344
345 public void Verifica_Recebe(String nome_ficheiro, long fichLastModified, File fichServidor, long fichServerLastMod) throws Exception{
346 if (fichServidor.exists() && fichLastModified > fichServerLastMod ){
347 //tratar ficheiro parte 2
348
349 getOutputStream().writeBoolean(true);
350 getOutputStream().flush();
351 String[] nomePartido = nome_ficheiro.split("\\.(?=[^\\.]+$)");
352
353
354 Date d = new Date(fichServidor.lastModified());
355 Format formatter = new SimpleDateFormat("dd-MM-yyyy_HH:mm:ss");
356 File newVersion;
357
358 if (nomePartido.length<2){
359 newVersion = new File("Repositorio/"+nomePartido[0]+"versao_"+formatter.format(d));
360 }else{
361 newVersion = new File("Repositorio/"+nomePartido[0]+"versao_"+formatter.format(d)+"."+fichServidor.getName().split("\\.(?=[^\\.]+$)")[1]);
362 }
363
364 if (newVersion.exists())
365 throw new java.io.IOException("file exists");
366 // Rename file (or directory)
367 fichServidor.renameTo(newVersion);
368 ReceberFicheiro(nome_ficheiro, fichLastModified);
369 System.out.println("O ficheiro "+nome_ficheiro+" foi enviado para o servidor");
370 //fazer aqui um write
371 getOutputStream().writeObject("O ficheiro "+fichServidor.getName()+" foi enviado para o servidor");
372// getOutputStream().flush();
373 }
374 else if(!fichServidor.exists()){
375 System.out.println("tratar ficheiro parte 2-");
376 //tratar ficheiro parte 2
377 getOutputStream().writeBoolean(true);
378 //getOutputStream().flush();
379 ReceberFicheiro(nome_ficheiro, fichLastModified );
380 System.out.println("O ficheiro "+nome_ficheiro+" foi enviado para o servidor");
381 //fazer aqui um write
382 getOutputStream().writeObject("O ficheiro "+fichServidor.getName()+" foi enviado para o servidor");
383 getOutputStream().flush();
384 }else{
385
386 //tratar ficheiro parte 2
387 getOutputStream().writeBoolean(false);
388 //getOutputStream().flush();
389 System.out.println("O servidor ja tem o ficheiro mais recente");
390 }
391 }
392
393 public void TreatDirectory(String name, long dirLastModified, File dirServidor, List<String> listaNomes, String user){
394 try{
395 //se diretoria existe faz below
396 if (dirServidor.exists()){
397 // this.getOutputStream().writeBoolean(false);
398 List<String> listaServidor = new ArrayList<String>();
399 for(File i : dirServidor.listFiles()){
400 System.out.println("Nome do ficheiro--------->>"+i.getName());
401 listaServidor.add(i.getName());
402 }
403
404 RemoverFicheiros(listaServidor,listaNomes, name, user);
405
406
407 for(String ficheiroNaDir : listaNomes){
408 File fichServidor = new File("Repositorio"+File.separator+user+File.separator+dirServidor.getName()+File.separator+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".sig");
409 File fichServidor1 = new File("Repositorio"+File.separator+user+File.separator+dirServidor.getName()+File.separator+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".txt.key.server");
410 File fichServidor2 = new File("Repositorio"+File.separator+user+File.separator+dirServidor.getName()+File.separator+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".cif");
411
412 Long lastModified = (Long) getInputStream().readObject();
413 if(lastModified.longValue()>fichServidor.lastModified()){
414 getOutputStream().writeBoolean(true);
415 getOutputStream().flush();
416 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".sig", lastModified, fichServidor, fichServidor.lastModified());
417 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".key", lastModified, fichServidor1, fichServidor1.lastModified());
418 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".cif", lastModified, fichServidor2, fichServidor2.lastModified());
419 CifrarChaveComChavePublica(name.split("\\.(?=[^\\.]+$)")[0], ficheiroNaDir);
420 File fichKEY= new File(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".key");
421 fichKEY.delete();
422 }else{
423 getOutputStream().writeBoolean(false);
424 getOutputStream().flush();
425 System.out.println("O ficheiro do servidor e mais recente");
426 }
427
428 }
429 this.getOutputStream().writeObject("O ficheiro "+dirServidor.getName()+" foi enviado para o servidor");
430 }else if(!dirServidor.exists()){
431 dirServidor.mkdirs();
432 System.out.println("Este e o dir--->"+dirServidor.getName());
433 // this.getOutputStream().writeBoolean(true);
434 // this.getOutputStream().writeObject("O ficheiro "+dirServidor.getName()+" foi criado no servidor");
435 PrintWriter writer = new PrintWriter("Repositorio/"+user+"/"+dirServidor.getName()+"/shareFilesUsers.txt", "UTF-8");
436 writer.println(user);
437 writer.close();
438
439 for(String ficheiroNaDir : listaNomes){
440 File file= new File("Repositorio/"+dirServidor.getName()+"/"+ficheiroNaDir);
441 File fichServidor = new File("Repositorio"+File.separator+user+File.separator+dirServidor.getName()+File.separator+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".sig");
442 File fichServidor1 = new File("Repositorio"+File.separator+user+File.separator+dirServidor.getName()+File.separator+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".txt.key.server");
443 File fichServidor2 = new File("Repositorio"+File.separator+user+File.separator+dirServidor.getName()+File.separator+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".cif");
444
445 long lastModified = (long) getInputStream().readObject();
446
447 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".sig", lastModified, fichServidor, fichServidor.lastModified());
448 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".key", lastModified, fichServidor1, fichServidor1.lastModified());
449 Verifica_Recebe(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".cif", lastModified, fichServidor2, fichServidor2.lastModified());
450 CifrarChaveComChavePublica(user,name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir);
451 File fichKEY= new File(user+"/"+name.split("\\.(?=[^\\.]+$)")[0]+"/"+ficheiroNaDir.split("\\.(?=[^\\.]+$)")[0]+".key");
452 fichKEY.delete();
453 }
454 }else{
455 // this.getOutputStream().writeBoolean(true);
456 // this.getOutputStream().writeObject("Ficheiro do servidor � mais recente que o local");
457 System.out.println("Ficheiro do servidor � mais recente que o local");
458 }
459
460 }
461 catch (Exception e)
462 {
463 e.printStackTrace();
464 }
465
466 }
467
468
469 public boolean Authentication(String PasswordDoServidor) throws ClassNotFoundException, IOException{
470 try {
471 decriptado();
472 File file = new File("Repositorio/utilizadores.txt");
473 FileReader fr = new FileReader(file);
474 BufferedReader br = new BufferedReader(fr);
475 String sCurrentLine;
476 String name =(String) getInputStream().readObject();
477 String nounce = SendNounce();
478 getOutputStream().writeObject(nounce);
479 getOutputStream().flush();
480 String passwordfinal = (String) getInputStream().readObject();
481 boolean flag=true;
482 boolean response=true;
483 while ((sCurrentLine = br.readLine()) != null) {
484 if (sCurrentLine.split(":")[0].equals(name)){
485 flag=false;
486 System.out.println(passwordfinal);
487 System.out.println(DoMACTest(nounce+sCurrentLine.split(":")[1]));
488
489 if (DoMACTest(nounce+sCurrentLine.split(":")[1]).equals(passwordfinal)){
490 getOutputStream().writeBoolean(false);
491 getOutputStream().writeObject("A password esta correcta");
492 getOutputStream().flush();
493 getOutputStream().writeBoolean(true);
494 getOutputStream().flush();
495 br.close();
496 fr.close();
497 response=true;
498 break;
499 }else{
500 getOutputStream().writeBoolean(false);
501 getOutputStream().writeObject("A esta password incorrecta,desligando este cliente");
502 getOutputStream().flush();
503 getOutputStream().writeBoolean(false);
504 getOutputStream().flush();
505 br.close();
506 fr.close();
507 response=false;
508 break;
509 }
510
511 }
512 }
513 br.close();
514 fr.close();
515 if (flag){
516 System.out.println("devia entrar aqui");
517 getOutputStream().writeBoolean(true);
518 getOutputStream().flush();
519 String password = (String) getInputStream().readObject(); // so manda em claro senao existir
520 System.out.println("devia entrar aqui2-----"+password);
521 if(getInputStream().readBoolean()){
522
523 System.out.println("devia entrar aqui3");
524 CreateUser("Repositorio/utilizadores.txt", name, password);
525 getOutputStream().writeObject("O utilizador "+name+" foi criado");
526 getOutputStream().flush();
527 System.out.println("Passdoserver---"+PasswordDoServidor);
528 DoMAC(PasswordDoServidor);
529 }else{
530 getOutputStream().writeObject("As passwords nao sao iguais");
531 getOutputStream().flush();
532 response=false;
533
534
535 }
536 }
537
538 encriptado();
539
540
541
542
543
544
545 return response;
546 } catch (Exception e) {
547 e.printStackTrace();
548 return false;
549 }
550
551
552 }
553
554 private void CreateUser(String writeFile, String name, String password) {
555 try {
556
557 Files.write(Paths.get(writeFile), ("\n"+name+":"+password).getBytes(), StandardOpenOption.APPEND);
558
559 } catch (Exception e) {
560 e.printStackTrace();
561 }
562 }
563
564 public void Verifica_Envia(String nome_ficheiro, long fichLastModified) throws Exception{
565 File fichServidor = new File("Repositorio/"+nome_ficheiro);
566 long fichServidorLastModified = fichServidor.lastModified();
567 if (fichServidor.exists() && fichLastModified < fichServidorLastModified ){
568 getOutputStream().writeObject((fichLastModified < fichServidorLastModified));
569 getOutputStream().writeObject(fichServidorLastModified);
570 getOutputStream().flush();
571 EnviarFicheiro(fichServidor, false);
572 //ReceberFicheiro(nome_ficheiro, fichLastModified);
573 System.out.println("o ficheiro "+nome_ficheiro+" foi enviado para o cliente");
574 }
575 else if(!fichServidor.exists()){
576 getOutputStream().writeObject(true);
577 getOutputStream().flush();
578 ReceberFicheiro(nome_ficheiro, fichLastModified );
579 }else{
580 getOutputStream().writeObject((fichLastModified > fichServidor.lastModified()));
581 getOutputStream().flush();
582 System.out.println("O servidor ja tem o ficheiro mais recente");
583 }
584 }
585
586
587 public void ReceberFicheiro (String nome_ficheiro, long fichLastModified) throws Exception{
588 System.out.println("ele existe---->"+"Repositorio/"+nome_ficheiro);
589 FileOutputStream fileOutput = new FileOutputStream("Repositorio/"+nome_ficheiro);
590 BufferedOutputStream fileBuffer = new BufferedOutputStream(fileOutput);
591 int size = getInputStream().readInt();
592 System.out.println("ele existe FIM---->"+"Repositorio/"+nome_ficheiro);
593 int n;
594 int lidos=0;
595 byte[] buffer = new byte[1024];
596 while(lidos < (int) size){
597 n= getInputStream().read(buffer,0,size-lidos<1024? size-lidos:1024);
598 fileOutput.write(buffer,0,n);
599 fileOutput.flush();
600 lidos+=n;
601 }
602 new File("Repositorio/"+nome_ficheiro).setLastModified(fichLastModified);
603 fileBuffer.close();
604// fileOutput.flush();
605 fileOutput.close();
606
607 }
608
609 public void RemoverFicheiros(List<String> listaServidor,List<String> listaNomes, String name, String user) throws IOException{
610
611 List<String> listaParaRemover = new ArrayList<String>();
612
613 for(String j : listaServidor){
614
615 if (listaNomes!=null && listaNomes.indexOf(j)==-1 && !(j.equals("shareFilesUsers.txt")) && j.indexOf("versao_")==-1){
616 listaParaRemover.add(j);
617 }
618 }
619
620
621 for (String aRemover : listaParaRemover){
622 File fichParaRemover = new File("Repositorio/"+user+"/"+name+"/"+aRemover);
623 String[] nomePartido = fichParaRemover.getName().split("\\.(?=[^\\.]+$)");
624 Date d = new Date(fichParaRemover.lastModified());
625 Format formatter = new SimpleDateFormat("dd-MM-yyyy_HH:mm:ss");
626 File newVersion = new File("Repositorio/"+user+"/"+name+"/"+nomePartido[0]+"versao_"+formatter.format(d)+"."+nomePartido[1]);
627 if (newVersion.exists())
628 throw new java.io.IOException("file exists");
629 // Rename file (or directory)
630 fichParaRemover.renameTo(newVersion);
631 }
632 }
633
634 public void EnviarFicheiro(File file, boolean isDirectory) throws IOException {
635
636 if (isDirectory){
637 this.getOutputStream().writeObject(new Long(file.lastModified()));
638
639 getOutputStream().flush();
640
641 if(!getInputStream().readBoolean()){
642 System.out.println("O servidor ja tem a vers�o mais recente!!");
643 return;
644 }
645 }
646
647 getOutputStream().writeInt((int)file.length());
648
649 FileInputStream fileInputStream = new FileInputStream(file);
650 BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
651 int n;
652 byte[] buffer = new byte[1024];
653 while((n=bufferedInputStream.read(buffer, 0, 1024))!=-1){
654 getOutputStream().write(buffer,0,n);
655 getOutputStream().flush();
656 }
657 //System.out.println("resultado do servidor: "+String.valueOf(inputStream.readObject())); //mensagem do servidor
658 bufferedInputStream.close();
659 fileInputStream.close();
660 }
661
662 public void ShareRep() throws ClassNotFoundException, IOException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException{
663
664 String nameDir = (String) this.getInputStream().readObject();
665 String owner = (String) this.getInputStream().readObject();
666 String userToAdd = (String) this.getInputStream().readObject();
667 File file = new File("Repositorio/"+owner+"/"+nameDir+"/shareFilesUsers.txt"); // creates the file
668 DoMACforShare(passwordDoserver,owner,nameDir);
669// VerificaMACForShare(passwordDoserver,owner,nameDir);
670
671
672 decriptado();
673 if (CheckUser(userToAdd, new File("Repositorio/utilizadores.txt"))){
674 if(CheckOwner(owner, file)){
675 FileWriter writer = new FileWriter(file, true); // Writes the content to the file
676 if (!IsInFile(file, userToAdd)){
677 writer.append("\n"+userToAdd);
678 writer.flush();
679 }else{
680 System.out.println("O utilizador a que pretende fazer a partilha do reposit�rio, j� tem permiss�o para aceder a pasta");
681 }
682 writer.close();
683 }else{
684 System.out.println("O utilizador n�o tem permiss�o para fazer share deste reposit�rio");
685 }
686 }else{
687 System.out.println("Erro: O utilizador "+userToAdd+" n�o existe");
688 }
689 encriptado();
690 DoMACforShare(passwordDoserver,owner,nameDir);
691
692
693 }
694
695 public void RemovePermisson() throws ClassNotFoundException, IOException, InvalidKeyException, NoSuchAlgorithmException{
696
697 String nameDir = (String) this.getInputStream().readObject();
698 String owner = (String) this.getInputStream().readObject();
699 String userToRemove = (String) this.getInputStream().readObject();
700 File file = new File("Repositorio/"+owner+"/"+nameDir+"/shareFilesUsers.txt"); // creates the file
701
702 if (CheckUser(userToRemove, file)){
703
704 if(CheckOwner(owner, file)){
705 if (IsInFile(file, userToRemove)){
706 RemoverLinha(userToRemove,file);
707
708 }else{
709 System.out.println("O utilizador a que pretende fazer a partilha do reposit�rio, j� tem permiss�o para aceder a pasta");
710 }
711 }else{
712 System.out.println("O utilizador n�o tem permiss�o para fazer share deste reposit�rio");
713 }
714 }
715 DoMACforShare(passwordDoserver,owner,nameDir);
716
717 }
718
719 public boolean IsInFile(File file,String string) {
720 try {
721 Scanner scanner = new Scanner(file);
722
723 while (scanner.hasNextLine()) {
724 String line = scanner.nextLine();
725
726 if(line.equals(string)) {
727 scanner.close();
728 return true;
729 }
730 }
731 scanner.close();
732 return false;
733
734 } catch(FileNotFoundException e) {
735 //handle this
736 }
737 return false;
738 }
739
740
741 public boolean CheckOwner(String owner, File file) throws IOException{
742 BufferedReader test = new BufferedReader(new FileReader(file));
743 String text = test.readLine();
744 if (text.equals(owner)){
745 test.close();
746 return true;
747 }
748 test.close();
749 return false;
750 }
751
752 public boolean CheckUser(String user, File file) throws IOException{
753 try{
754 FileReader fr = new FileReader(file);
755 BufferedReader br = new BufferedReader(fr);
756 String sCurrentLine;
757 while ((sCurrentLine = br.readLine()) != null) {
758 //System.out.println(sCurrentLine+ "scurrentline");
759 if (sCurrentLine.split(":")[0].equals(user)){
760 return true;
761 }
762 }
763 br.close();
764 fr.close();
765 return false;
766 } catch (Exception e) {
767 e.printStackTrace();
768
769 return false;
770 }
771
772 }
773
774 public boolean RemoverLinha(String username,File filename) throws IOException {
775 BufferedReader reader = new BufferedReader(new FileReader(filename));
776 File tempFile = new File("shareFilesUsers.txt");
777 BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
778
779 String lineToRemove = username;
780 String currentLine;
781
782 while((currentLine = reader.readLine()) != null) {
783 // trim newline when comparing with lineToRemove
784 String trimmedLine = currentLine.trim();
785 if(trimmedLine.equals(lineToRemove)) continue;
786 writer.write(currentLine + System.getProperty("line.separator"));
787 }
788 writer.close();
789 reader.close();
790 boolean successful = tempFile.renameTo(filename);
791 return successful;
792 }
793
794 public List<String> listaNomesFicheiros(File file) throws IOException{
795 List<String> listaNomes = new ArrayList<String>();
796 for (File i : file.listFiles()){
797 if (!i.getName().equals(".DS_Store") && !i.getName().equals("shareFilesUsers.txt"))
798 listaNomes.add(i.getName());
799 }
800 return listaNomes;
801 }
802
803 public void EnviarDiretoria(String user, File dir) throws Exception {
804 File[] listaNomes = dir.listFiles();
805 for (File ficheiro : listaNomes) {
806 System.out.println(ficheiro.getName().split("\\.(?=[^\\.]+$)")[0]);
807 File fichServidor2 = new File("Repositorio/"+ficheiro.getName().split("\\.(?=[^\\.]+$)")[0]+".sig");
808 File fichServidor = new File("Repositorio/"+ficheiro.getName().split("\\.(?=[^\\.]+$)")[0]+".cif");
809 byte [] chaveDecifradaPublica=null;
810 if (!ficheiro.getName().equals("shareFilesUsers.txt"))
811 chaveDecifradaPublica = DecifrarChavePublica(user,user+"/"+dir.getName()+"/"+ficheiro.getName().split("\\.(?=[^\\.]+$)")[0]);
812
813 System.out.println("ele entra");
814 if (!ficheiro.getName().equals(".DS_Store") && !ficheiro.getName().equals("shareFilesUsers.txt")){
815 System.out.println("ele entra2");
816 //falta por isto do outro lado pa receber
817
818 this.getOutputStream().writeObject(chaveDecifradaPublica);
819
820 System.out.println("ele entra3");
821 EnviarFicheiro(fichServidor, true);
822 EnviarFicheiro(fichServidor2, false);
823 }
824 }
825 }
826
827 public String SendNounce() throws NoSuchAlgorithmException, IOException {
828 SecureRandom random = new SecureRandom();
829 String nounce = new BigInteger(256,random).toString();
830 return nounce;
831 }
832
833 public String DoMACTest(String passwd) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
834 Mac mac = Mac.getInstance("HmacSHA256");
835 byte [] pass = passwd.getBytes();
836 SecretKey key = new SecretKeySpec(pass, "HmacSHA256");
837 mac.init(key);
838 return DatatypeConverter.printHexBinary(mac.doFinal());
839 }
840
841 public static void DoMAC(String passwd) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
842 try (BufferedWriter bw = new BufferedWriter(new FileWriter("Repositorio/MAC"))) {
843 Mac mac = Mac.getInstance("HmacSHA256");
844 byte [] pass = passwd.getBytes();
845 Path path = Paths.get("Repositorio/utilizadores.txt");
846 byte[] data = Files.readAllBytes(path);
847 SecretKey key = new SecretKeySpec(pass, "HmacSHA256");
848 mac.init(key);
849 mac.update(data);
850 bw.write(DatatypeConverter.printHexBinary(mac.doFinal()));
851 bw.close();
852
853 } catch (IOException e) {
854 e.printStackTrace();
855
856 }
857 }
858
859 public static void DoMACforShare(String passwd,String owner,String namedir) throws NoSuchAlgorithmException, InvalidKeyException, IOException {
860 try (BufferedWriter bw = new BufferedWriter(new FileWriter("Repositorio/"+owner+"/"+namedir+"/ShareMACFile"))) {
861 Mac mac = Mac.getInstance("HmacSHA256");
862 byte [] pass = passwd.getBytes();
863 byte[] bFile = Files.readAllBytes(Paths.get("Repositorio/"+owner+"/"+namedir+"/shareFilesUsers.txt"));
864 SecretKey key = new SecretKeySpec(pass, "HmacSHA256");
865 mac.init(key);
866 mac.update(bFile);
867 bw.write(DatatypeConverter.printHexBinary(mac.doFinal()));
868 bw.close();
869 } catch (IOException e) {
870 e.printStackTrace();
871
872 }
873 }
874
875 public static void VerificaMACForShare(String passwd,String owner,String namedir) throws NoSuchAlgorithmException, IOException, InvalidKeyException {
876 Mac mac = Mac.getInstance("HmacSHA256");
877 byte[] pass = passwd.getBytes();
878 SecretKey key = new SecretKeySpec(pass, "HmacSHA256");
879 mac.init(key);
880 FileReader fr = new FileReader("Repositorio/"+owner+"/"+namedir+"/ShareMACFile");
881 BufferedReader br = new BufferedReader(fr);
882 String s;
883 while((s = br.readLine()) != null) {
884 if(s.equals(DatatypeConverter.printHexBinary(mac.doFinal()))) {
885
886 System.out.println("Sucesso");
887 }
888 else {
889 System.out.println("Ficheiro MAC corrompido, desligando o servidor ");
890 System.exit(-1);
891 }
892 }
893 fr.close();
894 }
895
896
897 private static byte[] encriptado() throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
898 PBEKeySpec keySpec = new PBEKeySpec(passServer.toCharArray());
899 SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
900
901 SecretKey key = kf.generateSecret(keySpec);
902 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
903 PBEParameterSpec spec = new PBEParameterSpec(SALT, 20, ivSpec);
904
905 Path path = Paths.get("Repositorio/utilizadores.txt");
906 byte[] data = Files.readAllBytes(path);
907
908 Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
909 c.init(Cipher.ENCRYPT_MODE, key, spec);
910 FileOutputStream fos = new FileOutputStream("Repositorio/utilizadores.txt");
911 fos.write(c.doFinal(data));
912 fos.close();
913
914 return c.doFinal();
915 }
916
917 private static byte[] decriptado() throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, IOException {
918
919 PBEKeySpec keySpec = new PBEKeySpec(passServer.toCharArray());
920 SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
921 SecretKey key = kf.generateSecret(keySpec);
922 IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
923 PBEParameterSpec spec = new PBEParameterSpec(SALT, 20, ivSpec);
924
925
926 Path path = Paths.get("Repositorio/utilizadores.txt");
927 byte[] data = Files.readAllBytes(path);
928
929
930 Cipher c = Cipher.getInstance("PBEWithHmacSHA256AndAES_128");
931 c.init(Cipher.DECRYPT_MODE, key, spec);
932 FileOutputStream fos = new FileOutputStream("Repositorio/utilizadores.txt");
933 fos.write(c.doFinal(data));
934 fos.close();
935
936 return c.doFinal(data);
937 }
938
939
940
941
942 public static void CifrarChaveComChavePublica(String user,String keyname) throws Exception {
943 FileInputStream fis = new FileInputStream("Repositorio/"+user+"/"+keyname.split("\\.(?=[^\\.]+$)")[0]+".key");
944 File cacheKEY= new File(("Repositorio/"+user+"/"+keyname.split("\\.(?=[^\\.]+$)")[0]+".key"));
945
946
947
948 byte[] keyS = new byte[16];
949 fis.read(keyS);
950 // cifrar chave secreta com a chave publica que está na keystore
951 // 1) obter o certificado
952 FileInputStream kfile = new FileInputStream("myServer.keystore"); //keystore
953 KeyStore kstore = KeyStore.getInstance("JKS");
954 kstore.load(kfile, "trotinete".toCharArray()); //password
955 Certificate cert = kstore.getCertificate("myServer");
956
957 //2) cifrar chave secreta com chave publica
958
959 Cipher cs = Cipher.getInstance("RSA");
960 cs.init(Cipher.WRAP_MODE, cert);
961 byte[] chaveCifrada = cs.wrap(new SecretKeySpec(keyS, "AES"));
962
963
964
965 FileOutputStream kos = new FileOutputStream("Repositorio/"+user+"/"+keyname.split("\\.(?=[^\\.]+$)")[0]+".txt.key.server");
966 ObjectOutputStream oos = new ObjectOutputStream(kos);
967 oos.write(chaveCifrada);
968 oos.close();
969 cacheKEY.delete();
970 fis.close();
971 }
972
973
974 public static byte[] DecifrarChavePublica(String user,String keyname) throws Exception {
975 ObjectInputStream keyFile =new ObjectInputStream(new FileInputStream("Repositorio"+File.separator+keyname.split("\\.(?=[^\\.]+$)")[0]+".txt.key.server"));
976 byte[] keyEncoded2 = new byte[256];
977
978 keyFile.read(keyEncoded2);
979 keyFile.close(); //decifra a chave lida do ficheiro
980 FileInputStream kfile = new FileInputStream("Repositorio"+File.separator+"myServer.keystore"); //keystore
981 KeyStore kstore = KeyStore.getInstance("JKS");
982 kstore.load(kfile, "trotinete".toCharArray()); //password
983 Key myPrivatekey = kstore.getKey("myServer", "trotinete".toCharArray());
984
985 Cipher c1 = Cipher.getInstance("RSA");
986 c1.init(Cipher.UNWRAP_MODE, myPrivatekey);
987 Key key = c1.unwrap(keyEncoded2, "AES", Cipher.SECRET_KEY);
988
989 return key.getEncoded();
990
991 }
992}