Example #1
0
  private static void encryptFile(File file, EncryptedFormInformation formInfo)
      throws IOException, EncryptionException {
    File encryptedFile = new File(file.getParentFile(), file.getName() + ".enc");

    if (encryptedFile.exists() && !encryptedFile.delete()) {
      throw new IOException(
          "Cannot overwrite " + encryptedFile.getAbsolutePath() + ". Perhaps the file is locked?");
    }

    // add elementSignatureSource for this file...
    formInfo.appendFileSignatureSource(file);

    RandomAccessFile randomAccessFile = null;
    CipherOutputStream cipherOutputStream = null;
    try {
      Cipher c = formInfo.getCipher();

      randomAccessFile = new RandomAccessFile(encryptedFile, "rws");
      ByteArrayOutputStream encryptedData = new ByteArrayOutputStream();
      cipherOutputStream = new CipherOutputStream(encryptedData, c);
      InputStream fin = new FileInputStream(file);
      byte[] buffer = new byte[2048];
      int len = fin.read(buffer);
      while (len != -1) {
        cipherOutputStream.write(buffer, 0, len);
        len = fin.read(buffer);
      }
      fin.close();
      cipherOutputStream.flush();
      cipherOutputStream.close();

      randomAccessFile.write(encryptedData.toByteArray());

      Log.i(t, "Encrpyted:" + file.getName() + " -> " + encryptedFile.getName());
    } catch (Exception e) {
      String msg = "Error encrypting: " + file.getName() + " -> " + encryptedFile.getName();
      Log.e(t, msg, e);
      e.printStackTrace();
      throw new EncryptionException(msg, e);
    } finally {
      IOUtils.closeQuietly(cipherOutputStream);

      if (randomAccessFile != null) {
        randomAccessFile.close();
      }
    }
  }