1 6 21 22 package de.schlichtherle.crypto.io; 23 24 import java.io.FilterOutputStream ; 25 import java.io.IOException ; 26 import java.io.OutputStream ; 27 28 import org.bouncycastle.crypto.BufferedBlockCipher; 29 import org.bouncycastle.crypto.InvalidCipherTextException; 30 31 49 public class CipherOutputStream extends FilterOutputStream { 50 51 52 protected BufferedBlockCipher cipher; 53 54 58 private byte[] outBuf = new byte[0]; 59 60 61 private boolean closed; 62 63 76 public CipherOutputStream(OutputStream out, BufferedBlockCipher cipher) { 77 super(out); 78 79 this.cipher = cipher; 80 } 81 82 90 public void write(final int b) 91 throws IOException { 92 ensureInit(); 93 94 int outLen = cipher.getUpdateOutputSize(1); 95 if (outLen > outBuf.length) 96 outBuf = new byte[outLen]; 97 outLen = cipher.processByte((byte) b, outBuf, 0); 98 if (outLen > 0) 99 out.write(outBuf, 0, outLen); 100 } 101 102 113 public void write(final byte[] buf, final int off, final int len) 114 throws IOException { 115 ensureInit(); 116 117 int outLen = cipher.getUpdateOutputSize(len); 118 if (outLen > outBuf.length) 119 outBuf = new byte[outLen]; 120 outLen = cipher.processBytes(buf, off, len, outBuf, 0); 121 out.write(outBuf, 0, outLen); 122 } 123 124 137 public void finish() throws IOException { 138 ensureInit(); 139 140 int outLen = cipher.getOutputSize(0); 141 if (outLen > outBuf.length) 142 outBuf = new byte[outLen]; 143 try { 144 outLen = cipher.doFinal(outBuf, 0); 145 } catch (InvalidCipherTextException icte) { 146 IOException ioe = new IOException (icte.toString()); 147 ioe.initCause(icte); 148 throw ioe; 149 } 150 out.write(outBuf, 0, outLen); 151 out.flush(); 152 } 154 155 160 private final void ensureInit() throws IOException { 161 if (cipher == null) 162 throw new IOException ("CipherOutputStream has already been closed or is not initialized!"); 163 } 164 165 172 public void close() throws IOException { 173 if (!closed) { 175 closed = true; 176 try { 177 finish(); 178 } finally { 179 cipher = null; 180 super.close(); 181 } 182 } 183 } 184 } 185 | Popular Tags |