Encryption/Decryption Using AES Algorithm Example

๐Ÿ” AES Encryption and Decryption in Java — Step-by-Step Example

In modern applications, data security is crucial — especially when handling sensitive information like passwords, tokens, or financial data.
One of the most widely used symmetric encryption techniques is AES (Advanced Encryption Standard).

This post explains how to encrypt and decrypt data using AES in Java, with a simple working example.


๐Ÿงฉ What is AES?

AES (Advanced Encryption Standard) is a symmetric key algorithm, meaning:

  • The same key is used for both encryption and decryption.

  • It provides strong security, fast performance, and is standardized by NIST.

It supports key sizes of:

  • 128 bits (16 bytes)

  • 192 bits (24 bytes)

  • 256 bits (32 bytes)

For most cases, AES-128 offers a strong balance of speed and security.


⚙️ Step 1 — Create the AES Encryption Class

package com.vinod.test; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; /** * Simple example demonstrating AES encryption and decryption in Java. * * Uses javax.crypto package for symmetric key encryption. * * @author vinod */ public class AESEncryptionTest { // Key used for both encryption and decryption (must be 16 bytes for AES-128) static String keyString = "Pretec_SecretKeu"; // 16 characters = 128 bits public static void main(String[] args) { String plainText = "Hello world"; // Encrypt the message byte[] encryptedValue = encrypt(keyString, plainText); System.out.println("Encrypted Value (raw bytes): " + encryptedValue); // Decrypt the message String decryptedValue = decrypt(keyString, encryptedValue); System.out.println("Decrypted Value: " + decryptedValue); } /** * Encrypts the given text using AES algorithm. * * @param keyString Secret key string (16/24/32 bytes) * @param msg Text to encrypt * @return Encrypted bytes */ public static byte[] encrypt(String keyString, String msg) { byte[] byteCipherText = null; try { SecretKey secKey = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES"); Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.ENCRYPT_MODE, secKey); byteCipherText = aesCipher.doFinal(msg.getBytes()); System.out.println("✅ Encryption completed successfully."); } catch (Exception e) { e.printStackTrace(); } return byteCipherText; } /** * Decrypts AES-encrypted data using the same key. * * @param keyString Secret key string (same as used for encryption) * @param cipherBytes Encrypted message bytes * @return Decrypted plain text */ public static String decrypt(String keyString, byte[] cipherBytes) { byte[] bytePlainText = null; try { SecretKey secKey = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES"); Cipher aesCipher = Cipher.getInstance("AES"); aesCipher.init(Cipher.DECRYPT_MODE, secKey); bytePlainText = aesCipher.doFinal(cipherBytes); System.out.println("✅ Decryption completed successfully."); } catch (Exception e) { e.printStackTrace(); } return new String(bytePlainText); } }

๐Ÿงพ Output

✅ Encryption completed successfully. Encrypted Value (raw bytes): [B@2fc14f68 ✅ Decryption completed successfully. Decrypted Value: Hello world

๐Ÿ’ก Note: The encrypted output [B@2fc14f68 represents a byte array’s memory address, not the actual encrypted text.
To see the readable Base64-encoded value, you can modify the print statement as shown below.


๐Ÿงฑ Step 2 — Display the Encrypted Text in Base64 (Optional)

To view or store the encrypted data safely (for logging or transmission), convert it to Base64:

import java.util.Base64; String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedValue); System.out.println("Encrypted (Base64): " + encryptedBase64);

And when decrypting:

byte[] decodedBytes = Base64.getDecoder().decode(encryptedBase64); String decryptedValue = decrypt(keyString, decodedBytes);

Output:

Encrypted (Base64): p7pE8zS44vbl/2YNN5wT2g== Decrypted Value: Hello world

๐Ÿง  How It Works — Step by Step

Here’s what happens under the hood:

1️⃣ Convert key string16-byte key (SecretKeySpec) 2️⃣ Initialize AES Cipher in ENCRYPT_MODE 3️⃣ Encrypt plain textbyte array 4️⃣ Initialize Cipher in DECRYPT_MODE with same key 5️⃣ Decrypt byte array → original plain text

๐Ÿงฉ Text-Based Flow

[Plain Text: "Hello world"](AES Encrypt) [Cipher Bytes: p7pE8zS44vbl/2YNN5wT2g==](AES Decrypt) [Plain Text: "Hello world"]

๐Ÿ”’ Key Points to Remember

ConceptDescription
AlgorithmAES (Advanced Encryption Standard)
TypeSymmetric key (same key for encryption & decryption)
Key Sizes128, 192, or 256 bits
Cipher Mode Used"AES" (defaults to ECB mode)
EncodingUse Base64 for readable output
Security NoteFor real-world security, use "AES/CBC/PKCS5Padding" or "AES/GCM/NoPadding" instead of plain "AES" (ECB)
 

No comments:

Post a Comment

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts