Saturday, December 1, 2012

How to marshal XML as encrypted file using CipherOutputStream



CipherOutputStream can be used to marshal XML as encrypted file to protect some confidential information. The CipherOutputStream overrides all methods underlying output stream to support encryption needs. It takes OutputStream and Cipher in the constructor and the incoming Cipher must need to be initialized before passing in. 

The following code shows how to use CipherOutputStream to marshal XML to encrypted file.

List<Object> data = new ArrayList<Object>(); //data with large list
      JAXBContext jc = JAXBContext.newInstance("XML SCHEMA PATH");
      Marshaller m = jc.createMarshaller();
       
      byte[] key = new byte[]{/*key bytes*/};
      final SecretKey secretKey = new SecretKeySpec(key, "AES");  
      Cipher cipher = Cipher.getInstance("AES", "SunJCE");
      cipher.init(Cipher.ENCRYPT_MODE, secretKey);
OutputStream outputStream = new CipherOutputStream(new FileOutputStream(new File("largetest.xml")), cipher);       
      m.marshal(data, outputStream);
      outputStream.close();

No comments:

Post a Comment