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