List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Implement MD5 Encryption and Decryption of a Text File using Java?

Encrypt and Decrypt Text File using MD5 in Java

Condition for Encrypt and Decrypt Text File using MD5 in Java

  • Description:
    MD5 (Message-Digest Algorithm 5) is a widely used cryptographic hash function that produces a fixed 128-bit hash value from an input message, regardless of its size. It transforms data into a unique, irreversible hash, ensuring integrity by detecting any changes made to the original file. MD5 is commonly used for checksums, digital signatures, and verifying file integrity but does not provide encryption or decryption in the traditional sense.


    The MessageDigest class handles MD5 hashing. To hash a file, read the file’s content as bytes, pass the data to the MessageDigest instance initialized with the "MD5" algorithm, and generate the hash. The output is a byte array that represents the unique hash value of the file. This hash can be encoded as a hexadecimal string for easier storage or comparison.

    Since MD5 produces a one-way hash, reversing it to retrieve the original data is not possible. It serves as a tool for integrity verification rather than data encryption. Although MD5 remains widely used, its vulnerability to collision attacks limits its application in security-critical environments. For stronger security, consider using modern alternatives like SHA-256.

    In file verification processes, compare the computed hash of the file with a previously stored hash to detect tampering or corruption. Properly handling file input and output streams ensures efficient processing and minimizes resource usage. Despite its limitations, MD5 remains useful in scenarios where speed and file integrity checks take precedence over strong cryptographic security.
Sample Code
  • Encryption:
    package hashFunction;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.security.MessageDigest;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    public class MD5_Encryption extends javax.swing.JFrame {
    private int result;
    SecretKey secretKey;
    private String keyPath = "/home/soft20/NetBeansProjects/MD5/client_key.key";
    public MD5_Encryption() {
    initComponents();
    try {
    String password = "myStrongPassword";
    secretKey = generateKeyFromSHA256(password);
    saveKeyToFile(secretKey, keyPath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    @SuppressWarnings("unchecked")
    private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jButton4 = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setText("MD5_Encryption");
    jLabel2.setText("File Path");
    jButton1.setText("Choose File");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });
    jLabel3.setText("File Path");
    jButton2.setText("Choose File");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    });
    jButton3.setText("ENCRYPT");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
    }
    });
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    jButton4.setText("SecretKey");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton4ActionPerformed(evt);
    }
    });
    pack();
    }
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField1.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField1.setText("No File Selected ");
    }
    }
    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    result = fileChooser.showOpenDialog(this);
    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField2.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField2.setText("No File Selected ");
    }
    }
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    String inputFilePath = jTextField1.getText();
    String outputFilePath = jTextField2.getText();
    try {
    encrypt(inputFilePath, outputFilePath, secretKey);
    JOptionPane.showMessageDialog(this, "File encrypted successfully.");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
    display();
    }
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
    new MD5_Encryption().setVisible(true);
    });
    }
    private void encrypt(String inputFilePath, String outputFilePath, SecretKey secretKey) {
    try {
    byte[] plainText = readFile(inputFilePath);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] encryptedData = cipher.doFinal(plainText);
    try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
    fos.write(encryptedData);
    fos.flush();
    }
    System.out.println("Encryption successful. Encrypted text saved to: " + outputFilePath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    private void display() {
    try {
    byte[] publicKeyBytes = secretKey.getEncoded();
    String res = Base64.getEncoder().encodeToString(publicKeyBytes);
    jTextArea1.setText(res);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }
    private byte[] readFile(String inputFilePath) throws Exception {
    File file = new File(inputFilePath);
    byte[] data = new byte[(int) file.length()];
    try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(data);
    }
    return data;
    }
    private SecretKey generateKeyFromSHA256(String password) throws Exception {
    MessageDigest sha = MessageDigest.getInstance("MD5");
    byte[] keyBytes = sha.digest(password.getBytes());
    return new SecretKeySpec(keyBytes, 0, 16, "AES");
    }
    private void saveKeyToFile(SecretKey secretKey, String keyPath) throws Exception {
    byte[] encodedKey = Base64.getEncoder().encode(secretKey.getEncoded());
    try (FileOutputStream fos = new FileOutputStream(keyPath)) {
    fos.write(encodedKey);
    System.out.println("Secret key saved to: " + keyPath);
    }
    }
    }
  • Decryption:
    package hashFunction;

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.FileReader;
    import java.util.Base64;
    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;

    public class MD5_Decryption extends javax.swing.JFrame {

    private int result;
    SecretKey clientSecretKey;
    private String keyPath = "/home/soft20/NetBeansProjects/MD5/client_key.key";

    public MD5_Decryption() {
    initComponents();
    clientSecretKey = loadKeyFromFile(keyPath);
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jButton4 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("MD5_Decryption");

    jLabel2.setText("File Path");

    jButton1.setText("Choose File");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });

    jLabel3.setText("File Path");

    jButton2.setText("Choose File");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    });

    jButton3.setText("DECRYPT");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
    }
    });

    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);

    jButton4.setText("SecretKey");
    jButton4.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton4ActionPerformed(evt);
    }
    });

    pack();
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    result = fileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField1.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField1.setText("No File Selected ");
    }
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setDialogTitle("Choose a file");
    result = fileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
    File selectedFile = fileChooser.getSelectedFile();
    jTextField2.setText(selectedFile.getAbsolutePath());
    } else {
    jTextField2.setText("No File Selected ");
    }
    }

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    String inputFilePath = jTextField1.getText();
    String outputFilePath = jTextField2.getText();

    try {
    decrypt(inputFilePath, outputFilePath, clientSecretKey);
    JOptionPane.showMessageDialog(this, "File decrypted successfully.");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    private void display() {
    try {
    byte[] publicKeyBytes = clientSecretKey.getEncoded();
    String res = Base64.getEncoder().encodeToString(publicKeyBytes);
    jTextArea1.setText(res);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    private void decrypt(String inputFilePath, String outputFilePath, SecretKey clientSecretKey) {
    try {
    byte[] encryptedData = readFile(inputFilePath);
    Cipher cipher = Cipher.getInstance("AES");
    cipher.init(Cipher.DECRYPT_MODE, clientSecretKey);
    byte[] decryptedData = cipher.doFinal(encryptedData);

    try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
    fos.write(decryptedData);
    }

    System.out.println("Decryption complete. Decrypted data saved to " + outputFilePath);
    } catch (Exception e) {
    System.out.println(e.getMessage());
    }
    }

    private byte[] readFile(String inputFilePath) throws Exception {
    File file = new File(inputFilePath);
    byte[] data = new byte[(int) file.length()];
    try (FileInputStream fis = new FileInputStream(file)) {
    fis.read(data);
    }
    return data;
    }

    private SecretKey loadKeyFromFile(String keyPath) {
    try (BufferedReader reader = new BufferedReader(new FileReader(keyPath))) {
    String base64Key = reader.readLine();
    byte[] decodedKey = Base64.getDecoder().decode(base64Key);
    return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    } catch (Exception e) {
    JOptionPane.showMessageDialog(this, "Error loading secret key: " + e.getMessage());
    return null;
    }
    }
    }
Step 1
  • To start the encryption process, select the input file path after setting up the MD5 encryption GUI.
  • Encrypt and Decrypt data using md51
  • Encrypt and Decrypt data using md52
Step 2
  • The chosen file location is indicated by the selected file path that shows up in the text field.
  • Encrypt and Decrypt data using md53
Step 3
  • Select the path of the 'Encrypt.txt' file to begin the encryption process.
  • Encrypt and Decrypt data using md54
Step 4
  • The path of the 'Encrypt.txt' file has been selected for encryption.
  • Encrypt and Decrypt data using md55
Step 5
  • The encrypt method reads the plain text from an input file, uses AES encryption with the provided secret key, and writes the encrypted data to an output file. It initializes the AES cipher in encryption mode and applies the doFinal method to encrypt the data. If successful, it saves the encrypted content to the specified output file and prints a confirmation message.
  • Encrypt and Decrypt data using md56
Step 6
  • To start the decryption process, select the input file path after setting up the MD5 decryption GUI.
  • Encrypt and Decrypt data using md57
  • Encrypt and Decrypt data using md58
Step 7
  • The chosen file location is indicated by the selected file path that shows up in the text field.
  • Encrypt and Decrypt data using md59
Step 8
  • Select the path of the 'Decrypt.txt' file to begin the decryption process.
  • Encrypt and Decrypt data using md510
Step 9
  • The path of the 'Decrypt.txt' file has been selected for decryption.
  • Encrypt and Decrypt data using md511
Step 10
  • The decrypt method reads the encrypted data from an input file, uses AES decryption with the provided secret key, and saves the decrypted content to an output file. It initializes the AES cipher in decryption mode and applies the doFinal method to decrypt the data. The decrypted content is then written to the specified output file. A success message is displayed once the decryption is complete.
  • Read Encrypted File: The readFile method reads the entire content of a file at Encrypted text file path and returns it as a byte array. It uses Files.readAllBytes() for efficient reading, handling file input as a stream of bytes.
  • Encrypt and Decrypt data using md512
Step 11
  • To incorporate a secret key with MD5, combine the key with the input data before hashing, creating an HMAC (Hash-Based Message Authentication Code) for added integrity and authenticity.
  • Encrypt and Decrypt data using md513
  • Encrypt and Decrypt data using md514
  • Encrypt and Decrypt data using md515
Step 12
  • Encryption applies to the input text file, with the result saved in the encrypt text file. Decryption restores the original content from the decrypt text file.
  • Encrypt and Decrypt data using md516
  • Encrypt and Decrypt data using md517
  • Encrypt and Decrypt data using md518