Chapter 4 90 // Create a cipher using that key to initialize it Cipher cipher = Cipher.getInstance("RC4"); System.out.println("Initializing SecureRandom..."); // Now we need an Initialization Vector for the cipher in CBC mode. // We use 16 bytes, because the block size of Rijndael is 256 bits. SecureRandom random = new SecureRandom(); byte[] iv = new byte[16]; random.nextBytes(iv); FileInputStream fis = new FileInputStream(fileInput); FileOutputStream fos = new FileOutputStream(fileOutput); // Write the IV as the first 16 bytes in the file fos.write(iv); IvParameterSpec spec = new IvParameterSpec(iv); System.out.println("Initializing the cipher."); cipher.init(Cipher.ENCRYPT_MODE, key); and for decrypt(), they are: // Create a cipher using that key to initialize it Cipher cipher = Cipher.getInstance("RC4"); FileInputStream fis = new FileInputStream(fileInput); FileOutputStream fos = new FileOutputStream(fileOutput); // Read the IV from the file. It's the first 16 bytes. byte[] iv = new byte[16]; fis.read(iv); IvParameterSpec spec = new IvParameterSpec(iv); System.out.println("Initializing the cipher."); cipher.init(Cipher.DECRYPT_MODE, key); CipherInputStream cis = new CipherInputStream(fis, cipher); System.out.println("Decrypting the file..."); Now we should be able to encrypt and decrypt files using RC4 instead of Rijndael/AES. We've finished our discussion of cipher streams, and are going to move on to a new class that uses symmetric encryption: SealedObject. Sealed Objects The JCE provides a way to encrypt objects one at a time with a given cipher or key. The encrypted objects are then called sealed objects. Sealed objects can be useful for storing or transferring an encrypted version of an object, although the object to be encrypted needs to be serializable.