๐Ÿ” How to Encrypt and Decrypt Messages and Files in Java using AES

PrajwalPrajwal
7 min read

In a world where data security is more crucial than ever, understanding encryption is not just a โ€œdeveloper nice-to-haveโ€โ€”itโ€™s a must. Whether you're working on a personal project, a fintech app, or a medical records platform, securing user data should be top priority.

In this blog, we'll take a hands-on journey into AES encryption and decryption using pure Java. You'll learn the what, why, and howโ€”backed with runnable code and clear examples.

Letโ€™s get started.


๐Ÿ” Introduction: What is Encryption?

Imagine you're writing a letter to a friend, but you don't want anyone else to read it. So, you scramble the letters using a secret code that only your friend understands. Thatโ€™s encryption in its simplest form.

In the digital world, encryption serves the same purpose. It converts readable data (plain text) into an unreadable format (cipher text) using a special secret called a key. This ensures that even if someone intercepts the data, they canโ€™t make sense of it without the key. The process of turning unreadable/cipher text back into plain text is called decryption.

๐Ÿ” Encryption = Locking the message
๐Ÿ”“ Decryption = Unlocking the message using the right key

Why is encryption important?

Encryption is one of the pillars of modern cybersecurity. Hereโ€™s why it matters:

  • ๐Ÿ›ก๏ธ Data Protection: Keeps sensitive information (like passwords, credit cards, and personal files) safe from unauthorized access.

  • ๐Ÿ”„ Data Integrity: Helps detect tampering. If encrypted/cipher data is changed in transit, it often becomes undecryptable.

  • ๐Ÿ” Secure Communication: Enables safe data transfer between users, devices, or systems (e.g., HTTPS, messaging apps, VPNs).

  • โš–๏ธ Compliance: Many industries (finance, healthcare, education) legally require data encryption to protect customer information.

Whether youโ€™re securing a login form or saving user files on the server, encryption adds a critical layer of protection.


๐Ÿ” What is AES?

AES stands for Advanced Encryption Standard, and it's one of the most widely used encryption algorithms in the world today. It was established by the U.S. National Institute of Standards and Technology (NIST) and is used in everything from military-grade communications to online banking.

๐Ÿ”‘ How does AES work?

AES is a symmetric encryption algorithm. This means:

  • The same key is used to both encrypt and decrypt data.

  • If someone has the key, they can unlock the message. If not, it remains gibberish.

Unlike older encryption methods like DES (which had security flaws), AES is considered very secure and efficient. It works on blocks of data (called block cipher), processing fixed chunksโ€”usually 128 bits at a time.

For more details of Symmetric and Asymetric encryption read this.

๐Ÿ” AES Key Sizes

AES supports three key sizes:

  • 128-bit key โ€” fast and secure (good for most uses)

  • 192-bit key โ€” stronger security, slightly slower

  • 256-bit key โ€” strongest option, used when ultra-security is needed

For this blog, weโ€™ll use a 128-bit key, which is more than enough for most applications, and easier to work with.

๐Ÿ”’ Why use AES?

  • Symmetric = Simple: You donโ€™t need complex public-private key infrastructure (like in RSA).

  • Fast & Lightweight: Ideal for encrypting both small messages and large files.

  • Widely Supported: Almost every programming language and framework supports AES out of the box.

  • Battle-tested: Trusted by governments, enterprises, and security experts globally.

๐Ÿ“ฆ Simple Example:

Let's say you want to send this message:

"HELLO"

AES will turn it into something like:

"X5#9Z"

Only someone with the correct key can turn "X5#9Z" back into "HELLO".

๐Ÿ“Œ AES encryption is used in technologies like HTTPS, disk encryption tools (BitLocker, VeraCrypt), encrypted messaging apps, and more.


๐Ÿงช Prerequisites

  • Basic Java knowledge

  • JDK 17+ (or 11+)

  • Maven (or any Java build tool)

  • An IDE or terminal


๐Ÿ› ๏ธ Practical Implementation

Letโ€™s build a simple Java Maven project where we:

  • Generate a secret key

  • Encrypt and decrypt a message

  • Encrypt and decrypt a file


๐Ÿ“ Step 1: Create a Maven Project

Create a folder for your project and structure it like this:

aes-encryption-java/
โ”œโ”€โ”€ src/
โ”‚   โ””โ”€โ”€ main/
โ”‚       โ””โ”€โ”€ java/
โ”‚           โ””โ”€โ”€ com/
โ”‚               โ””โ”€โ”€ myproject/
โ”‚                   โ””โ”€โ”€ crypto/
โ”‚                       โ”œโ”€โ”€ AesEncryptor.java
โ”‚                       โ”œโ”€โ”€ SecretKeyGenerator.java
โ”‚                       โ””โ”€โ”€ Main.java
โ”œโ”€โ”€ pom.xml

๐Ÿ“ฆ Step 2: Add dependencies

In your pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.myproject</groupId>
    <artifactId>aes-encryption-java</artifactId>
    <version>1.0</version>
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
</project>

๐Ÿ” Step 3: Generate a Secret Key

package com.myproject.crypto;

