1 7 package org.jboss.crypto; 8 9 import java.io.InputStream ; 10 import java.io.IOException ; 11 import java.io.OutputStream ; 12 import java.net.Socket ; 13 import java.util.Arrays ; 14 import javax.crypto.Cipher; 15 import javax.crypto.CipherInputStream; 16 import javax.crypto.CipherOutputStream; 17 import javax.crypto.spec.IvParameterSpec; 18 import javax.crypto.SecretKey; 19 20 24 public class CipherSocket extends Socket 25 { 26 private Cipher cipher; 27 private Socket delegate; 28 String algorithm; 29 SecretKey key; 30 31 32 public CipherSocket(String host, int port, String algorithm, SecretKey key) 33 throws IOException 34 { 35 super(host, port); 36 this.algorithm = algorithm; 37 this.key = key; 38 } 39 public CipherSocket(Socket delegate, String algorithm, SecretKey key) 40 throws IOException 41 { 42 this.delegate = delegate; 43 this.algorithm = algorithm; 44 this.key = key; 45 } 46 47 public InputStream getInputStream() throws IOException 48 { 49 InputStream is = delegate == null ? super.getInputStream() : delegate.getInputStream(); 50 Cipher cipher = null; 51 try 52 { 53 cipher = Cipher.getInstance(algorithm); 54 int size = cipher.getBlockSize(); 55 byte[] tmp = new byte[size]; 56 Arrays.fill(tmp, (byte)15); 57 IvParameterSpec iv = new IvParameterSpec(tmp); 58 cipher.init(Cipher.DECRYPT_MODE, key, iv); 59 } 60 catch(Exception e) 61 { 62 e.printStackTrace(); 63 throw new IOException ("Failed to init cipher: "+e.getMessage()); 64 } 65 CipherInputStream cis = new CipherInputStream(is, cipher); 66 return cis; 67 } 68 69 public OutputStream getOutputStream() throws IOException 70 { 71 OutputStream os = delegate == null ? super.getOutputStream() : delegate.getOutputStream(); 72 Cipher cipher = null; 73 try 74 { 75 cipher = Cipher.getInstance(algorithm); 76 int size = cipher.getBlockSize(); 77 byte[] tmp = new byte[size]; 78 Arrays.fill(tmp, (byte)15); 79 IvParameterSpec iv = new IvParameterSpec(tmp); 80 cipher.init(Cipher.ENCRYPT_MODE, key, iv); 81 } 82 catch(Exception e) 83 { 84 throw new IOException ("Failed to init cipher: "+e.getMessage()); 85 } 86 CipherOutputStream cos = new CipherOutputStream(os, cipher); 87 return cos; 88 } 89 } 90 | Popular Tags |