1 29 package Acme.Crypto; 30 31 import java.io.*; 32 33 61 public class EncryptedOutputStream extends FilterOutputStream 62 { 63 64 private BlockCipher blockCipher = null; 66 67 private StreamCipher streamCipher = null; 69 70 private Cipher cipher; 72 73 private CbcBlockCipher cbcBlockCipher; 75 76 private int blockSize; 78 79 private int cryptoSize; 81 82 private byte[] clearText; 84 85 private byte[] cipherText; 87 88 private int byteCount; 90 91 public EncryptedOutputStream( BlockCipher blockCipher, OutputStream out ) throws IOException 95 { 96 super( out ); 97 this.blockCipher = blockCipher; 98 this.blockSize = blockCipher.blockSize(); 99 cbcBlockCipher = new CbcBlockCipher( blockCipher ); 100 cryptoSize = blockSize; 101 clearText = new byte[blockSize]; 102 cipherText = new byte[blockSize]; 103 byteCount = 0; 104 this.cipher = blockCipher; 105 out.write( cbcBlockCipher.setRandomIv(), 0, blockSize ); 107 } 108 109 public EncryptedOutputStream( StreamCipher streamCipher, OutputStream out ) 113 { 114 super( out ); 115 this.streamCipher = streamCipher; 116 this.blockSize = 1; 117 this.cipher = streamCipher; 118 } 119 120 121 public void setKey( String keyStr ) 123 { 124 cipher.setKey( keyStr ); 125 } 126 127 128 private boolean encrypting = true; 130 131 public void setEncrypting( boolean encrypting ) throws IOException 133 { 134 if ( this.encrypting && ! encrypting ) 135 flush(); 136 this.encrypting = encrypting; 137 } 138 139 140 private void sendBlock() throws IOException 141 { 142 for ( int i = byteCount; i < cryptoSize; ++i ) 144 clearText[i] = (byte) ( Math.random() * 256.0 ); 145 cbcBlockCipher.encrypt( clearText, 0, cipherText, 0 ); 147 out.write( cipherText, 0, blockSize ); 149 out.write( (byte) byteCount ); 151 byteCount = 0; 152 } 153 154 public void write( int b ) throws IOException 156 { 157 if ( encrypting ) 158 { 159 if ( blockCipher != null ) 160 { 161 clearText[byteCount++] = (byte) b; 162 if ( byteCount >= cryptoSize ) 163 sendBlock(); 164 } 165 else 166 out.write( streamCipher.encrypt( (byte) b ) ); 168 } 169 else 170 out.write( b ); 172 } 173 174 public void write( byte b[], int off, int len ) throws IOException 176 { 177 if ( encrypting ) 178 { 179 if ( blockCipher != null ) 180 { 181 for ( int i = off; i < off + len; ++i ) 182 { 183 clearText[byteCount++] = b[i]; 184 if ( byteCount >= cryptoSize ) 185 sendBlock(); 186 } 187 } 188 else 189 { 190 byte[] cipherText = new byte[len]; 192 streamCipher.encrypt( b, off, cipherText, 0, len ); 193 out.write( cipherText, 0, len ); 194 } 195 } 196 else 197 out.write( b, off, len ); 199 } 200 201 202 public void flush() throws IOException 204 { 205 if ( encrypting && blockCipher != null && byteCount != 0 ) 206 sendBlock(); 207 out.flush(); 208 } 209 210 } 211 | Popular Tags |