7 import java.security.*;
\r
8 import javax.crypto.*;
\r
9 import javax.crypto.spec.*;
\r
11 import org.bouncycastle.openssl.*;
\r
12 import org.bouncycastle.util.encoders.*;
\r
18 public class TCP implements Runnable{
\r
19 private Socket $sock = null;
\r
20 private InputStream $in = null;
\r
21 private OutputStream $out = null;
\r
22 private Cipher $c2s = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding");
\r
23 private Cipher $s2c = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding");
\r
24 private PublicKey $puk = null;
\r
25 public PrivateKey $prk = null;
\r
26 public String $challenge = null;
\r
29 public TCP(String $server, int $port)throws Exception{
\r
30 System.out.println("CLIENT TCP: "+$server+":"+$port);
\r
31 $sock = new Socket($server, $port);
\r
32 $in = $sock.getInputStream();
\r
33 $out = $sock.getOutputStream();
\r
35 PEMReader in = new PEMReader(new FileReader(Main.$cfg.getString("server.key")));
\r
36 $puk = (PublicKey) in.readObject();
\r
38 $c2s.init(Cipher.ENCRYPT_MODE, $puk);
\r
39 $s2c.init(Cipher.DECRYPT_MODE, $prk);
\r
40 new Thread(this).start();
\r
45 while($sock != null){
\r
48 }catch(Exception $e){}
\r
49 System.out.println("TCP:run() ended");
\r
52 public void send(String $msg){
\r
54 byte[] $encrypted = $c2s.doFinal($msg.getBytes());
\r
55 byte[] $len = Helper.int2ba($encrypted.length);
\r
57 $out.write($encrypted);
\r
59 }catch(Exception $e){$e.printStackTrace();}
\r
62 public void receive()throws Exception{
\r
63 int $len = Helper.ba2int(Helper.readBA($in, 4));
\r
64 byte[]$raw = Helper.readBA($in, $len);
\r
65 String $msg = new String($s2c.doFinal($raw));
\r
66 if($msg.startsWith("!ok")){
\r
67 String[] $eing = $msg.split("\\s+");
\r
68 if(!$challenge.equals($eing[1])){
\r
69 System.out.println("ERROR: Challenge mismatch!");
\r
73 byte[] $skey = Base64.decode($eing[3].getBytes());
\r
74 byte[] $iv = Base64.decode($eing[4].getBytes());
\r
75 $c2s = Cipher.getInstance("AES/CTR/NoPadding");
\r
76 $s2c = Cipher.getInstance("AES/CTR/NoPadding");
\r
77 $c2s.init(Cipher.ENCRYPT_MODE, new SecretKeySpec($skey, "AES"), new IvParameterSpec($iv));
\r
78 $s2c.init(Cipher.DECRYPT_MODE, new SecretKeySpec($skey, "AES"), new IvParameterSpec($iv));
\r
81 System.out.println($msg);
\r
85 public void shutdown(){
\r
87 send("CLIENT shutting down...");
\r
92 }catch(Exception $e){$e.printStackTrace();}
\r