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