Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CipherConnection {
- private String password = "abcdef0123456789";
- private Key key;
- private Cipher c;
- private OutputStream os;
- private InputStream is;
- private Socket s;
- public CipherConnection(Socket s) {
- try {
- this.s = s;
- os = s.getOutputStream();
- is = s.getInputStream();
- key = new SecretKeySpec(password.getBytes(), "AES");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- void send(byte[] b) {
- try {
- c = Cipher.getInstance("AES");
- c.init(Cipher.ENCRYPT_MODE, key);
- CipherOutputStream cos = new CipherOutputStream(os, c);
- cos.write(b);
- } catch(Exception e) {
- e.printStackTrace();
- }
- }
- void send(byte b) {
- byte[] bb = new byte[1];
- bb[0] = b;
- send(bb);
- }
- byte[] receive() {
- try {
- int b;
- Vector v = new Vector();
- c = Cipher.getInstance("AES");
- c.init(Cipher.DECRYPT_MODE, key);
- CipherInputStream cis = new CipherInputStream(is, c);
- b = cis.read();
- while ( b != -1) {
- v.add(b);
- b = cis.read();
- }
- return toByteArray(v);
- } catch(Exception e) {
- e.printStackTrace();
- return null;
- }
- }
- byte[] toByteArray(Vector v) {
- byte[] b = new byte[v.size()];
- int i = 0;
- while (!v.isEmpty()) {
- b[i] = (byte)v.remove(i);
- i++;
- }
- return null;
- }
- void close() {
- try {
- os.close();
- is.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- boolean isClosed() {
- return s.isClosed();
- }
- public class TestServer {
- static CipherConnection co;
- public static void main(String[] args) {
- try {
- byte[] b;
- Socket s = new ServerSocket(3242).accept();
- co = new CipherConnection(s);
- b = co.receive();
- System.out.println(new String(b));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public class TestClient {
- static CipherConnection ci;
- /**
- * @param args the command line arguments
- */
- public static void main(String[] args) {
- try {
- Socket s = new Socket("127.0.0.1", 3242);
- byte[] b;
- b = "Hello".getBytes();
- ci = new CipherConnection(s);
- ci.send(b);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement