by BehindJava

How to Encrypt a file using AES256 algorithm in Java CryptoJS

Home » java » How to Encrypt a file using AES256 algorithm in Java CryptoJS

How to Encrypt a file using AES256 algorithm in Java?

In this tutorial, we are going learn about encrypting the files using AES256 Algorithm.

Firstly, create a Global key.

public class GlobalKey {
	public static void main(String[] args) {
		String CipherAlg="AES";
		try{ 
			KeyGenerator keyGen = KeyGenerator.getInstance(CipherAlg);
			keyGen.init(256); 			SecretKey secretKey = keyGen.generateKey();
			// Generate the secret key specs.
			byte[] rawGlobalKey = secretKey.getEncoded();      	 
			}
             catch(Exception e)
             { 
             System.out.println(e);
              }  
}
}

Now create a secret key for encrypting files by passing global as a parameter to the secretkey method.

public void secretKey(byte[] globalKey) throws Exception {     
	
		KeyGenerator keyGen = KeyGenerator.getInstance(this.CipherAlg);
		keyGen.init(256); 
		SecretKey secretKey = keyGen.generateKey();
		// Generate the secret key specs.		byte[] appRawKey = secretKey.getEncoded();   

		Cipher aesAppCipher = Cipher.getInstance(CipherAlg); 
		SecretKeySpec skeySpec = new SecretKeySpec(globalKey, CipherAlg);
		aesAppCipher.init(aesAppCipher.ENCRYPT_MODE, skeySpec);          
		byte[] encAppKey = aesAppCipher.doFinal(appRawKey);
	}

Using this encAppKey which is generated by the secretKey method the files get encrypted.

public class FileEncryption {

	String CipherAlg = "AES";
	byte[] appRawSkey;	byte[] appEncSkey;
	byte[] globalRawSKey;
	

	void EncryptDirFiles(String inputDir, String outDir) throws Exception {
		
		secretKey();
		try
		{
		File decryptDir = new File(inputDir);                

		File[] decFiles = decryptDir.listFiles();
		
		if(decFiles.length==0)
		{
			System.out.println("there are no files present in    "+inputDir);
		}
		else
		{
		Encrypt enc = new Encrypt(cap.appRawSkey,this.CipherAlg);
		for (int i = 0; i < decFiles.length; i++) {                
			String fname = decFiles[i].getName();
			enc.EncryptFile(decFiles[i],new File(outDir+"/"+fname)); 
			System.out.println("Encrypting " + fname);
			if(decFiles[i].delete())
			{
				System.out.println("Deleted the file from the path.." +decFiles[i].getPath());
			}
			
			else
			{
				System.out.println("Error while deleting the path" +decFiles[i].getPath());
			}
		}
		}
		}
	catch(Exception e)
	{
		System.out.println("Exception occured :"+e.toString());
	}
	}
	public static void main(String[] args) throws Exception {
		
		String inputDir = "C:\\Users\\Deepak\\Documents\\originalfiles";
		String outDir = "C:\\Users\\Deepak\\Documents\\wcr\\encryptedfiles";
		
		FileEncryption en=new FileEncryption();
		en.EncryptDirFiles(inputDir, outDir);
 	}
	
}

Encrypt class is called after checking the files in the directory based on this encryption of files happen.

public class Encrypt {

	String algorithm="";
	SecretKeySpec skeySpec;
	/** Creates a new instance of Encrypt */
	public Encrypt(byte[] sKey, String algorithm) {
		this.algorithm = algorithm;
		skeySpec = new SecretKeySpec(sKey, this.algorithm);
	}

	/** Read an unencrypted file and write it with encryption */
	public void EncryptFile(File inFile, File outFile) throws Exception{
		try
		{
		// Create Cipher
		Cipher des = Cipher.getInstance(this.algorithm);
		des.init(Cipher.ENCRYPT_MODE, this.skeySpec);
		FileInputStream in = new FileInputStream(inFile);
		FileOutputStream out = new FileOutputStream(outFile);
		CipherOutputStream cos = new CipherOutputStream(out,des);
		int len;
		byte[] buf = new byte[1024];
		while ((len = in.read(buf)) > 0) {
			cos.write(buf, 0, len);
		}
		in.close();
		cos.close();
		}
		catch(Exception e)
		{
			System.out.println("Exception occured" + e.toString());
		}
	}

	/** Read an encrypted file and write it unencrypted */
	public void DecryptFile(File inFile, File outFile) throws Exception {
		try
		{
		Cipher desCipher = Cipher.getInstance(this.algorithm);
		desCipher.init(Cipher.DECRYPT_MODE, this.skeySpec); 
		FileInputStream in = new FileInputStream(inFile);
		CipherInputStream cis = new CipherInputStream(in,desCipher);
		FileOutputStream out = new FileOutputStream(outFile);
		byte [] buf = new byte [1024];
		int n;
		while ((n = cis.read(buf)) > -1)
		{        
			out.write(buf, 0, n);
		}
		in.close();
		out.close();
		cis.close();
	}
	catch(Exception e)
	{
		System.out.println("Exception occured" + e.toString());
	}
}
}

If you are facing this error while creating keys i.e. “InvalidKeyException Illegal key size or default parameters”.

Please refer to this https://www.behindjava.com/java-AES256-key/