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" ) ) ; } }
Encrypt a file .