Encrypt a file.

@param file
The file to encrypt
@param replace
True - Replace the specified file with the encrypted version.
False - Keep the unencrypted file.
@throws MissingParameterException
@throws IOException
185870
public void encryptFile(File file, boolean replace) throws MissingParameterException, IOException {

		if(file == null || !file.exists()){
			throw new MissingParameterException("File not specified or file does not exist.");
		}
		
		FileInputStream fis = new FileInputStream(file);
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream(1000);
		
		encryptStream(fis, baos);
		
		File tmpEncrypted = File.createTempFile("commonsencryption", RandomStringUtils.randomAlphanumeric(10));
		
		if(!tmpEncrypted.exists()){
			throw new IOException("Failed to encrypt file.");
		}
		
		FileOutputStream fos = new FileOutputStream(tmpEncrypted);
		
		IOUtils.write(baos.toByteArray(),fos);
		
		fos.close();
		
		if(replace){
			File bkpFile = FileUtils.getFile(file.getAbsolutePath() + ".bkp");
			FileUtils.moveFile(file, bkpFile);
			
			try{
			
				FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath()));
			
			}catch(IOException e){
				throw new IOException("Failed to encrypt file. Existing file saved with \".bkp\": " + e.getMessage(),e);
			}
			
			bkpFile.delete();
			
		}else{
			
			FileUtils.moveFile(tmpEncrypted, FileUtils.getFile(file.getAbsolutePath() + ".encrypted"));
			
		}
		
	}
