Creating a Desktop File Encryption Tool with Java: High-Strength Encryption Algorithms to Protect File Privacy and Security

Creating a Desktop File Encryption Tool with Java

Hello, friends! I also started as a beginner in Python, and today we will create a super practical desktop file encryption tool using Java. In our daily work and life, file privacy and security are becoming increasingly important. With this tool, we can use high-strength encryption algorithms to add a “security lock” to our files and protect our privacy. Without further ado, let’s start our learning journey!

1. Preparation Before Development

(1) Install JDK

To embark on the journey of Java development, the JDK (Java Development Kit) is essential. It is like a universal key; without it, Java programs cannot run, let alone develop. You can download it from the Oracle website, and just follow the prompts during the installation process; it’s not difficult. After installation, there is a crucial step: configuring the environment variables. This is like drawing a detailed map for the computer, allowing it to easily find various Java commands; otherwise, the computer won’t know where to look for Java!

(2) Choose Development Tools

A good Integrated Development Environment (IDE) can greatly improve our development efficiency, like having a super capable assistant. Eclipse and IntelliJ IDEA are both excellent choices. Personally, I prefer IntelliJ IDEA; its features are particularly powerful, and the code suggestions and smart completion functions are very useful, saving us a lot of coding time. Open IntelliJ IDEA and create a new Java project, so we can officially start development!

2. Choosing and Implementing the Encryption Algorithm

(1) Introduction to Encryption Algorithms

In the field of encryption, there are many types of encryption algorithms, such as AES (Advanced Encryption Standard), which is like a very powerful safe, widely used and highly secure. We will choose the AES algorithm to implement file encryption.

(2) Implementation of AES Encryption Algorithm

 1import javax.crypto.Cipher;
 2import javax.crypto.KeyGenerator;
 3import javax.crypto.SecretKey;
 4import javax.crypto.spec.IvParameterSpec;
 5import java.io.*;
 6
 7public class FileEncryptionUtil {
 8    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
 9    private static final int KEY_SIZE = 128;
10
11    // Generate encryption key
12    public static SecretKey generateKey() throws Exception {
13        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
14        keyGenerator.init(KEY_SIZE);
15        return keyGenerator.generateKey();
16    }
17
18    // Encrypt file
19    public static void encryptFile(File inputFile, File outputFile, SecretKey key) throws Exception {
20        Cipher cipher = Cipher.getInstance(ALGORITHM);
21        byte[] iv = new byte[16];
22        IvParameterSpec ivSpec = new IvParameterSpec(iv);
23        cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
24
25        try (FileInputStream fis = new FileInputStream(inputFile);
26             FileOutputStream fos = new FileOutputStream(outputFile);
27             CipherOutputStream cos = new CipherOutputStream(fos, cipher)) {
28            byte[] buffer = new byte[1024];
29            int len;
30            while ((len = fis.read(buffer))!= -1) {
31                cos.write(buffer, 0, len);
32            }
33        }
34    }
35
36    // Decrypt file
37    public static void decryptFile(File inputFile, File outputFile, SecretKey key) throws Exception {
38        Cipher cipher = Cipher.getInstance(ALGORITHM);
39        byte[] iv = new byte[16];
40        IvParameterSpec ivSpec = new IvParameterSpec(iv);
41        cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
42
43        try (FileInputStream fis = new FileInputStream(inputFile);
44             FileOutputStream fos = new FileOutputStream(outputFile);
45             CipherInputStream cis = new CipherInputStream(fis, cipher)) {
46            byte[] buffer = new byte[1024];
47            int len;
48            while ((len = cis.read(buffer))!= -1) {
49                fos.write(buffer, 0, len);
50            }
51        }
52    }
53}

In this code, the <span>generateKey</span> method is used to generate the encryption key, like giving the safe a unique key. The <span>encryptFile</span> method is responsible for encrypting the file; it first initializes the encryption mode, then reads the file content and writes it to the output file through the encryption stream, like putting the file into the safe and locking it. The <span>decryptFile</span> method is used to decrypt the file, equivalent to using the key to open the safe and take the file out.

Tip: Be sure to keep the generated encryption key safe; if the key is lost, the file cannot be decrypted, and it will be locked in the “safe” forever.

3. Designing the Graphical Interface

To make our file encryption tool more convenient to use, we will design a simple graphical interface using Java’s Swing library.

  1. Create a main window, set the window title, size, and layout.
  2. Add a file selection button to facilitate selecting files to encrypt or decrypt.
  3. Add a key input box for entering the key required for encryption or decryption.
  4. Add encrypt and decrypt buttons to trigger the corresponding encryption or decryption operations when clicked.

