x
x
Example of Java encryption for any file using AES, IV, and CBC to CipherOutputStream. Download our desktop application and .jar file that includes this example below. View our desktop application's full source code for desktop, command line, or maven dependency on our GitHub page.



	import java.io.File;

	import java.io.FileInputStream;

	import java.io.FileOutputStream;

	import java.io.IOException;

	import java.io.InputStream;

	import java.io.OutputStream;

	import java.security.InvalidAlgorithmParameterException;

	import java.security.InvalidKeyException;

	import java.security.MessageDigest;

	import java.security.NoSuchAlgorithmException;

	import java.security.SecureRandom;

	

	import javax.crypto.Cipher;

	import javax.crypto.CipherOutputStream;

	import javax.crypto.NoSuchPaddingException;

	import javax.crypto.spec.IvParameterSpec;

	import javax.crypto.spec.SecretKeySpec;

	

	

	

	public class EncDecAESEncryptionExample {

	  private final static String KEYALG = "AES/CBC/PKCS5Padding";

	    

	  //encrypt method

	  public static boolean encrypt(String key, InputStream is, OutputStream out)

	    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,

	    InvalidAlgorithmParameterException, IOException {

			

	      boolean enc = false;

	      int ivSize = 16;

	      int keySize = 32;

	      try {

	        //Generate IV

	        byte[] iv = new byte[ivSize];

	        SecureRandom random = new SecureRandom();

	        random.nextBytes(iv);

	        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

	

	        //Hash key

	        MessageDigest digest = MessageDigest.getInstance("SHA-256");

	        digest.update(key.getBytes());

	        byte[] keyBytes = new byte[keySize];

	        System.arraycopy(digest.digest(), 0, keyBytes, 0, keyBytes.length);

	        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

	        	

	        //write iv to file first

	        out.write(iv);

	

	        //Encrypt

	        Cipher c = Cipher.getInstance(KEYALG);

	        c.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);

		    	

	        out = new CipherOutputStream(out, c);

	        int count = 0;

	        byte[] buffer = new byte[1024];

	        while ((count = is.read(buffer)) >= 0) {

	          out.write(buffer, 0, count);

	        }

		    	

	        enc = true;

	      }

	      catch (Exception e) {

	        e.printStackTrace();

	        enc = false;

	      }

	      finally {

	        out.close();

	      }

		    

	      return enc;

	    }

	

	    //decrypt mode

	    public static boolean decrypt(String key, InputStream is, OutputStream out)

	      throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,

	      InvalidAlgorithmParameterException, IOException {

	    	

	      boolean dec = false;

	      int ivSize = 16;

	      int keySize = 32;

	    	

	      try {		

	        //Extract IV

	        byte[] iv = new byte[ivSize];

	        is.read(iv, 0, 16);

	        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

	    		

	        //Hash key

	        byte[] keyBytes = new byte[keySize];

	        MessageDigest md = MessageDigest.getInstance("SHA-256");

	        md.update(key.getBytes());

	        System.arraycopy(md.digest(), 0, keyBytes, 0, keyBytes.length);

	        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

	    		

	        //Decrypt

	        Cipher c = Cipher.getInstance(KEYALG);

	        c.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);

	        out = new CipherOutputStream(out, c);

	        int count = 0;

	        byte[] buffer = new byte[1024];

	        while ((count = is.read(buffer)) >= 0) {

	          out.write(buffer, 0, count);

	        }

	

	        dec = true;

	      }

	      catch (Exception e) {

	        e.printStackTrace();

	        dec = false;

	      }

	      finally {

	        is.close();

	        out.close();

	      }    

	

	      return dec;

	    }

	

	

	    //process file for encryption or decryption

	    public static void main (String[] args) throws IOException {

	

	    //Files file mode 1, encrypt method

	    //Ex. "C:\test-original.docx"

	    File originalFile = new File("path\\to\\original\\file");

	    //Ex. "C:\my-hidden-file"

	    File encryptedOutFile = new File("your-fullpath\\new-encrypted-filename");

	

	    //Files for mode 2, decrypt method

	    //Ex. "C:\my-hidden-file" **encrypted file created in mode 1**

	    File encryptedInFile = new File("path\\to\\encrypted\\file");

	    //Ex. "C:\test-decrypted.docx"

	    File decrypted_file = 

	      new File("your-fullpath\\new-location-for-decrpyted-file-with-ext");

	    	

	    String passcode = "your encryption passcode 1";

	    //set encdec mode, 1 = encryption, 2 = decryption

	    int mode = 0;

	    boolean encDec = false;

	

	    try {           

	      //create 32 character, 

	      //encryption algorithm expects a passcode of base 16

	

	      if (mode == 1) {

	        //convert original file to inputstream

	        InputStream is = new FileInputStream(originalFile);

	        		

	        //call encrypt method

	        encDec = encrypt(passcode, is, 

	          new FileOutputStream(encryptedOutFile));

	

	        //create return values

	        if (encDec == true) {

	          System.out.println("File encrypted");

	        }

	        else {

	          System.out.println("File not encrypted");

	        }

	  

	      }

	      else if (mode == 2) {

	        //convert encrypted file to inputstream

	        InputStream is = new FileInputStream(encryptedInFile);

					    	          		       		  

	        //call decrypt method

	        encDec = decrypt(passcode, is, 

	          new FileOutputStream(decrypted_file));

	        if (encDec == true) {

	          System.out.println("File decrypted");	        		

	        }

	        else {

	          System.out.println("File not decrypted");

	        }

	      }

	      else {

	        System.out.println("Set mode to 1 or 2");

	      }

	    } 

	    catch (Exception e) {

	      e.printStackTrace();

	    }

	

	  }

	

	}










x
EncDec, LLC has a Terms, Privacy, and Cookie agreement to be acknowledged by all website users. More info on Cookies (www.ftc.gov) I understand