public BlockStreamCrypter(Idea idea, bool encrypt) { this.idea = idea; this.encrypt = encrypt; prev = new byte[blockSize]; newPrev = new byte[blockSize]; }
/** * Encrypts or decrypts a file. * * @param inputFileName * Name of the input file. * @param outputFileName * Name of the output file. * @param charKey * The encryption key. A string of ASCII characters within the range 0x21 .. 0x7E. * @param encrypt * true to encrypt, false to decrypt. * @param mode * Mode of operation. */ public static void cryptFile(String inputFileName, String outputFileName, String charKey, bool encrypt) { FileStream inStream = null; FileStream outStream = null; try { Idea idea = new Idea(charKey, encrypt); BlockStreamCrypter bsc = new BlockStreamCrypter(idea, encrypt); inStream = new FileStream(inputFileName, FileMode.Open, FileAccess.ReadWrite); long inFileSize = inStream.Length; long inDataLen; long outDataLen; if (encrypt) { inDataLen = inFileSize; outDataLen = (inDataLen + blockSize - 1) / blockSize * blockSize; } else { if (inFileSize == 0) { throw new IOException("Input file is empty."); } if (inFileSize % blockSize != 0) { throw new IOException("Input file size is not a multiple of " + blockSize + "."); } inDataLen = inFileSize - blockSize; outDataLen = inDataLen; } outStream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write); processData(inStream, inDataLen, outStream, outDataLen, bsc); if (encrypt) { writeDataLength(outStream, inDataLen, bsc); } else { long outFileSize = readDataLength(inStream, bsc); if (outFileSize < 0 || outFileSize > inDataLen || outFileSize < inDataLen - blockSize + 1) { throw new IOException("Input file is not a valid cryptogram."); } if (outFileSize != outDataLen) { outStream.SetLength(outFileSize); } } outStream.Close(); } finally { if (inStream != null) { inStream.Close(); } if (outStream != null) { outStream.Close(); } } }