· 5 years ago · Mar 11, 2020, 08:02 PM
1import javax.crypto.*;
2import javax.crypto.spec.IvParameterSpec;
3import javax.crypto.spec.SecretKeySpec;
4import java.net.*;
5import java.io.*;
6import java.security.InvalidAlgorithmParameterException;
7import java.security.InvalidKeyException;
8import java.security.NoSuchAlgorithmException;
9
10public class Client {
11 public static void main(String args[]) {
12
13 Socket s = null;
14 int serversocket = 4567;
15 try {
16 s = new Socket("127.0.0.1", serversocket);
17
18 //DataInputStream in = new DataInputStream(s.getInputStream());
19 //DataOutputStream out = new DataOutputStream(s.getOutputStream());
20
21 //String text = "";
22 //InputStreamReader input = new InputStreamReader(System.in);
23 //BufferedReader reader = new BufferedReader(input);
24
25 /*while (true) {
26 try {
27 text = reader.readLine();
28 } catch (Exception e) {}
29
30 out.writeUTF(text);
31
32 /*String data = in.readUTF();
33 System.out.println(data);
34 }*/
35
36 //Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
37
38 while (true){
39 //key
40 /*KeyGenerator keyGen = KeyGenerator.getInstance("AES");
41 keyGen.init(128);
42 SecretKey secretKey = keyGen.generateKey();*/
43 byte [] key = {1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
44 SecretKey secretKey = new SecretKeySpec(key, 0, key.length, "AES");
45
46 //nonce
47 byte[] nonce={1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1};
48 IvParameterSpec iv = new IvParameterSpec(nonce);
49
50 Cipher c = Cipher.getInstance("AES/CTR/NoPadding");
51 c.init(Cipher.ENCRYPT_MODE, secretKey, iv);
52
53
54 FileOutputStream file = new FileOutputStream("C:\\Users\\maria\\IdeaProjects\\AC2\\src\\encrypt.txt");
55 CipherOutputStream cos = new CipherOutputStream(file, c);
56 int text;
57 while((text=System.in.read())!=-1) {
58 cos.write((byte)text);
59 cos.flush();
60 }
61 }
62 } catch (UnknownHostException e) {
63 System.out.println("Sock:" + e.getMessage());
64 } catch (EOFException e) {
65 System.out.println("EOF:" + e.getMessage());
66 } catch (IOException e) {
67 System.out.println("IO:" + e.getMessage());
68 } catch (NoSuchPaddingException e) {
69 e.printStackTrace();
70 } catch (NoSuchAlgorithmException e) {
71 e.printStackTrace();
72 } catch (InvalidAlgorithmParameterException e) {
73 e.printStackTrace();
74 } catch (InvalidKeyException e) {
75 e.printStackTrace();
76 } finally {
77 if (s != null)
78 try {
79 s.close();
80 } catch (IOException e) {
81 System.out.println("close:" + e.getMessage());
82 }
83 }
84 }
85
86 public void writeFile(Cipher c, String inputFile)
87 throws IOException {
88 FileOutputStream file = new FileOutputStream(inputFile);
89 CipherOutputStream cos = new CipherOutputStream(file, c);
90 int text;
91 while((text=System.in.read())!=-1) {
92 cos.write((byte)text);
93 cos.flush();
94 }
95 }
96}