package divya.upstream.common; import java.util.*; import java.io.*; import cryptix.security.*; /** * This class provides the ability to encrypt an OutputStream * using the DES 56-bit encryption as provided in the cryptix * library from Systemics (http://www.systemics.com). */ public class CryptOutputStream extends OutputStream { DES cryptor = null; byte[] pBuffer = null, eBuffer = null, inBuffer = new byte[16*1024], outBuffer = new byte[16*1024]; int pCount = 0, eCount = 0, blockLength = 0, bufferSize = 16*1024, bWritten = 0; OutputStream out; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean encrypt = false; public CryptOutputStream(OutputStream outStream, String key, boolean doCrypt) { out = outStream; if (doCrypt) { byte[] cryptkey; ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] keyBytes = key.getBytes(); baos.write(keyBytes, 0, (keyBytes.length>8) ? 8 : keyBytes.length); int cnt = baos.size(); for (int i = cnt; i < 8; i++) baos.write(-1); cryptkey = baos.toByteArray(); cryptor = new DES(cryptkey); blockLength = cryptor.blockLength(); } else blockLength = 8; pBuffer = new byte[blockLength]; eBuffer = new byte[blockLength]; encrypt = doCrypt; } public void flush() throws IOException { overflow(); super.flush(); out.flush(); } public void write(int b) throws IOException { if (pCount == blockLength) { if (encrypt) { cryptor.encrypt(pBuffer, eBuffer); if (baos.size() >= bufferSize) overflow(); baos.write(eBuffer, 0, blockLength); } else { if (baos.size() >= bufferSize) overflow(); baos.write(pBuffer, 0, blockLength); } bWritten += blockLength; pCount = 0; } if (pCount < blockLength) { pBuffer[pCount] = (new Integer(b)).byteValue(); pCount++; } } public void write(byte b[]) throws IOException { ByteArrayInputStream bais = new ByteArrayInputStream(b); int c = -1; while ((c = bais.read(pBuffer, pCount, blockLength-pCount)) != -1) { if (c < blockLength-pCount) { pCount += c; break; } if (encrypt) { cryptor.encrypt(pBuffer, eBuffer); if (baos.size() >= bufferSize) overflow(); baos.write(eBuffer, 0, blockLength); } else { if (baos.size() >= bufferSize) overflow(); baos.write(pBuffer, 0, blockLength); } bWritten += blockLength; pCount = 0; } } public void write(byte b[], int offset, int len) throws IOException { byte[] inB = new byte[len]; for (int i = offset; i < offset+len; i++) inB[i] = b[i]; this.write(inB); } public void overflow() throws IOException { byte [] outBytes = baos.toByteArray(); out.write(outBytes, 0, outBytes.length); baos.reset(); } public void close() throws IOException { if (pBuffer == null) return; if (pCount < blockLength) { for (int i = pCount; i < blockLength; i++) pBuffer[i] = -1; } if (encrypt) { cryptor.encrypt(pBuffer, eBuffer); baos.write(eBuffer, 0, blockLength); overflow(); } else { baos.write(pBuffer, 0, blockLength); overflow(); } bWritten += blockLength; out.flush(); out.close(); // now cleanup... pCount = 0; pBuffer = null; eBuffer = null; cryptor = null; } }