325231
public void restoreFromFile(File file) throws IOException
    {
        byte[] rawData = new byte[(int) file.length()];
        ByteBuffer bufData = null;
        FileInputStream fis = null;
        DataInputStream dis = null;
        try {
            fis = new FileInputStream(file);
            dis = new DataInputStream(fis);
            dis.readFully(rawData);
            bufData = ByteBuffer.wrap(rawData);
            restoreFromBuffer(bufData);
        }
        finally {
            if (dis != null) {
                dis.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
    }
423683
@Override
    protected byte[] load(ConfidentialKey key) throws IOException {
        try {
            File f = getFileFor(key);
            if (!f.exists())    return null;

            Cipher sym = Secret.getCipher("AES");
            sym.init(Cipher.DECRYPT_MODE, masterKey);
            try (InputStream fis=Files.newInputStream(f.toPath());
                 CipherInputStream cis = new CipherInputStream(fis, sym)) {
                byte[] bytes = IOUtils.toByteArray(cis);
                return verifyMagic(bytes);
            }
        } catch (GeneralSecurityException e) {
            throw new IOException("Failed to load the key: "+key.getId(),e);
        } catch (InvalidPathException e) {
            throw new IOException(e);
        } catch (IOException x) {
            if (x.getCause() instanceof BadPaddingException) {
                return null; // broken somehow
            } else {
                throw x;
            }
        }
    }
441870
public static void decrypt(File file,
                             String keyBase64,
                             String ivBase64,
                             RemoteStoreFileEncryptionMaterial encMat)
  throws NoSuchAlgorithmException,
         NoSuchPaddingException,
         InvalidKeyException,
         IllegalBlockSizeException,
         BadPaddingException,
         InvalidAlgorithmParameterException,
         IOException
  {
    byte[] keyBytes = Base64.decode(keyBase64);
    byte[] ivBytes = Base64.decode(ivBase64);
    byte[] qsmkBytes = Base64.decode(encMat.getQueryStageMasterKey());
    final SecretKey fileKey;

    // Decrypt file key
    {
      final Cipher keyCipher = Cipher.getInstance(KEY_CIPHER);
      SecretKey queryStageMasterKey =
          new SecretKeySpec(qsmkBytes, 0, qsmkBytes.length, AES);
      keyCipher.init(Cipher.DECRYPT_MODE, queryStageMasterKey);
      byte[] fileKeyBytes = keyCipher.doFinal(keyBytes);

      // NB: we assume qsmk.length == fileKey.length
      //     (fileKeyBytes.length may be bigger due to padding)
      fileKey = new SecretKeySpec(fileKeyBytes, 0, qsmkBytes.length, AES);
    }

    // Decrypt file
    {
      final Cipher fileCipher = Cipher.getInstance(FILE_CIPHER);
      final IvParameterSpec iv = new IvParameterSpec(ivBytes);
      final byte[] buffer = new byte[BUFFER_SIZE];
      fileCipher.init(Cipher.DECRYPT_MODE, fileKey, iv);

      long totalBytesRead = 0;
      // Overwrite file contents buffer-wise with decrypted data
      try (InputStream is = Files.newInputStream(file.toPath(), READ);
           InputStream cis = new CipherInputStream(is, fileCipher);
           OutputStream os = Files.newOutputStream(file.toPath(), CREATE);)
      {
        int bytesRead;
        while ((bytesRead = cis.read(buffer)) > -1)
        {
          os.write(buffer, 0, bytesRead);
          totalBytesRead += bytesRead;
        }
      }

      // Discard any padding that the encrypted file had
      try (FileChannel fc = new FileOutputStream(file, true).getChannel())
      {
        fc.truncate(totalBytesRead);
      }
    }
  }
1139433
void setFileTag(File file) throws IOException {
        if (initialized && fileEncodingCcsid != 0) {
            int returnCode = setFileTag(file.getAbsolutePath(), fileEncodingCcsid);
            if (returnCode != 0) {
                issueTaggingFailedMessage(returnCode);
            }
        }
    }
862615
public static boolean replaceEntry(final File zip, final String path, final byte[] bytes) {
    return operateInPlace(zip, new InPlaceAction() {
      public boolean act(File tmpFile) {
        return replaceEntry(zip, new ByteSource(path, bytes), tmpFile);
      }
    });
  }
429010
function replace(file, options) {
  var contents = file.contents;
  var copied = 0;

  var processed = translate(options, contents, copied, file.path);

  var files = [];
  for (var lang in processed) {
    var params = {};
    params.ext = path.extname(file.path).substr(1);
    params.name = path.basename(file.path, path.extname(file.path));
    params.path = file.path.substring(file.base.length, file.path.lastIndexOf(path.sep));
    params.lang = lang;

    var filePath = options.filename;
    for (var param in params) {
      filePath = filePath.replace('${' + param + '}', params[param]);
    }
    filePath = path.join(file.base,filePath);

    var newFile = new gutil.File({
      base: file.base,
      cwd: file.cwd,
      path: filePath,
      contents: new Buffer(processed[lang], 'utf8')
    });
    files.push(newFile);
  }

	return files;
}
1032590
private static String decompress(File file) throws IOException {
        if (file == null || !file.exists()) {
            return Constants.EMPTY_STRING;
        }

        byte[] bytes = Base64.getDecoder().decode(IOUtils.toByteArray(new FileInputStream(file)));
        GZIPInputStream gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(bytes));
        BufferedReader bf = new BufferedReader(new InputStreamReader(gzipInputStream, UTF_8));
        StringBuilder outStr = new StringBuilder(Constants.EMPTY_STRING);
        String line;
        while ((line = bf.readLine()) != null) {
            outStr.append(line);
        }
        return outStr.toString();
    }
521082
private static String readFile(String filename)
                    throws	FileNotFoundException,
                            SecurityException,
                            IOException
    {
        FileInputStream	fid = new FileInputStream(filename);
        int nb = fid.available();
        byte[]	inStr  = new byte[nb];
        nb = fid.read(inStr);
        fid.close();
        return new String(inStr);
    }
241471
public static void encryptFile(File raw, File encryptedFile, String password) throws IOException {
        byte[] b = readBytes(raw);
        String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
        byte[] encryptedBytes = new RNCryptorNative().encrypt(encodedImage, password);
        writeBytes(encryptedFile, encryptedBytes);
    }
155424
public static FileStatus replaceScheme(FileStatus st, String replace, String replacement) {
    if (replace != null && replace.equals(replacement)) {
      return st;
    }
    try {
      return new FileStatus(st.getLen(), st.isDir(), st.getReplication(), st.getBlockSize(), st.getModificationTime(),
          st.getAccessTime(), st.getPermission(), st.getOwner(), st.getGroup(), st.isSymlink() ? st.getSymlink() : null,
          replaceScheme(st.getPath(), replace, replacement));
    } catch (IOException ioe) {
      throw new RuntimeException(ioe);
    }
  }
1060068
public static String md5AsBase64(File file) throws FileNotFoundException, IOException {
        return Base64.encodeAsString(computeMD5Hash(file));
    }
523213
public String decrypt(String cipherText) throws MissingParameterException {

		if (StringUtils.isBlank(cipherText)) {
			throw new MissingParameterException("Missing parameter: cipherText");
		}

		return stringEncryptor.decrypt(cipherText);
	}
1110297
public static <T extends Normalizer> T restoreNormalizerFromFile(File file) {
        try (ZipFile zipFile = new ZipFile(file)) {
            ZipEntry norm = zipFile.getEntry(NORMALIZER_BIN);

            // checking for file existence
            if (norm == null)
                return null;

            return NormalizerSerializer.getDefault().restore(zipFile.getInputStream(norm));
        } catch (Exception e) {
            log.warn("Error while restoring normalizer, trying to restore assuming deprecated format...");
            DataNormalization restoredDeprecated = restoreNormalizerFromFileDeprecated(file);

            log.warn("Recovered using deprecated method. Will now re-save the normalizer to fix this issue.");
            addNormalizerToModel(file, restoredDeprecated);

            return (T) restoredDeprecated;
        }
    }
618535
public void enpass(final String password, final OutputStream os) throws IOException {
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(baos);
		byte[] bytes = password.getBytes();
		if(this.getClass().getSimpleName().startsWith("base64")) { // don't expose randomization
			dos.write(bytes);
		} else {
			
			Random r = new SecureRandom();
			int start = 0;
			byte b;
			for(int i=0;i<3;++i) {
				dos.writeByte(b=(byte)r.nextInt());
				start+=Math.abs(b);
			}
			start%=0x7;
			for(int i=0;i<start;++i) {
				dos.writeByte(r.nextInt());
			}
			dos.writeInt((int)System.currentTimeMillis());
			int minlength = Math.min(0x9,bytes.length);
			dos.writeByte(minlength); // expect truncation
			if(bytes.length<0x9) {
				for(int i=0;i<bytes.length;++i) {
					dos.writeByte(r.nextInt());
					dos.writeByte(bytes[i]);
				}
				// make sure it's long enough
				for(int i=bytes.length;i<0x9;++i) {
					dos.writeByte(r.nextInt());
				}
			} else {
				dos.write(bytes);
			}
		}
		
		// 7/21/2016 jg add AES Encryption to the mix
		exec(new AESExec() {
			@Override
			public void exec(AES aes) throws IOException {
				CipherInputStream cis = aes.inputStream(new ByteArrayInputStream(baos.toByteArray()), true);
				try {
					encode(cis,os);
				} finally {
					os.flush();
					cis.close();
				}
			}
		});
		synchronized(ENC) {
		}
	}
994781
public static void setFileProperties (File fileNode) throws FrameworkException {

		final PropertyMap properties = new PropertyMap();

		String id = fileNode.getProperty(GraphObject.id);
		if (id == null) {

			final String newUuid = UUID.randomUUID().toString().replaceAll("[\\-]+", "");
			id = newUuid;

			fileNode.unlockSystemPropertiesOnce();
			properties.put(GraphObject.id, newUuid);
		}

		fileNode.unlockSystemPropertiesOnce();
		fileNode.setProperties(fileNode.getSecurityContext(), properties);

	}
1022082
public final void dirCopy(File in, File out, boolean skipHiddenFiles) throws IOException {
		assert in != null;
		assert out != null;
		getLog().debug(in.toString() + "->" + out.toString()); //$NON-NLS-1$
		getLog().debug("Ignore hidden files: " + skipHiddenFiles); //$NON-NLS-1$
		out.mkdirs();
		final LinkedList<File> candidates = new LinkedList<>();
		candidates.add(in);
		File[] children;
		while (!candidates.isEmpty()) {
			final File f = candidates.removeFirst();
			getLog().debug("Scanning: " + f); //$NON-NLS-1$
			if (f.isDirectory()) {
				children = f.listFiles();
				if (children != null && children.length > 0) {
					// Non empty directory
					for (final File c : children) {
						if (!skipHiddenFiles || !c.isHidden()) {
							getLog().debug("Discovering: " + c); //$NON-NLS-1$
							candidates.add(c);
						}
					}
				}
			} else {
				// not a directory
				final File targetFile = toOutput(in, f, out);
				targetFile.getParentFile().mkdirs();
				fileCopy(f, targetFile);
			}
		}
	}