A few years ago, I wrote a post regarding file encryption with Java here: https://cryptofreek.org/2010/06/04/encrypting-and-decrypting-files-with-java/
To my amazement, that post still gets tons of hits and it’s linked to from lots of different places. The problem, it’s a bit crusty and I really don’t like it that much. So, here’s a much needed update:
I’m not going to spend much time explaining everything here. Hopefully the comments in the code will do that. This example uses AES, but could be easily modified to use other encryption algorithms.
Generating secure keys is beyond the scope of this post, but take a look here for a decent starting point: https://cryptofreek.org/2012/11/29/pbkdf2-pure-java-implementation/
If you have any questions, let me know!
/* * Copyright (c) 2012 Cole Barnes [cryptofreek{at}gmail{dot}com] * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Formatter; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class CEncryptExample { /** * Encrypts the data received from the specified InputStream; encrypted data * is written to the specified OutputStream. * * @param key The secret key used to encrypt the data. * @param baIv The initialization vector to be used in encryption. * @param in InputStream for reading data to encrypt. * @param out OutputStream for writing encrypted data. * @param strCipherAlg The encryption algorithm to use; this must correspond * to something that makes sense with the specified * secret key. * @throws Exception */ public static void encrypt(SecretKey key, byte[] baIv, InputStream in, OutputStream out, String strCipherAlg) throws Exception { doCrypto(key, baIv, in, out, Cipher.ENCRYPT_MODE, strCipherAlg); } /** * Decrypts the data received from the specified InputStream; decrypted data * is written to the specified OutputStream. * * @param key The secret key used to decrypt the data. * @param baIv The initialization vector to be used in decryption. * @param in InputStream for reading encrypted data. * @param out OutputStream for writing decrypted data. * @param strCipherAlg The encyption algorithm to use; this must correspond * to something that makes sense with the specified * secret key. * @throws Exception */ public static void decrypt(SecretKey key, byte[] baIv, InputStream in, OutputStream out, String strCipherAlg) throws Exception { doCrypto(key, baIv, in, out, Cipher.DECRYPT_MODE, strCipherAlg); } /** * Performs the cryptographic operation on the specified IO Streams. This * function is private and is not meant to be called directly. * * @param key The secret key used in the crypto operation. * @param baIv The initialization vector used in the crypto operation. * @param in InputStream to from which data is read. * @param out OutputStream to where data is written. * @param nMode Operation mode; either Cipher.DECRYPT_MODE or Cipher.ENCRYPT_MODE * @param strCipherAlg The encryption algorithm; this must correspond to * something that makes sense with the specified secret key * @throws Exception */ private static void doCrypto(SecretKey key, byte[] baIv, InputStream in, OutputStream out, int nMode, String strCipherAlg) throws Exception { Cipher cipher = Cipher.getInstance(strCipherAlg); cipher.init(nMode, key, new IvParameterSpec(baIv, 0, cipher.getBlockSize())); CipherInputStream cis = new CipherInputStream(in, cipher); byte[] baBuff = new byte[1024]; int nBytesRead = -1; while ((nBytesRead = cis.read(baBuff)) != -1) { out.write(baBuff, 0, nBytesRead); } cis.close(); in.close(); out.flush(); out.close(); } /* There's only static utility/test functions from here down. */ private static void doFileCryptoTest(SecretKey key, byte[] baIv, String strCipherAlg) throws Exception { String strFile = "/Users/cbarnes/Desktop/test.txt"; String strEncryptedFile = "/Users/cbarnes/Desktop/test.txt.encrypted"; String strDecryptedFile = "/Users/cbarnes/Desktop/test.txt.decrypted"; encrypt(key, baIv, new FileInputStream(strFile), new FileOutputStream(strEncryptedFile), strCipherAlg); decrypt(key, baIv, new FileInputStream(strEncryptedFile), new FileOutputStream(strDecryptedFile), strCipherAlg); System.out.println("Encrypted File Hash: " + calcDigest(new FileInputStream(strEncryptedFile))); System.out.println("Decrypted File Hash: " + calcDigest(new FileInputStream(strDecryptedFile))); System.out.println(" Orig File Hash: " + calcDigest(new FileInputStream(strFile))); System.out.println(); } private static void doByteCryptoTest(SecretKey key, byte[] baIv, String strCipherAlg) throws Exception { byte[] baData = "This is some data.".getBytes(); ByteArrayInputStream baisData = new ByteArrayInputStream( baData ); ByteArrayOutputStream baosEncrytpedData = new ByteArrayOutputStream(); encrypt(key, baIv, baisData, baosEncrytpedData, strCipherAlg); byte[] baEncrytpedData = baosEncrytpedData.toByteArray(); ByteArrayInputStream baisEncryptedData = new ByteArrayInputStream(baEncrytpedData); ByteArrayOutputStream baosDecryptedData = new ByteArrayOutputStream(); decrypt(key, baIv, baisEncryptedData, baosDecryptedData, strCipherAlg); byte[] baDecryptedData = baosDecryptedData.toByteArray(); System.out.println("Encrypted Data Hash: " + calcDigest(new ByteArrayInputStream(baEncrytpedData))); System.out.println("Decrypted Data Hash: " + calcDigest(new ByteArrayInputStream(baDecryptedData))); System.out.println(" Orig Data Hash: " + calcDigest(new ByteArrayInputStream(baData))); System.out.println(); } private static String calcDigest(InputStream in) throws Exception { MessageDigest digest = MessageDigest.getInstance("SHA-1"); byte[] baBuff = new byte[1024]; int nBytesRead = -1; while ((nBytesRead = in.read(baBuff)) != -1) { digest.update(baBuff, 0, nBytesRead); } in.close(); byte[] baDigest = digest.digest(); StringBuilder sb = new StringBuilder(baDigest.length * 2); Formatter formatter = new Formatter(sb); for (byte b : baDigest) { formatter.format("%02x", b); } formatter.close(); String strDigest = sb.toString().toLowerCase(); return strDigest; } public static void main(String[] args) { try { String strKeyAlg = "AES"; int nKeySize = 128; String strCipherAlg = "AES/CBC/PKCS5Padding"; /* It is your responsibility to come up with a secure manor in which to * generate encryption keys!!! */ byte[] baKey = new byte[nKeySize / 8]; SecureRandom.getInstance("SHA1PRNG").nextBytes(baKey); SecretKey key = new SecretKeySpec(baKey, strKeyAlg); /* * NEVER reuse initialization vectors (IV)!!! They should be randomly/securely * generated for each separate encryption operation. The IV should be * kept with the encrypted data; it is not "secret" and does not necessarily * need to be protected. You only need to insure new secure IV is generated * each time data is encrypted; the same IV is used to decrypt the data. */ byte[] baIv = new byte[128]; SecureRandom.getInstance("SHA1PRNG").nextBytes(baIv); doFileCryptoTest(key, baIv, strCipherAlg); SecureRandom.getInstance("SHA1PRNG").nextBytes(baIv); doByteCryptoTest(key, baIv, strCipherAlg); } catch (Exception e) { e.printStackTrace(); } } }