Esempio n. 1
0
  public void write(SecureItemTable tbl, char[] password) throws IOException {
    OutputStream os = new FileOutputStream(file);
    OutputStream xmlout;

    if (password.length == 0) {
      xmlout = os;
      os = null;
    } else {
      PBEKeySpec keyspec = new PBEKeySpec(password);
      Cipher c;
      try {
        SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = fac.generateSecret(keyspec);

        c = Cipher.getInstance("PBEWithMD5AndDES");
        c.init(Cipher.ENCRYPT_MODE, key, pbeSpec);
      } catch (java.security.GeneralSecurityException exc) {
        os.close();
        IOException ioe = new IOException("Security exception during write");
        ioe.initCause(exc);
        throw ioe;
      }

      CipherOutputStream out = new CipherOutputStream(os, c);
      xmlout = out;
    }

    try {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer t = tf.newTransformer();

      DOMSource src = new DOMSource(tbl.getDocument());
      StringWriter writer = new StringWriter();
      StreamResult sr = new StreamResult(writer);
      t.transform(src, sr);

      OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8);
      osw.write(writer.toString());
      osw.close();
    } catch (Exception exc) {
      IOException ioe = new IOException("Unable to serialize XML");
      ioe.initCause(exc);
      throw ioe;
    } finally {
      xmlout.close();
      if (os != null) os.close();
    }

    tbl.setDirty(false);
    return;
  }