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