1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
/**
* Crypts or decrypts the specified input stream to the specified output
* stream with a given cipher. The crypting or decrypting operation is
* determined by the cipher's state.
* @param cipher The cipher used to crypt the specified input stream to the specified output
* stream.
* @param in the input srteal stream to be encypted or decrypted.
* @param out the output stream to be encypted or decrypted.
* @throws java.io.IOException if an I/O error occurs during crypting the input stream to the output stream.
*/
public void crypt(InputStream in, OutputStream out, Cipher cipher)
throws IOException
{
int blockSize = cipher.getBlockSize();
int outputSize = cipher.getOutputSize(blockSize);
byte[] inBytes = new byte[blockSize];
byte[] outBytes = new byte[outputSize];
int inLength = 0;
boolean done = false;
while(!done)
{
inLength = in.read(inBytes);
if(inLength == blockSize)
{
try
{
int outLength = cipher.update(inBytes, 0, blockSize, outBytes);
out.write(outBytes, 0, outLength);
}
catch(ShortBufferException e)
{
e.printStackTrace();
}
}
else
done = true;
}
try
{
if(inLength > 0)
outBytes = cipher.doFinal(inBytes, 0, inLength);
else
outBytes = cipher.doFinal();
out.write(outBytes);
}
catch(IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch(BadPaddingException e)
{
e.printStackTrace();
}
} |
Partager