Here is a simple example code:

 1import javax.swing.*;
 2import java.awt.*;
 3import java.awt.event.ActionEvent;
 4import java.awt.event.ActionListener;
 5import java.io.File;
 6
 7public class FileEncryptionGUI extends JFrame {
 8    private JTextField filePathTextField;
 9    private JTextField keyTextField;
10    private JButton selectFileButton;
11    private JButton encryptButton;
12    private JButton decryptButton;
13
14    public FileEncryptionGUI() {
15        setTitle("File Encryption Tool");
16        setSize(400, 300);
17        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18        setLayout(new FlowLayout());
19
20        filePathTextField = new JTextField(20);
21        keyTextField = new JTextField(20);
22        selectFileButton = new JButton("Select File");
23        encryptButton = new JButton("Encrypt");
24        decryptButton = new JButton("Decrypt");
25
26        selectFileButton.addActionListener(new ActionListener() {
27            @Override
28            public void actionPerformed(ActionEvent e) {
29                JFileChooser fileChooser = new JFileChooser();
30                int result = fileChooser.showOpenDialog(FileEncryptionGUI.this);
31                if (result == JFileChooser.APPROVE_OPTION) {
32                    File selectedFile = fileChooser.getSelectedFile();
33                    filePathTextField.setText(selectedFile.getAbsolutePath());
34                }
35            }
36        });
37
38        encryptButton.addActionListener(new ActionListener() {
39            @Override
40            public void actionPerformed(ActionEvent e) {
41                String filePath = filePathTextField.getText();
42                String keyText = keyTextField.getText();
43                if (!filePath.isEmpty() &amp;&amp;!keyText.isEmpty()) {
44                    try {
45                        File inputFile = new File(filePath);
46                        File outputFile = new File(filePath + ".encrypted");
47                        SecretKey key = new javax.crypto.spec.SecretKeySpec(keyText.getBytes(), "AES");
48                        FileEncryptionUtil.encryptFile(inputFile, outputFile, key);
49                        JOptionPane.showMessageDialog(FileEncryptionGUI.this, "File encrypted successfully!");
50                    } catch (Exception ex) {
51                        ex.printStackTrace();
52                        JOptionPane.showMessageDialog(FileEncryptionGUI.this, "File encryption failed!");
53                    }
54                } else {
55                    JOptionPane.showMessageDialog(FileEncryptionGUI.this, "Please select a file and enter a key!");
56                }
57            }
58        });
59
60        decryptButton.addActionListener(new ActionListener() {
61            @Override
62            public void actionPerformed(ActionEvent e) {
63                String filePath = filePathTextField.getText();
64                String keyText = keyTextField.getText();
65                if (!filePath.isEmpty() &amp;&amp;!keyText.isEmpty()) {
66                    try {
67                        File inputFile = new File(filePath);
68                        File outputFile = new File(filePath.replace(".encrypted", ""));
69                        SecretKey key = new javax.crypto.spec.SecretKeySpec(keyText.getBytes(), "AES");
70                        FileEncryptionUtil.decryptFile(inputFile, outputFile, key);
71                        JOptionPane.showMessageDialog(FileEncryptionGUI.this, "File decrypted successfully!");
72                    } catch (Exception ex) {
73                        ex.printStackTrace();
74                        JOptionPane.showMessageDialog(FileEncryptionGUI.this, "File decryption failed!");
75                    }
76                } else {
77                    JOptionPane.showMessageDialog(FileEncryptionGUI.this, "Please select a file and enter a key!");
78                }
79            }
80        });
81
82        add(new JLabel("File Path:"));
83        add(filePathTextField);
84        add(selectFileButton);
85        add(new JLabel("Key:"));
86        add(keyTextField);
87        add(encryptButton);
88        add(decryptButton);
89
90        setVisible(true);
91    }
92
93    public static void main(String[] args) {
94        new FileEncryptionGUI();
95    }
96}

In this code, the <span>FileEncryptionGUI</span> class extends <span>JFrame</span>, creating a simple graphical interface. Users can select the file to operate on by clicking the “Select File” button, enter the key in the “Key” input box, and then click the “Encrypt” or “Decrypt” button to perform the corresponding operation. A message box will pop up to inform the user of the success or failure of the operation.

Notes: When using the graphical interface, pay attention to checking the validity of user input, such as whether the file path is correct and whether the key meets the requirements, to avoid program errors due to incorrect user input. Also, pay attention to the layout of the interface to make it look clean and beautiful, facilitating user operation.

Friends, today we learned the basic steps to create a desktop file encryption tool with Java, including development preparation, encryption algorithm implementation, and graphical interface design. Hurry up and practice, applying what you have learned. If you have any questions during the process, feel free to reach out to me in the comments. I wish everyone a successful journey in Java development, creating more practical tools!

Leave a Comment