Advertisement
Guest User

Untitled

a guest
May 30th, 2016
39
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. public class CipherConnection {
  2.  
  3. private String password = "abcdef0123456789";
  4. private Key key;
  5. private Cipher c;
  6. private OutputStream os;
  7. private InputStream is;
  8. private Socket s;
  9.  
  10. public CipherConnection(Socket s) {
  11. try {
  12. this.s = s;
  13. os = s.getOutputStream();
  14. is = s.getInputStream();
  15. key = new SecretKeySpec(password.getBytes(), "AES");
  16.  
  17. } catch (Exception e) {
  18. e.printStackTrace();
  19. }
  20. }
  21.  
  22.  
  23. void send(byte[] b) {
  24. try {
  25. c = Cipher.getInstance("AES");
  26. c.init(Cipher.ENCRYPT_MODE, key);
  27. CipherOutputStream cos = new CipherOutputStream(os, c);
  28. cos.write(b);
  29. } catch(Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33.  
  34. void send(byte b) {
  35. byte[] bb = new byte[1];
  36. bb[0] = b;
  37. send(bb);
  38. }
  39.  
  40. byte[] receive() {
  41. try {
  42. int b;
  43. Vector v = new Vector();
  44. c = Cipher.getInstance("AES");
  45. c.init(Cipher.DECRYPT_MODE, key);
  46. CipherInputStream cis = new CipherInputStream(is, c);
  47. b = cis.read();
  48. while ( b != -1) {
  49. v.add(b);
  50. b = cis.read();
  51. }
  52.  
  53. return toByteArray(v);
  54. } catch(Exception e) {
  55. e.printStackTrace();
  56. return null;
  57. }
  58. }
  59.  
  60. byte[] toByteArray(Vector v) {
  61. byte[] b = new byte[v.size()];
  62. int i = 0;
  63. while (!v.isEmpty()) {
  64. b[i] = (byte)v.remove(i);
  65. i++;
  66. }
  67. return null;
  68. }
  69.  
  70. void close() {
  71. try {
  72. os.close();
  73. is.close();
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. }
  77.  
  78. }
  79.  
  80. boolean isClosed() {
  81. return s.isClosed();
  82. }
  83.  
  84. public class TestServer {
  85.  
  86. static CipherConnection co;
  87. public static void main(String[] args) {
  88. try {
  89.  
  90. byte[] b;
  91. Socket s = new ServerSocket(3242).accept();
  92. co = new CipherConnection(s);
  93. b = co.receive();
  94. System.out.println(new String(b));
  95. } catch (Exception e) {
  96. e.printStackTrace();
  97. }
  98. }
  99.  
  100. public class TestClient {
  101.  
  102. static CipherConnection ci;
  103. /**
  104. * @param args the command line arguments
  105. */
  106. public static void main(String[] args) {
  107. try {
  108. Socket s = new Socket("127.0.0.1", 3242);
  109.  
  110. byte[] b;
  111. b = "Hello".getBytes();
  112. ci = new CipherConnection(s);
  113. ci.send(b);
  114. } catch (Exception e) {
  115. e.printStackTrace();
  116. }
  117.  
  118. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement