· 5 years ago · Mar 30, 2020, 10:46 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;
9import java.security.SecureRandom;
10
11public class Client {
12 public static void main(String args[]) {
13
14 Socket s = null;
15 int serversocket = 4567;
16 try {
17 s = new Socket("127.0.0.1", serversocket);
18
19 DataInputStream in = new DataInputStream(s.getInputStream());
20 DataOutputStream out = new DataOutputStream(s.getOutputStream());
21
22 while (true){
23 //key
24 byte [] key = {1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4};
25 SecretKey secretKey = new SecretKeySpec(key, 0, key.length, "AES");
26
27 //nonce
28 byte[] bytesForIV=new byte[16];
29 SecureRandom sr = new SecureRandom();
30 sr.nextBytes(bytesForIV);
31 IvParameterSpec iv = new IvParameterSpec(bytesForIV);
32
33 //sends the bytes in plaintext so that the server can create the same IV
34 out.write(bytesForIV);
35
36 Cipher c = Cipher.getInstance("AES/CTR/PKCS5Padding");
37 c.init(Cipher.ENCRYPT_MODE, secretKey, iv);
38
39 OutputStream ot = out;
40 CipherOutputStream cos = new CipherOutputStream(ot, c);
41 int text;
42 while((text=System.in.read())!=-1){
43 cos.write((byte)text);
44 cos.flush();
45 }
46
47 }
48 } catch (UnknownHostException e) {
49 System.out.println("Sock:" + e.getMessage());
50 } catch (EOFException e) {
51 System.out.println("EOF:" + e.getMessage());
52 } catch (IOException e) {
53 System.out.println("IO:" + e.getMessage());
54 } catch (NoSuchPaddingException e) {
55 e.printStackTrace();
56 } catch (NoSuchAlgorithmException e) {
57 e.printStackTrace();
58 } catch (InvalidAlgorithmParameterException e) {
59 e.printStackTrace();
60 } catch (InvalidKeyException e) {
61 e.printStackTrace();
62 } finally {
63 if (s != null)
64 try {
65 s.close();
66 } catch (IOException e) {
67 System.out.println("close:" + e.getMessage());
68 }
69 }
70 }
71}