The following works for both encryption and decryption. If the Cipher has been initialised with javax.crypto.Cipher.ENCRYPT_MODE then it encrypts and if with javax.crypto.Cipher.DECRYPT_MODE then it decrypts..
public static void encryptOrDecryptFile(File ifile, Cipher cipher, File ofile) throws Exception
{
InputStream istrm = new FileInputStream(ifile);
istrm = new javax.crypto.CipherInputStream(istrm, cipher);
OutputStream ostrm = new FileOutputStream(ofile);
byte[] buffer = new byte[65536];
for (int len = 0; (len = istrm.read(buffer)) >= 0;)
{
ostrm.write(buffer, 0, len);
}
ostrm.close();
istrm.close();
}
If all you need is to read from an encrypted XML file then just wrap the FileInputStream in a CipherInputStream and use that as input to the SAX parser. To save then just wrap your FileOutputStream in a CipherOuputStream.
Message was edited by:
sabre150
> Thanks, it's helpful. A bit more clarification. If
> I'm going to use asymmetric algorithm, then should I
> use different Cipher instances for encryption and
> decryption? Like one of them initialized with private
> key and another with public.
I probably would have two instances but it is not strictly necessary since one can init() a cipher as often as one likes.
> I'm going to use asymmetric algorithm,
Are you aware that the use of RSA for encrpting a lot of data is very very very slow and fraught with difficulties. You might want to consider the approach suggested by Ferguson and Schneier in chapter 13.6 of their book 'Practical Cryptography'. In this they create a random symetric algorithm session key and encrypt that with RSA shipping the RSA encrpted session key followed by the symetric algorithm encrypted data.