· 6 years ago · Feb 01, 2019, 05:12 PM
1import java.net.*;
2import java.security.InvalidKeyException;
3import java.security.NoSuchAlgorithmException;
4import java.io.*;
5
6import javax.crypto.Cipher;
7import javax.crypto.CipherInputStream;
8import javax.crypto.CipherOutputStream;
9import javax.crypto.NoSuchPaddingException;
10import javax.crypto.SecretKey;
11import javax.crypto.spec.SecretKeySpec;
12
13public class UTP301 {
14
15 public static void main(String args[])
16 {
17 int localPort = 6060;
18
19 ServerSocket sc;
20 Socket s;
21 FileOutputStream fos;
22
23 int bytesRead;
24 int current = 0;
25 /*int filesize;*/
26 long start,end ;
27 String nazwa;
28
29 SecretKey secret = new SecretKeySpec("1234567812345678".getBytes(), "AES");
30
31 Cipher cipher = null;
32 try {
33 cipher = Cipher.getInstance("AES");
34 } catch (NoSuchAlgorithmException e2) {
35 // TODO Auto-generated catch block
36 e2.printStackTrace();
37 } catch (NoSuchPaddingException e2) {
38 // TODO Auto-generated catch block
39 e2.printStackTrace();
40 }
41
42 try {
43 cipher.init(Cipher.DECRYPT_MODE,secret);
44 } catch (InvalidKeyException e1) {
45 // TODO Auto-generated catch block
46 e1.printStackTrace();
47 }
48
49 try {
50 // Nawiazywanie Polaczenia
51 System.out.println("Oczekiwanie...");
52 sc = new ServerSocket(localPort);
53 s = sc.accept();
54 System.out.println("Nawiazano Polaczenie");
55 sc.close();
56
57 start = System.currentTimeMillis(); // zaczyna mierzyc czas
58
59 //wysylanie nazwy pliku
60 DataInputStream dis = new DataInputStream(s.getInputStream());
61 nazwa = dis.readUTF();
62
63/* //wysylanie rozmiaru pliku
64 dis = new DataInputStream(s.getInputStream());
65 filesize = dis.readInt();*/
66
67 //wysylanie pliku
68 System.out.println("Odbieranie pliku " + nazwa);
69 InputStream is = s.getInputStream();
70 fos = new FileOutputStream(nazwa);
71 CipherOutputStream cos = new CipherOutputStream(fos, cipher);
72 byte [] mybytearray = new byte [cipher.getBlockSize()];
73 bytesRead = is.read(mybytearray,0,mybytearray.length);
74 current = bytesRead;
75
76 do {
77 //System.out.println("Odebrano: " + current + "bytes");
78 bytesRead = is.read(mybytearray, current, (mybytearray.length-current));
79 if(bytesRead >= 0) current += bytesRead;
80 } while(bytesRead > -1);
81
82 //zapis do pliku
83 cos.write(mybytearray, 0 , current);
84
85 end = System.currentTimeMillis(); // konczy mierzyc czas
86 System.out.println("Czas: "+ (end-start));
87 System.out.println("Stworzona plik: " + nazwa + " " + current + "bytes");
88
89 cos.close();
90 fos.close();
91 s.close();
92
93 }
94 catch (IOException e) {
95
96 System.out.println(e);
97 e.printStackTrace();
98 }
99 }
100}