Encrypt File with AES Example

This program demonstrates encrypting a file using AES.

Problem Statement

Write a Java program that encrypts a text file using AES algorithm.

Source Code

1 import java.io.*;
2 import javax.crypto.*;
3 import javax.crypto.spec.SecretKeySpec;
4 public class AESEncryptExample {
5 public static void main(String[] args) {
6 System.out.println("Eduinq AES Encrypt Example");
7 try {
8 SecretKeySpec key=new SecretKeySpec("1234567890123456".getBytes(),"AES");
9 Cipher cipher=Cipher.getInstance("AES");
10 cipher.init(Cipher.ENCRYPT_MODE,key);
11 FileInputStream fis=new FileInputStream("plain.txt");
12 FileOutputStream fos=new FileOutputStream("encrypted.aes");
13 CipherOutputStream cos=new CipherOutputStream(fos,cipher);
14 byte[] buffer=new byte[1024];
15 int len;
16 while((len=fis.read(buffer))!=-1){
17 cos.write(buffer,0,len);
18 }
19 cos.close();fis.close();fos.close();
20 System.out.println("Eduinq File Encrypted Successfully");
21 } catch(Exception e) {
22 System.out.println("Eduinq Exception: "+e.getMessage());
23 }
24 }
25 }

Program Output

					Eduinq AES Encrypt Example
Eduinq File Encrypted Successfully
				

Explanation

AES encryption uses Cipher with secret key. - Encrypts file content into binary format. - Exception handling ensures safe operations. - In enterprise systems, AES encryption secures sensitive files. Conclusion: Shows encrypting files with AES.

Quick Links to Explore