import java.security.SecureRandom;
import java.util.Base64;

public class SecretKeyGenerator {
    public static void main(String[] args) {
        // Create a 128-bit (16 bytes) random key
        byte[] key = new byte[16];

        // SecureRandom provides a cryptographically strong random number generator
        new SecureRandom().nextBytes(key);

        // Print the Base64-encoded version of the key for easier storage and use
        System.out.println("Generated Key (Base64): " + Base64.getEncoder().encodeToString(key));
    }
}

This will output a random Base64-encoded 128-bit AES key.

Example:


๐Ÿ”„ Step 4: AES Utility for Encryption/Decryption

package com.myproject.crypto;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.util.Base64;

public class AesEncryptor {

    // Encrypts a String using AES and returns the result in Base64 format
    public static String encrypt(String input, String base64Key) throws Exception {
        byte[] key = Base64.getDecoder().decode(base64Key); // Decode Base64 key
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES"); // Create AES key spec

        Cipher cipher = Cipher.getInstance("AES"); // AES/ECB/PKCS5Padding by default
        cipher.init(Cipher.ENCRYPT_MODE, secretKey); // Initialize cipher for encryption

        byte[] encrypted = cipher.doFinal(input.getBytes()); // Perform encryption
        return Base64.getEncoder().encodeToString(encrypted); // Encode result to Base64
    }

    // Decrypts a Base64-encoded AES-encrypted string
    public static String decrypt(String encryptedBase64, String base64Key) throws Exception {
        byte[] key = Base64.getDecoder().decode(base64Key);
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedBase64)); // Decrypt
        return new String(decrypted); // Convert bytes to original String
    }

    // Encrypts a file using AES
    public static void encryptFile(File inputFile, File outputFile, String base64Key) throws Exception {
        processFile(Cipher.ENCRYPT_MODE, inputFile, outputFile, base64Key);
    }

    // Decrypts a previously encrypted file
    public static void decryptFile(File inputFile, File outputFile, String base64Key) throws Exception {
        processFile(Cipher.DECRYPT_MODE, inputFile, outputFile, base64Key);
    }

    // Common file processing method for both encryption and decryption
    private static void processFile(int mode, File in, File out, String base64Key) throws Exception {
        byte[] key = Base64.getDecoder().decode(base64Key);
        SecretKeySpec secretKey = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(mode, secretKey);

        try (FileInputStream fis = new FileInputStream(in);
             FileOutputStream fos = new FileOutputStream(out)) {

            byte[] inputBytes = fis.readAllBytes(); // Read all input bytes
            byte[] outputBytes = cipher.doFinal(inputBytes); // Encrypt or decrypt

            fos.write(outputBytes); // Write the result to output file
        }
    }
}

โ–ถ๏ธ Step 5: Test It

package com.myproject.crypto;

import java.io.File;

public class Main {
    public static void main(String[] args) throws Exception {
        // Replace with your generated Base64 key
        String secretKey = "your-generated-base64-key"; //Example: "22EbiI6nJ8PEqLazPdw1PA=="

        // Test data
        String originalText = "This is a secret message.";
        System.out.println("Original: " + originalText);

        // Encrypt string
        String encrypted = AesEncryptor.encrypt(originalText, secretKey);
        System.out.println("Encrypted: " + encrypted);

        // Decrypt string
        String decrypted = AesEncryptor.decrypt(encrypted, secretKey);
        System.out.println("Decrypted: " + decrypted);

        // Files for encryption
        File input = new File("secret.txt");
        File encryptedFile = new File("secret.txt.aes");
        File decryptedFile = new File("secret-decrypted.txt");

        // Encrypt the file
        AesEncryptor.encryptFile(input, encryptedFile, secretKey);
        System.out.println("File encrypted: " + encryptedFile.getAbsolutePath());

        // Decrypt the file
        AesEncryptor.decryptFile(encryptedFile, decryptedFile, secretKey);
        System.out.println("File decrypted: " + decryptedFile.getAbsolutePath());
    }
}

๐Ÿ“ Make sure secret.txt contains some text before running.


โš ๏ธ Important Notes

  • AES encryption is only as secure as your secret key. Store it securely (never hardcode in real apps).

  • Always handle exceptions gracefully in production.

  • For stronger security, consider AES with IV (Initialization Vector) and GCM mode.


โœ… Conclusion

We just walked through encrypting and decrypting data (both strings and files) using AES in a pure Java project. No frameworks, no Spring Bootโ€”just clean, understandable Java.

๐Ÿ”’ Want to see how this concept is applied in a real Spring Boot backend app?

๐Ÿ‘‰ Check out this GitHub project where Iโ€™m building a Personal Data Vault using Spring Boot, JWT, file storage, and AES encryption.

If you liked this tutorial, give it a ๐Ÿ’™ and follow for more deep dives like this!

1
Subscribe to my newsletter

Read articles from Prajwal directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Prajwal
Prajwal

Software Developer at HCL Infosystems Ltd.| Blockchain Trainer| Java| Spring Boot| Blockchain| Ethereum| Solidity| Bassist| Guitarist