Java tutorial
//package com.java2s; //License from project: Apache License import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class Main { private static final String KEY_ALGORITHM = "AES"; private static final String AES_CFB_NOPADDING = "AES/CFB/NOPADDING"; public static boolean encryptFile(byte[] key, byte[] iv, String sourceFilePath, String destFilePath) { return handleFile(Cipher.ENCRYPT_MODE, key, iv, sourceFilePath, destFilePath); } private static boolean handleFile(int mode, byte[] key, byte[] iv, String sourceFilePath, String destFilePath) { File sourceFile = new File(sourceFilePath); File destFile = new File(destFilePath); try { if (sourceFile.exists() && sourceFile.isFile()) { if (!destFile.getParentFile().exists()) destFile.getParentFile().mkdirs(); destFile.createNewFile(); InputStream in = new FileInputStream(sourceFile); OutputStream out = new FileOutputStream(destFile); Cipher cipher = initCipher(mode, key, iv, AES_CFB_NOPADDING); CipherInputStream cin = new CipherInputStream(in, cipher); byte[] b = new byte[1024]; int read = 0; while ((read = cin.read(b)) != -1) { out.write(b, 0, read); out.flush(); } cin.close(); in.close(); out.close(); return true; } } catch (Exception e) { e.printStackTrace(); } return false; } private static Cipher initCipher(int mode, byte[] key, byte[] iv, String cipherAlgotirhm) { try { Key k = toKey(key); Cipher cipher = Cipher.getInstance(cipherAlgotirhm); String CipherAlgotirhm = cipherAlgotirhm.toUpperCase(); if (CipherAlgotirhm.contains("CFB") || CipherAlgotirhm.contains("CBC")) cipher.init(mode, k, new IvParameterSpec(iv)); else cipher.init(mode, k); return cipher; } catch (Exception e) { e.printStackTrace(); } return null; } private static Key toKey(byte[] key) { return new SecretKeySpec(key, KEY_ALGORITHM); } }