Stream implementation for encrypted files

I'm looking for stream implementation suitable for SAX parsers for reading and writing encrypted XML files. Can somebody point me on some examples using CipherInputStream, Cipher, and Key?Message was edited by: dmitryr
[240 byte] By [dmitryra] at [2007-10-3 3:49:03]
# 1

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

sabre150a at 2007-7-14 21:46:11 > top of Java-index,Security,Cryptography...
# 2
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.
dmitryra at 2007-7-14 21:46:11 > top of Java-index,Security,Cryptography...
# 3

> 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.

sabre150a at 2007-7-14 21:46:11 > top of Java-index,Security,Cryptography...
# 4

> 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.

sabre150a at 2007-7-14 21:46:11 > top of Java-index,Security,Cryptography...
# 5
Thank you for pointing that. Actually performance isn't the case for my usage . However I'll check the chapter.
dmitryra at 2007-7-14 21:46:11 > top of Java-index,Security,Cryptography...